@stencil/core 5.0.0-alpha.32 → 5.0.0-alpha.33

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 (34) hide show
  1. package/dist/app-data/index.d.ts +1 -1
  2. package/dist/app-data/index.js +2 -0
  3. package/dist/client-Bqq2Agpl.mjs +2367 -0
  4. package/dist/compiler/index.d.mts +1 -1
  5. package/dist/compiler/index.mjs +2 -3
  6. package/dist/compiler/utils/index.d.mts +1 -1
  7. package/dist/compiler/utils/index.mjs +3 -3
  8. package/dist/{compiler-D2MlfN4O.mjs → compiler-DjwEWyq2.mjs} +470 -9
  9. package/dist/declarations/stencil-public-compiler.d.ts +20 -3
  10. package/dist/declarations/stencil-public-runtime.d.ts +10 -0
  11. package/dist/{regular-expression-XqU5zmPp.mjs → helpers-Cpp3qc3u.mjs} +12 -13
  12. package/dist/{index-BHj3EBl2.d.mts → index-BCm37iOm.d.mts} +40 -3
  13. package/dist/{index-D2PAsXxx.d.ts → index-BTVuF9UD.d.ts} +2 -0
  14. package/dist/{index-VK8okIiF.d.mts → index-C-fMSffa.d.mts} +2 -10
  15. package/dist/index.mjs +1 -1
  16. package/dist/jsx-runtime.mjs +1 -1
  17. package/dist/{node-DRT35FuO.mjs → node-DugJ2Vs2.mjs} +3 -3
  18. package/dist/runtime/client/lazy.js +13 -1
  19. package/dist/runtime/client/runtime.js +13 -1
  20. package/dist/runtime/index.d.ts +1 -1
  21. package/dist/runtime/index.js +13 -1
  22. package/dist/runtime/server/index.mjs +13 -1
  23. package/dist/runtime/server/runner.mjs +21 -3
  24. package/dist/signals/index.js +2 -0
  25. package/dist/sys/node/index.d.mts +1 -1
  26. package/dist/sys/node/index.mjs +1 -1
  27. package/dist/sys/node/worker.mjs +2 -2
  28. package/dist/testing/index.d.mts +4677 -100
  29. package/dist/testing/index.mjs +7553 -780
  30. package/dist/{util-BIa-iHnt.mjs → util-IKfWWLJo.mjs} +1 -1
  31. package/dist/{validation-Dd3g77T5.mjs → validation-DAdGTrys.mjs} +16 -3
  32. package/package.json +4 -4
  33. package/dist/client-C3HYn-8p.mjs +0 -4850
  34. package/dist/reactive-controller-BdCpSAQP.d.mts +0 -13
@@ -1,4850 +0,0 @@
1
- import { G as MEMBER_FLAGS, K as NODE_TYPES, Q as SVG_NS, R as EVENT_FLAGS, S as queryNonceMetaTagContent, U as LISTENER_FLAGS, V as HOST_FLAGS, c as isDef, s as isComplexType, t as escapeRegExpSpecialCharacters, tt as WATCH_FLAGS, w as CMP_FLAGS } from "./regular-expression-XqU5zmPp.mjs";
2
- import { effect, effect as effect$1, signal } from "@preact/signals-core";
3
- //#region src/app-data/index.ts
4
- /**
5
- * A collection of default build flags for a Stencil project.
6
- *
7
- * This collection can be found throughout the Stencil codebase, often imported from the `virtual:app-data` module like so:
8
- * ```ts
9
- * import { BUILD } from 'virtual:app-data';
10
- * ```
11
- * and is used to determine if a portion of the output of a Stencil _project_'s compilation step can be eliminated.
12
- *
13
- * e.g. When `BUILD.allRenderFn` evaluates to `false`, the compiler will eliminate conditional statements like:
14
- * ```ts
15
- * if (BUILD.allRenderFn) {
16
- * // some code that will be eliminated if BUILD.allRenderFn is false
17
- * }
18
- * ```
19
- *
20
- * `virtual:app-data`, the module that `BUILD` is imported from, is an alias for `@stencil/core/app-data`, and is
21
- * partially referenced by {@link STENCIL_APP_DATA_ID}. The `src/compiler/bundle/app-data-plugin.ts` references
22
- * `STENCIL_APP_DATA_ID` uses it to replace these defaults with {@link BuildConditionals} that are derived from a
23
- * Stencil project's contents (i.e. metadata from the components). This replacement happens at a Stencil project's
24
- * compile time. Such code can be found at `src/compiler/app-core/app-data.ts`.
25
- */
26
- const BUILD = {
27
- allRenderFn: false,
28
- element: true,
29
- event: true,
30
- hasRenderFn: true,
31
- hostListener: true,
32
- hostListenerTargetWindow: true,
33
- hostListenerTargetDocument: true,
34
- hostListenerTargetBody: true,
35
- hostListenerTarget: true,
36
- member: true,
37
- method: true,
38
- mode: true,
39
- observeAttribute: true,
40
- prop: true,
41
- propMutable: true,
42
- reflect: true,
43
- scoped: true,
44
- shadowDom: true,
45
- shadowModeClosed: false,
46
- slot: true,
47
- cssAnnotations: true,
48
- state: true,
49
- style: true,
50
- formAssociated: true,
51
- svg: true,
52
- updatable: true,
53
- vdomAttribute: true,
54
- vdomXlink: true,
55
- vdomClass: true,
56
- vdomFunctional: true,
57
- vdomKey: true,
58
- vdomListener: true,
59
- vdomRef: true,
60
- vdomPropOrAttr: true,
61
- vdomRender: true,
62
- vdomStyle: true,
63
- vdomText: true,
64
- propChangeCallback: true,
65
- taskQueue: true,
66
- lifecycle: true,
67
- serializer: true,
68
- deserializer: true,
69
- patchAll: true,
70
- patchChildren: true,
71
- patchClone: true,
72
- patchInsert: true,
73
- hotModuleReplacement: false,
74
- isDebug: false,
75
- isDev: false,
76
- isTesting: false,
77
- hydrateServerSide: false,
78
- hydrateClientSide: true,
79
- lifecycleDOMEvents: false,
80
- lazyLoad: false,
81
- profile: false,
82
- slotRelocation: true,
83
- lightDomPatches: true,
84
- slotChildNodes: true,
85
- slotCloneNode: true,
86
- slotDomMutations: true,
87
- slotTextContent: true,
88
- hydratedAttribute: false,
89
- hydratedClass: true,
90
- invisiblePrehydration: true,
91
- staticHydrationStyles: false,
92
- propBoolean: true,
93
- propNumber: true,
94
- propString: true,
95
- constructableCSS: true,
96
- devTools: false,
97
- shadowDelegatesFocus: true,
98
- shadowSlotAssignmentManual: false,
99
- initializeNextTick: false,
100
- asyncLoading: true,
101
- asyncQueue: false
102
- };
103
- const Env = {};
104
- //#endregion
105
- //#region src/client/client-build.ts
106
- const Build = {
107
- isDev: BUILD.isDev,
108
- isBrowser: true,
109
- isServer: false,
110
- isTesting: BUILD.isTesting
111
- };
112
- //#endregion
113
- //#region src/utils/get-prop-descriptor.ts
114
- /**
115
- * Walks up a prototype chain to find a property descriptor.
116
- * Stops before reaching native DOM prototypes (HTMLElement, etc.) to avoid
117
- * treating native properties like `hidden` as component-defined getters.
118
- * @param obj - The object to search on.
119
- * @param memberName - The name of the member to find.
120
- * @param getOnly - If true, only returns descriptors with a getter (i.e. ignores properties that are only fields or have setters without getters).
121
- * @returns The property descriptor if found, otherwise undefined.
122
- */
123
- function getPropertyDescriptor(obj, memberName, getOnly) {
124
- const stopAt = typeof HTMLElement !== "undefined" ? HTMLElement.prototype : null;
125
- while (obj && obj !== stopAt) {
126
- const desc = Object.getOwnPropertyDescriptor(obj, memberName);
127
- if (desc && (!getOnly || desc.get)) return desc;
128
- obj = Object.getPrototypeOf(obj);
129
- }
130
- }
131
- //#endregion
132
- //#region src/utils/es2022-rewire-class-members.ts
133
- /**
134
- * - Re-wires component prototype `get` / `set` with instance `@State` / `@Prop` decorated fields.
135
- * - Makes sure the initial value from the `Element` is synced to the instance `@Prop` decorated fields.
136
- *
137
- * Background:
138
- * During component init, Stencil loops through any `@Prop()` or `@State()` decorated properties
139
- * and sets up getters and setters for each (within `src/runtime/proxy-component.ts`) on a component prototype.
140
- *
141
- * These accessors sync-up class instances with their `Element` and controls re-renders.
142
- * With modern JS, compiled classes (e.g. `target: 'es2022'`) compiled Stencil components went from:
143
- *
144
- * ```ts
145
- * class MyComponent {
146
- * constructor() {
147
- * this.prop1 = 'value1';
148
- * }
149
- * }
150
- * ```
151
- * To:
152
- * ```ts
153
- * class MyComponent {
154
- * prop1 = 'value2';
155
- * // ^^ These override the accessors originally set on the prototype
156
- * }
157
- * ```
158
- *
159
- * @param instance - class instance to re-wire
160
- * @param hostRef - component reference meta
161
- */
162
- const reWireGetterSetter = (instance, hostRef) => {
163
- const cmpMeta = hostRef.$cmpMeta$;
164
- Object.entries(cmpMeta.$members$ ?? {}).map(([memberName, [memberFlags]]) => {
165
- if ((BUILD.state || BUILD.prop) && (memberFlags & MEMBER_FLAGS.Prop || memberFlags & MEMBER_FLAGS.State)) {
166
- const ogValue = instance[memberName];
167
- const ogDescriptor = getPropertyDescriptor(Object.getPrototypeOf(instance), memberName, true) || Object.getOwnPropertyDescriptor(instance, memberName);
168
- if (ogDescriptor) Object.defineProperty(instance, memberName, {
169
- get() {
170
- return ogDescriptor.get.call(this);
171
- },
172
- set(newValue) {
173
- ogDescriptor.set.call(this, newValue);
174
- },
175
- configurable: true,
176
- enumerable: true
177
- });
178
- if (hostRef.$instanceValues$.has(memberName)) instance[memberName] = hostRef.$instanceValues$.get(memberName);
179
- else if (ogValue !== void 0 && instance[memberName] !== ogValue) instance[memberName] = ogValue;
180
- }
181
- });
182
- };
183
- //#endregion
184
- //#region src/client/client-host-ref.ts
185
- /**
186
- * Given a {@link d.RuntimeRef} retrieve the corresponding {@link d.HostRef}
187
- *
188
- * @param ref the runtime ref of interest
189
- * @returns the Host reference (if found) or undefined
190
- */
191
- const getHostRef = (ref) => {
192
- if (ref.__s_ghr) return ref.__s_ghr();
193
- };
194
- /**
195
- * Register a host element for a Stencil component, setting up various metadata
196
- * and callbacks based on {@link BUILD} flags as well as the component's runtime
197
- * metadata.
198
- *
199
- * @param hostElement the host element to register
200
- * @param cmpMeta runtime metadata for that component
201
- * @returns a reference to the host ref WeakMap
202
- */
203
- const registerHost = (hostElement, cmpMeta) => {
204
- const hostRef = {
205
- $flags$: 0,
206
- $hostElement$: hostElement,
207
- $cmpMeta$: cmpMeta,
208
- $instanceValues$: /* @__PURE__ */ new Map(),
209
- $serializerValues$: /* @__PURE__ */ new Map()
210
- };
211
- if (BUILD.isDev) hostRef.$renderCount$ = 0;
212
- if (BUILD.method && BUILD.lazyLoad) hostRef.$onInstancePromise$ = new Promise((r) => hostRef.$onInstanceResolve$ = r);
213
- if (BUILD.asyncLoading) {
214
- hostRef.$onReadyPromise$ = new Promise((r) => hostRef.$onReadyResolve$ = r);
215
- hostElement["s-rp"] = hostRef.$onReadyPromise$;
216
- if (!BUILD.lazyLoad) {
217
- hostRef.$onFirstConnectPromise$ = new Promise((r) => hostRef.$onFirstConnectResolve$ = r);
218
- hostElement["s-fc"] = hostRef.$onFirstConnectPromise$;
219
- }
220
- if (!hostElement["s-p"]) hostElement["s-p"] = [];
221
- if (!hostElement["s-rc"]) hostElement["s-rc"] = [];
222
- if (!hostElement["s-pc"]) hostElement["s-pc"] = [];
223
- }
224
- if (BUILD.lazyLoad) hostRef.$fetchedCbList$ = [];
225
- const ref = hostRef;
226
- hostElement.__s_ghr = () => ref;
227
- if (!BUILD.lazyLoad && cmpMeta.$flags$ & CMP_FLAGS.hasModernPropertyDecls && (BUILD.state || BUILD.prop)) reWireGetterSetter(hostElement, hostRef);
228
- return ref;
229
- };
230
- const isMemberInElement = (elm, memberName) => memberName in elm;
231
- //#endregion
232
- //#region src/client/client-log.ts
233
- let customError;
234
- const consoleError = (e, el) => (customError || console.error)(e, el);
235
- const STENCIL_DEV_MODE = BUILD.isTesting ? ["STENCIL:"] : ["%cstencil", "color: white;background:#4c47ff;font-weight: bold; font-size:10px; padding:2px 6px; border-radius: 5px"];
236
- const consoleDevError = (...m) => console.error(...STENCIL_DEV_MODE, ...m);
237
- const consoleDevWarn = (...m) => console.warn(...STENCIL_DEV_MODE, ...m);
238
- const setErrorHandler = (handler) => customError = handler;
239
- //#endregion
240
- //#region src/client/client-load-module.ts
241
- const cmpModules = /*@__PURE__*/ new Map();
242
- /**
243
- * Tracks how many times a dynamic `import()` for a given lazy bundle has failed.
244
- * Used to cache bust the retry attempt in connected-callback.ts
245
- */
246
- const failedLoadAttempts = /*@__PURE__*/ new Map();
247
- /**
248
- * We need to separate out this prefix so that Esbuild doesn't try to resolve
249
- * the below, but instead retains a dynamic `import()` statement in the
250
- * emitted code.
251
- *
252
- * See here for details https://esbuild.github.io/api/#non-analyzable-imports
253
- *
254
- * We need to do this in order to prevent Esbuild from analyzing / transforming
255
- * the input. However some _other_ bundlers will _not_ work with such an import
256
- * if it _lacks_ a leading `"./"`, so we thus we have to do a little dance
257
- * where here in the source code it must be like this, so that an undesirable
258
- * transformation that Esbuild would otherwise carry out doesn't occur, but we
259
- * actually need to then manually edit the bundled Esbuild code later on to fix
260
- * that. We do this with plugins in the Esbuild and Rolldown bundles which
261
- * include this file.
262
- */
263
- const MODULE_IMPORT_PREFIX = "./";
264
- const loadModule = (cmpMeta, hostRef, hmrVersionId) => {
265
- const exportName = cmpMeta.$tagName$.replace(/-/g, "_");
266
- const bundleId = cmpMeta.$lazyBundleId$;
267
- if (BUILD.isDev && typeof bundleId !== "string") {
268
- consoleDevError(`Trying to lazily load component <${cmpMeta.$tagName$}> with style mode "${hostRef.$modeName$}", but it does not exist.`);
269
- return;
270
- } else if (!bundleId) return;
271
- const module = !BUILD.hotModuleReplacement ? cmpModules.get(bundleId) : false;
272
- if (module) return module[exportName];
273
- const retryCount = failedLoadAttempts.get(bundleId) ?? 0;
274
- const cacheBustParams = [retryCount > 0 ? `s-retry=${retryCount}` : "", BUILD.hotModuleReplacement && hmrVersionId ? `s-hmr=${hmrVersionId}` : ""].filter(Boolean).join("&");
275
- /*!__STENCIL_STATIC_IMPORT_SWITCH__*/
276
- const entryFile = `${bundleId}.entry.js${cacheBustParams ? "?" + cacheBustParams : ""}`;
277
- const onLoad = (importedModule) => {
278
- if (!BUILD.hotModuleReplacement) {
279
- failedLoadAttempts.delete(bundleId);
280
- cmpModules.set(bundleId, importedModule);
281
- }
282
- return importedModule[exportName];
283
- };
284
- const onError = (e) => {
285
- failedLoadAttempts.set(bundleId, retryCount + 1);
286
- consoleError(e, hostRef.$hostElement$);
287
- };
288
- return import(
289
- /* @vite-ignore */
290
- /* webpackInclude: /\.entry\.js$/ */
291
- /* webpackExclude: /\.system\.entry\.js$/ */
292
- /* webpackMode: "lazy" */
293
- `${MODULE_IMPORT_PREFIX}${entryFile}`
294
- ).then(onLoad, onError);
295
- };
296
- //#endregion
297
- //#region src/client/client-style.ts
298
- const styles = /*@__PURE__*/ new Map();
299
- const modeResolutionChain = [];
300
- const needsScopedSSR = () => false;
301
- //#endregion
302
- //#region src/runtime/runtime-constants.ts
303
- /**
304
- * Bit flags for recording various properties of VDom nodes
305
- */
306
- const VNODE_FLAGS = {
307
- /**
308
- * Whether or not a vdom node is a slot reference
309
- */
310
- isSlotReference: 1,
311
- /**
312
- * Whether or not a slot element has fallback content
313
- */
314
- isSlotFallback: 2,
315
- /**
316
- * Whether or not an element is a host element
317
- */
318
- isHost: 4
319
- };
320
- const PROXY_FLAGS = {
321
- isElementConstructor: 1,
322
- proxyState: 2
323
- };
324
- const PLATFORM_FLAGS = {
325
- /**
326
- * designates a node in the DOM as being actively moved by the runtime
327
- */
328
- isTmpDisconnected: 1,
329
- appLoaded: 2,
330
- queueSync: 4,
331
- queueMask: 6
332
- };
333
- /**
334
- * A (subset) of node types which are relevant for the Stencil runtime. These
335
- * values are based on the values which can possibly be returned by the
336
- * `.nodeType` property of a DOM node. See here for details:
337
- *
338
- * {@link https://dom.spec.whatwg.org/#ref-for-dom-node-nodetype%E2%91%A0}
339
- */
340
- const NODE_TYPE = {
341
- ElementNode: 1,
342
- TextNode: 3,
343
- CommentNode: 8,
344
- DocumentNode: 9,
345
- DocumentTypeNode: 10,
346
- DocumentFragment: 11
347
- };
348
- const HYDRATE_ID = "s-id";
349
- const HYDRATED_STYLE_ID = "sty-id";
350
- const HYDRATE_CHILD_ID = "c-id";
351
- const HYDRATED_CSS = "{visibility:hidden}.hydrated{visibility:inherit}";
352
- const STENCIL_DOC_DATA = "_stencilDocData";
353
- const DEFAULT_DOC_DATA = {
354
- hostIds: 0,
355
- rootLevelIds: 0,
356
- staticComponents: /* @__PURE__ */ new Set()
357
- };
358
- /**
359
- * Constant for styles to be globally applied to `slot-fb` elements for pseudo-slot behavior.
360
- *
361
- * Two cascading rules must be used instead of a `:not()` selector due to Stencil browser
362
- * support as of Stencil v4.
363
- */
364
- const SLOT_FB_CSS = "slot-fb{display:contents}slot-fb[hidden]{display:none}";
365
- const XLINK_NS = "http://www.w3.org/1999/xlink";
366
- /**
367
- * Minimum delay, in milliseconds, before retrying a failed lazy component load.
368
- */
369
- const LAZY_LOAD_RETRY_INTERVAL_MS = 1e3;
370
- const FORM_ASSOCIATED_CUSTOM_ELEMENT_CALLBACKS = [
371
- "formAssociatedCallback",
372
- "formResetCallback",
373
- "formDisabledCallback",
374
- "formStateRestoreCallback"
375
- ];
376
- //#endregion
377
- //#region src/client/client-window.ts
378
- const win = typeof window !== "undefined" ? window : {};
379
- win.HTMLElement;
380
- const plt = {
381
- $flags$: 0,
382
- $resourcesUrl$: "",
383
- jmp: (h) => h(),
384
- raf: (h) => requestAnimationFrame(h),
385
- ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts),
386
- rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts),
387
- ce: (eventName, opts) => new CustomEvent(eventName, opts)
388
- };
389
- const setPlatformHelpers = (helpers) => {
390
- Object.assign(plt, helpers);
391
- };
392
- const supportsListenerOptions = /*@__PURE__*/ (() => {
393
- let supported = false;
394
- try {
395
- win.document?.addEventListener("e", null, Object.defineProperty({}, "passive", { get() {
396
- supported = true;
397
- } }));
398
- } catch {}
399
- return supported;
400
- })();
401
- const promiseResolve = (v) => Promise.resolve(v);
402
- const supportsConstructableStylesheets = BUILD.constructableCSS ? /*@__PURE__*/ (() => {
403
- try {
404
- if (!win.document.adoptedStyleSheets) return false;
405
- return typeof new CSSStyleSheet().replaceSync === "function";
406
- } catch {}
407
- return false;
408
- })() : false;
409
- const supportsMutableAdoptedStyleSheets = supportsConstructableStylesheets ? /*@__PURE__*/ (() => !!win.document && Object.getOwnPropertyDescriptor(win.document.adoptedStyleSheets, "length").writable)() : false;
410
- //#endregion
411
- //#region src/client/client-task-queue.ts
412
- let queueCongestion = 0;
413
- let queuePending = false;
414
- const queueDomReads = [];
415
- const queueDomWrites = [];
416
- const queueDomWritesLow = [];
417
- const scheduleFlush = () => win.document?.hidden ? nextTick(flush) : plt.raf(flush);
418
- const queueTask = (queue, write) => (cb) => {
419
- queue.push(cb);
420
- if (!queuePending) {
421
- queuePending = true;
422
- if (write && plt.$flags$ & PLATFORM_FLAGS.queueSync) nextTick(flush);
423
- else scheduleFlush();
424
- }
425
- };
426
- const consume = (queue) => {
427
- for (let i = 0; i < queue.length; i++) try {
428
- queue[i](performance.now());
429
- } catch (e) {
430
- consoleError(e);
431
- }
432
- queue.length = 0;
433
- };
434
- const consumeTimeout = (queue, timeout) => {
435
- let i = 0;
436
- let ts = 0;
437
- while (i < queue.length && (ts = performance.now()) < timeout) try {
438
- queue[i++](ts);
439
- } catch (e) {
440
- consoleError(e);
441
- }
442
- if (i === queue.length) queue.length = 0;
443
- else if (i !== 0) queue.splice(0, i);
444
- };
445
- const flush = () => {
446
- if (BUILD.asyncQueue) queueCongestion++;
447
- consume(queueDomReads);
448
- if (BUILD.asyncQueue) {
449
- const timeout = (plt.$flags$ & PLATFORM_FLAGS.queueMask) === PLATFORM_FLAGS.appLoaded ? performance.now() + 14 * Math.ceil(queueCongestion * (1 / 10)) : Infinity;
450
- consumeTimeout(queueDomWrites, timeout);
451
- consumeTimeout(queueDomWritesLow, timeout);
452
- if (queueDomWrites.length > 0) {
453
- queueDomWritesLow.push(...queueDomWrites);
454
- queueDomWrites.length = 0;
455
- }
456
- if (queuePending = queueDomReads.length + queueDomWrites.length + queueDomWritesLow.length > 0) scheduleFlush();
457
- else queueCongestion = 0;
458
- } else {
459
- consume(queueDomWrites);
460
- if (queuePending = queueDomReads.length > 0) scheduleFlush();
461
- }
462
- };
463
- const nextTick = (cb) => promiseResolve().then(cb);
464
- const readTask = /*@__PURE__*/ queueTask(queueDomReads, false);
465
- const writeTask = /*@__PURE__*/ queueTask(queueDomWrites, true);
466
- //#endregion
467
- //#region src/runtime/asset-path.ts
468
- const getAssetPath = (path) => {
469
- const base = plt.$resourcesUrl$ || new URL(".", import.meta.url).href;
470
- const assetUrl = new URL(path, base);
471
- return assetUrl.origin !== win.location.origin ? assetUrl.href : assetUrl.pathname;
472
- };
473
- const setAssetPath = (path) => plt.$resourcesUrl$ = path;
474
- //#endregion
475
- //#region src/utils/style.ts
476
- /**
477
- * If (1) styles is not empty string, and (2) constructable stylesheets are supported,
478
- * then make a stylesheet.
479
- *
480
- * @param styles - The styles to add to the stylesheet. If empty string, then no stylesheet is returned.
481
- * @returns A stylesheet if it can be created, otherwise undefined.
482
- */
483
- function createStyleSheetIfNeededAndSupported(styles) {
484
- if (!styles || !supportsConstructableStylesheets) return void 0;
485
- const sheet = new CSSStyleSheet();
486
- sheet.replaceSync(styles);
487
- return sheet;
488
- }
489
- //#endregion
490
- //#region src/utils/shadow-root.ts
491
- let globalStyleSheet;
492
- function createShadowRoot(cmpMeta) {
493
- const isClosed = BUILD.shadowModeClosed && !!(cmpMeta.$flags$ & CMP_FLAGS.shadowModeClosed);
494
- const opts = { mode: isClosed ? "closed" : "open" };
495
- const reg = this.constructor._registry;
496
- if (reg) opts.customElementRegistry = reg;
497
- if (BUILD.shadowDelegatesFocus) opts.delegatesFocus = !!(cmpMeta.$flags$ & CMP_FLAGS.shadowDelegatesFocus);
498
- if (BUILD.shadowSlotAssignmentManual) {
499
- if (!!(cmpMeta.$flags$ & CMP_FLAGS.shadowSlotAssignmentManual)) opts.slotAssignment = "manual";
500
- }
501
- const shadowRoot = this.attachShadow(opts);
502
- if (BUILD.shadowModeClosed && isClosed) this.__shadowRoot = shadowRoot;
503
- if (globalStyleSheet === void 0) globalStyleSheet = createStyleSheetIfNeededAndSupported("") ?? null;
504
- if (globalStyleSheet) {
505
- if (supportsMutableAdoptedStyleSheets) shadowRoot.adoptedStyleSheets.push(globalStyleSheet);
506
- else shadowRoot.adoptedStyleSheets = [...shadowRoot.adoptedStyleSheets, globalStyleSheet];
507
- }
508
- }
509
- //#endregion
510
- //#region src/runtime/slot-polyfill-utils.ts
511
- /**
512
- * Adjust the `.hidden` property as-needed on any nodes in a DOM subtree which
513
- * are slot fallback nodes - `<slot-fb>...</slot-fb>`
514
- *
515
- * A slot fallback node should be visible by default. Then, it should be
516
- * conditionally hidden if:
517
- *
518
- * - it has a sibling with a `slot` property set to its slot name or if
519
- * - it is a default fallback slot node, in which case we hide if it has any
520
- * content
521
- *
522
- * @param elm the element of interest
523
- */
524
- const updateFallbackSlotVisibility = (elm) => {
525
- const childNodes = internalCall(elm, "childNodes");
526
- if (elm.tagName && elm.tagName.includes("-") && elm["s-cr"] && elm.tagName !== "SLOT-FB") getHostSlotNodes(childNodes, elm.tagName).forEach((slotNode) => {
527
- if (slotNode.nodeType === NODE_TYPE.ElementNode && slotNode.tagName === "SLOT-FB") {
528
- if (getSlotChildSiblings(slotNode, getSlotName(slotNode), false).length) slotNode.hidden = true;
529
- else slotNode.hidden = false;
530
- }
531
- });
532
- let i = 0;
533
- for (i = 0; i < childNodes.length; i++) {
534
- const childNode = childNodes[i];
535
- if (childNode.nodeType === NODE_TYPE.ElementNode && internalCall(childNode, "childNodes").length) updateFallbackSlotVisibility(childNode);
536
- }
537
- };
538
- /**
539
- * Get's the child nodes of a component that are actually slotted.
540
- * It does this by using root nodes of a component; for each slotted node there is a
541
- * corresponding slot location node which points to the slotted node (via `['s-nr']`).
542
- *
543
- * This is only required until all patches are unified / switched on all the time (then we can rely on `childNodes`)
544
- * either under 'lightDomPatches' or on by default
545
- * @param childNodes all 'internal' child nodes of the component
546
- * @returns An array of slotted reference nodes.
547
- */
548
- const getSlottedChildNodes = (childNodes) => {
549
- const result = [];
550
- for (let i = 0; i < childNodes.length; i++) {
551
- const slottedNode = childNodes[i]["s-nr"] || void 0;
552
- if (slottedNode && slottedNode.isConnected) result.push(slottedNode);
553
- }
554
- return result;
555
- };
556
- /**
557
- * Recursively searches a series of child nodes for slot node/s, optionally with a provided slot name.
558
- * @param childNodes the nodes to search for a slot with a specific name. Should be an element's root nodes.
559
- * @param hostName the host name of the slot to match on.
560
- * @param slotName the name of the slot to match on.
561
- * @returns a reference to the slot node that matches the provided name, `null` otherwise
562
- */
563
- function getHostSlotNodes(childNodes, hostName, slotName) {
564
- let i = 0;
565
- let slottedNodes = [];
566
- let childNode;
567
- for (; i < childNodes.length; i++) {
568
- childNode = childNodes[i];
569
- if (childNode["s-sr"] && (!hostName || childNode["s-hn"] === hostName) && (slotName === void 0 || getSlotName(childNode) === slotName)) {
570
- slottedNodes.push(childNode);
571
- if (typeof slotName !== "undefined") return slottedNodes;
572
- }
573
- slottedNodes = [...slottedNodes, ...getHostSlotNodes(internalCall(childNode, "childNodes"), hostName, slotName)];
574
- }
575
- return slottedNodes;
576
- }
577
- /**
578
- * Get all 'child' sibling nodes of a slot node
579
- * @param slot - the slot node to get the child nodes from
580
- * @param slotName - the name of the slot to match on
581
- * @param includeSlot - whether to include the slot node in the result
582
- * @returns child nodes of the slot node
583
- */
584
- const getSlotChildSiblings = (slot, slotName, includeSlot = true) => {
585
- const childNodes = [];
586
- if (includeSlot && slot["s-sr"] || !slot["s-sr"]) childNodes.push(slot);
587
- let node = slot;
588
- while (node = node.nextSibling) if (getSlotName(node) === slotName && (includeSlot || !node["s-sr"])) childNodes.push(node);
589
- return childNodes;
590
- };
591
- /**
592
- * Check whether a node is located in a given named slot.
593
- *
594
- * @param nodeToRelocate the node of interest
595
- * @param slotName the slot name to check
596
- * @returns whether the node is located in the slot or not
597
- */
598
- const isNodeLocatedInSlot = (nodeToRelocate, slotName) => {
599
- if (nodeToRelocate.nodeType === NODE_TYPE.ElementNode) {
600
- if (nodeToRelocate.getAttribute("slot") === null && slotName === "") return true;
601
- if (nodeToRelocate.getAttribute("slot") === slotName) return true;
602
- return false;
603
- }
604
- if (typeof nodeToRelocate["s-sa"] === "string") return nodeToRelocate["s-sa"] === slotName;
605
- return slotName === "";
606
- };
607
- /**
608
- * Creates an empty text node to act as a forwarding address to a slotted node:
609
- * 1) When non-shadow components re-render, they need a place to temporarily put 'lightDOM' elements.
610
- * 2) Patched dom methods and accessors use this node to calculate what 'lightDOM' nodes are in the host.
611
- *
612
- * @param newChild a node that's going to be added to the component
613
- * @param slotNode the slot node that the node will be added to
614
- * @param prepend move the slotted location node to the beginning of the host
615
- * @param position an ordered position to add the ref node which mirrors the lightDom nodes' order. Used during SSR hydration
616
- * (the order of the slot location nodes determines the order of the slotted nodes in our patched accessors)
617
- */
618
- const addSlotRelocateNode = (newChild, slotNode, prepend, position) => {
619
- if (newChild["s-ol"] && newChild["s-ol"].isConnected) return;
620
- const slottedNodeLocation = document.createTextNode("");
621
- slottedNodeLocation["s-nr"] = newChild;
622
- if (!slotNode["s-cr"] || !slotNode["s-cr"].parentNode) return;
623
- const parent = slotNode["s-cr"].parentNode;
624
- const appendMethod = prepend ? internalCall(parent, "prepend") : internalCall(parent, "appendChild");
625
- if (BUILD.hydrateClientSide && typeof position !== "undefined") {
626
- slottedNodeLocation["s-oo"] = position;
627
- const childNodes = internalCall(parent, "childNodes");
628
- const slotRelocateNodes = [slottedNodeLocation];
629
- childNodes.forEach((n) => {
630
- if (n["s-nr"]) slotRelocateNodes.push(n);
631
- });
632
- slotRelocateNodes.sort((a, b) => {
633
- if (!a["s-oo"] || a["s-oo"] < (b["s-oo"] || 0)) return -1;
634
- else if (!b["s-oo"] || b["s-oo"] < a["s-oo"]) return 1;
635
- return 0;
636
- });
637
- slotRelocateNodes.forEach((n) => appendMethod.call(parent, n));
638
- } else appendMethod.call(parent, slottedNodeLocation);
639
- newChild["s-ol"] = slottedNodeLocation;
640
- newChild["s-sh"] = slotNode["s-hn"];
641
- };
642
- const getSlotName = (node) => typeof node["s-sn"] === "string" ? node["s-sn"] : node.nodeType === 1 && node.getAttribute("slot") || void 0;
643
- /**
644
- * Add `assignedElements` and `assignedNodes` methods on a fake slot node
645
- *
646
- * @param node - slot node to patch
647
- */
648
- function patchSlotNode(node) {
649
- if (node.assignedElements || node.assignedNodes || !node["s-sr"]) return;
650
- const assignedFactory = (elementsOnly) => function(opts) {
651
- const toReturn = [];
652
- const slotName = this["s-sn"];
653
- if (opts?.flatten) {
654
- if (BUILD.isDev) console.error("Flattening is not supported for Stencil non-shadow slots. You can use `.childNodes` for nested slot fallback content.");
655
- else console.error("Flattening not supported for Stencil non-shadow slots");
656
- }
657
- const parent = this["s-cr"].parentElement;
658
- (parent.__childNodes ? parent.childNodes : getSlottedChildNodes(parent.childNodes)).forEach((n) => {
659
- if (slotName === getSlotName(n)) toReturn.push(n);
660
- });
661
- if (elementsOnly) return toReturn.filter((n) => n.nodeType === NODE_TYPE.ElementNode);
662
- return toReturn;
663
- }.bind(node);
664
- node.assignedElements = assignedFactory(true);
665
- node.assignedNodes = assignedFactory(false);
666
- }
667
- /**
668
- * Dispatches a `slotchange` event on a fake `<slot />` node.
669
- *
670
- * @param elm the slot node to dispatch the event from
671
- */
672
- function dispatchSlotChangeEvent(elm) {
673
- elm.name = elm["s-sn"] || "";
674
- elm.dispatchEvent(new CustomEvent("slotchange", {
675
- bubbles: false,
676
- cancelable: false,
677
- composed: false
678
- }));
679
- }
680
- /**
681
- * Find the slot node that a slotted node belongs to
682
- *
683
- * @param slottedNode - the slotted node to find the slot for
684
- * @param parentHost - the parent host element of the slotted node
685
- * @returns the slot node and slot name
686
- */
687
- function findSlotFromSlottedNode(slottedNode, parentHost) {
688
- parentHost = parentHost || slottedNode["s-ol"]?.parentElement;
689
- if (!parentHost) return {
690
- slotNode: null,
691
- slotName: ""
692
- };
693
- const slotName = slottedNode["s-sn"] = getSlotName(slottedNode) || "";
694
- return {
695
- slotNode: getHostSlotNodes(internalCall(parentHost, "childNodes"), parentHost.tagName, slotName)[0],
696
- slotName
697
- };
698
- }
699
- //#endregion
700
- //#region src/runtime/dom-extras.ts
701
- const applyLightDomPatches = (hostElementPrototype) => {
702
- patchSlotAppendChild(hostElementPrototype);
703
- patchSlotAppend(hostElementPrototype);
704
- patchSlotPrepend(hostElementPrototype);
705
- patchSlotInsertAdjacentHTML(hostElementPrototype);
706
- patchInsertBefore(hostElementPrototype);
707
- patchTextContent(hostElementPrototype);
708
- patchChildSlotNodes(hostElementPrototype);
709
- patchSlotRemoveChild(hostElementPrototype);
710
- };
711
- /**
712
- * Patches the `cloneNode` method on a `scoped` Stencil component.
713
- *
714
- * @param HostElementPrototype The Stencil component to be patched
715
- */
716
- const patchCloneNode = (HostElementPrototype) => {
717
- if (HostElementPrototype.__cloneNode) return;
718
- const orgCloneNode = HostElementPrototype.__cloneNode = HostElementPrototype.cloneNode;
719
- HostElementPrototype.cloneNode = function(deep) {
720
- const srcNode = this;
721
- const isShadowDom = BUILD.shadowDom ? !!srcNode.shadowRoot : false;
722
- const clonedNode = orgCloneNode.call(srcNode, isShadowDom ? deep : false);
723
- if (BUILD.slot && !isShadowDom && deep) {
724
- let i = 0;
725
- let slotted, nonStencilNode;
726
- const stencilPrivates = [
727
- "s-id",
728
- "s-cr",
729
- "s-lr",
730
- "s-rc",
731
- "s-sc",
732
- "s-p",
733
- "s-cn",
734
- "s-sr",
735
- "s-sn",
736
- "s-hn",
737
- "s-ol",
738
- "s-nr",
739
- "s-si",
740
- "s-rf",
741
- "s-scs"
742
- ];
743
- const childNodes = this.__childNodes || this.childNodes;
744
- for (; i < childNodes.length; i++) {
745
- slotted = childNodes[i]["s-nr"];
746
- nonStencilNode = stencilPrivates.every((privateField) => !childNodes[i][privateField]);
747
- if (slotted) {
748
- if (clonedNode.__appendChild) clonedNode.__appendChild(slotted.cloneNode(true));
749
- else clonedNode.appendChild(slotted.cloneNode(true));
750
- }
751
- if (nonStencilNode) clonedNode.appendChild(childNodes[i].cloneNode(true));
752
- }
753
- }
754
- return clonedNode;
755
- };
756
- };
757
- /**
758
- * Patches the `appendChild` method on a `scoped` Stencil component.
759
- * The patch will attempt to find a slot with the same name as the node being appended
760
- * and insert it into the slot reference if found. Otherwise, it falls-back to the original
761
- * `appendChild` method.
762
- *
763
- * @param HostElementPrototype The Stencil component to be patched
764
- */
765
- const patchSlotAppendChild = (HostElementPrototype) => {
766
- if (HostElementPrototype.__appendChild) return;
767
- HostElementPrototype.__appendChild = HostElementPrototype.appendChild;
768
- HostElementPrototype.appendChild = function(newChild) {
769
- const { slotName, slotNode } = findSlotFromSlottedNode(newChild, this);
770
- if (slotNode) {
771
- addSlotRelocateNode(newChild, slotNode);
772
- const slotChildNodes = getSlotChildSiblings(slotNode, slotName);
773
- const appendAfter = slotChildNodes[slotChildNodes.length - 1];
774
- const insertedNode = internalCall(internalCall(appendAfter, "parentNode"), "insertBefore")(newChild, appendAfter.nextSibling);
775
- dispatchSlotChangeEvent(slotNode);
776
- updateFallbackSlotVisibility(this);
777
- return insertedNode;
778
- }
779
- return this.__appendChild(newChild);
780
- };
781
- };
782
- /**
783
- * Patches the `removeChild` method on a `scoped` Stencil component.
784
- * This patch attempts to remove the specified node from a slot reference
785
- * if the slot exists. Otherwise, it falls-back to the original `removeChild` method.
786
- *
787
- * @param ElementPrototype The Stencil component to be patched
788
- */
789
- const patchSlotRemoveChild = (ElementPrototype) => {
790
- if (ElementPrototype.__removeChild) return;
791
- ElementPrototype.__removeChild = ElementPrototype.removeChild;
792
- ElementPrototype.removeChild = function(toRemove) {
793
- if (toRemove && typeof toRemove["s-sn"] !== "undefined") {
794
- if (getHostSlotNodes(this.__childNodes || this.childNodes, this.tagName, toRemove["s-sn"]) && toRemove.isConnected) {
795
- toRemove.remove();
796
- updateFallbackSlotVisibility(this);
797
- return;
798
- }
799
- }
800
- return this.__removeChild(toRemove);
801
- };
802
- };
803
- /**
804
- * Patches the `prepend` method for a slotted node inside a scoped component.
805
- *
806
- * @param HostElementPrototype the `Element` to be patched
807
- */
808
- const patchSlotPrepend = (HostElementPrototype) => {
809
- if (HostElementPrototype.__prepend) return;
810
- HostElementPrototype.__prepend = HostElementPrototype.prepend;
811
- HostElementPrototype.prepend = function(...newChildren) {
812
- newChildren.forEach((newChild) => {
813
- if (typeof newChild === "string") newChild = this.ownerDocument.createTextNode(newChild);
814
- const slotName = (newChild["s-sn"] = getSlotName(newChild)) || "";
815
- const slotNode = getHostSlotNodes(internalCall(this, "childNodes"), this.tagName, slotName)[0];
816
- if (slotNode) {
817
- addSlotRelocateNode(newChild, slotNode, true);
818
- const appendAfter = getSlotChildSiblings(slotNode, slotName)[0];
819
- const toReturn = internalCall(internalCall(appendAfter, "parentNode"), "insertBefore")(newChild, internalCall(appendAfter, "nextSibling"));
820
- dispatchSlotChangeEvent(slotNode);
821
- return toReturn;
822
- }
823
- if (newChild.nodeType === 1 && !!newChild.getAttribute("slot")) newChild.hidden = true;
824
- return HostElementPrototype.__prepend(newChild);
825
- });
826
- };
827
- };
828
- /**
829
- * Patches the `append` method for a slotted node inside a scoped component. The patched method uses
830
- * `appendChild` under-the-hood while creating text nodes for any new children that passed as bare strings.
831
- *
832
- * @param HostElementPrototype the `Element` to be patched
833
- */
834
- const patchSlotAppend = (HostElementPrototype) => {
835
- if (HostElementPrototype.__append) return;
836
- HostElementPrototype.__append = HostElementPrototype.append;
837
- HostElementPrototype.append = function(...newChildren) {
838
- newChildren.forEach((newChild) => {
839
- if (typeof newChild === "string") newChild = this.ownerDocument.createTextNode(newChild);
840
- this.appendChild(newChild);
841
- });
842
- };
843
- };
844
- /**
845
- * Patches the `insertAdjacentHTML` method for a slotted node inside a scoped component. Specifically,
846
- * we only need to patch the behavior for the specific `beforeend` and `afterbegin` positions so the element
847
- * gets inserted into the DOM in the correct location.
848
- *
849
- * @param HostElementPrototype the `Element` to be patched
850
- */
851
- const patchSlotInsertAdjacentHTML = (HostElementPrototype) => {
852
- if (HostElementPrototype.__insertAdjacentHTML) return;
853
- const originalInsertAdjacentHtml = HostElementPrototype.insertAdjacentHTML;
854
- HostElementPrototype.insertAdjacentHTML = function(position, text) {
855
- if (position !== "afterbegin" && position !== "beforeend") return originalInsertAdjacentHtml.call(this, position, text);
856
- const container = this.ownerDocument.createElement("_");
857
- let node;
858
- container.innerHTML = text;
859
- if (position === "afterbegin") while (node = container.firstChild) this.prepend(node);
860
- else if (position === "beforeend") while (node = container.firstChild) this.append(node);
861
- };
862
- };
863
- /**
864
- * Patches the `insertBefore` of a non-shadow component.
865
- *
866
- * The *current* node to insert before may not be in the root of our component
867
- * (e.g. if it's 'slotted' it appears in the root, but isn't really)
868
- *
869
- * This tries to find where the *current* node lives within the component and insert the new node before it
870
- * *If* the new node is in the same slot as the *current* node. Otherwise the new node is appended to it's 'slot'
871
- *
872
- * @param HostElementPrototype the custom element prototype to patch
873
- */
874
- const patchInsertBefore = (HostElementPrototype) => {
875
- if (HostElementPrototype.__insertBefore) return;
876
- const eleProto = HostElementPrototype;
877
- if (eleProto.__insertBefore) return;
878
- eleProto.__insertBefore = HostElementPrototype.insertBefore;
879
- HostElementPrototype.insertBefore = function(newChild, currentChild) {
880
- const { slotName, slotNode } = findSlotFromSlottedNode(newChild, this);
881
- const slottedNodes = this.__childNodes ? this.childNodes : getSlottedChildNodes(this.childNodes);
882
- if (slotNode) {
883
- let found = false;
884
- slottedNodes.forEach((childNode) => {
885
- if (childNode === currentChild || currentChild === null) {
886
- found = true;
887
- if (currentChild === null || slotName !== currentChild["s-sn"]) {
888
- this.appendChild(newChild);
889
- return;
890
- }
891
- if (slotName === currentChild["s-sn"]) {
892
- addSlotRelocateNode(newChild, slotNode);
893
- internalCall(internalCall(currentChild, "parentNode"), "insertBefore")(newChild, currentChild);
894
- dispatchSlotChangeEvent(slotNode);
895
- }
896
- return;
897
- }
898
- });
899
- if (found) return newChild;
900
- }
901
- /**
902
- * Fixes an issue where slotted elements are dynamically relocated in React, such as after data fetch.
903
- *
904
- * When a slotted element is passed to another scoped component (e.g., <A><C slot="header"/></A>),
905
- * the child’s __parentNode (original parent node property) does not match this.
906
- *
907
- * To prevent errors, this checks if the current child's parent node differs from this.
908
- * If so, appendChild(newChild) is called to ensure the child is correctly inserted,
909
- * allowing Stencil to properly manage the slot placement.
910
- */
911
- const parentNode = currentChild?.__parentNode;
912
- if (parentNode && !this.isSameNode(parentNode)) return this.appendChild(newChild);
913
- return this.__insertBefore(newChild, currentChild);
914
- };
915
- };
916
- /**
917
- * Patches the `textContent` of an unnamed slotted node inside a scoped component
918
- *
919
- * @param hostElementPrototype the `Element` to be patched
920
- */
921
- const patchTextContent = (hostElementPrototype) => {
922
- patchHostOriginalAccessor("textContent", hostElementPrototype);
923
- Object.defineProperty(hostElementPrototype, "textContent", {
924
- get: function() {
925
- let text = "";
926
- (this.__childNodes ? this.childNodes : getSlottedChildNodes(this.childNodes)).forEach((node) => text += node.textContent || "");
927
- return text;
928
- },
929
- set: function(value) {
930
- (this.__childNodes ? this.childNodes : getSlottedChildNodes(this.childNodes)).forEach((node) => {
931
- if (node["s-ol"]) node["s-ol"].remove();
932
- node.remove();
933
- });
934
- this.insertAdjacentHTML("beforeend", value);
935
- }
936
- });
937
- };
938
- const patchChildSlotNodes = (elm) => {
939
- class FakeNodeList extends Array {
940
- item(n) {
941
- return this[n];
942
- }
943
- }
944
- patchHostOriginalAccessor("children", elm);
945
- Object.defineProperty(elm, "children", { get() {
946
- return this.childNodes.filter((n) => n.nodeType === 1);
947
- } });
948
- Object.defineProperty(elm, "childElementCount", { get() {
949
- return this.children.length;
950
- } });
951
- patchHostOriginalAccessor("firstChild", elm);
952
- Object.defineProperty(elm, "firstChild", { get() {
953
- return this.childNodes[0] || null;
954
- } });
955
- patchHostOriginalAccessor("lastChild", elm);
956
- Object.defineProperty(elm, "lastChild", { get() {
957
- return this.childNodes[this.childNodes.length - 1] || null;
958
- } });
959
- patchHostOriginalAccessor("childNodes", elm);
960
- Object.defineProperty(elm, "childNodes", { get() {
961
- const result = new FakeNodeList();
962
- if (!this["s-cr"]) {
963
- result.push(...Array.from(this.__childNodes));
964
- return result;
965
- }
966
- result.push(...getSlottedChildNodes(this.__childNodes));
967
- return result;
968
- } });
969
- };
970
- /**
971
- * Patches sibling accessors of a 'slotted' node within a non-shadow component.
972
- * Meaning whilst stepping through a non-shadow element's nodes, only the mock 'lightDOM' nodes are returned.
973
- * Especially relevant when rendering components via SSR... Frameworks will often try to reconcile their
974
- * VDOM with the real DOM by stepping through nodes with 'nextSibling' et al.
975
- * - `nextSibling`
976
- * - `nextElementSibling`
977
- * - `previousSibling`
978
- * - `previousElementSibling`
979
- *
980
- * @param node the slotted node to be patched
981
- */
982
- const patchSlottedNode = (node) => {
983
- if (!node || node.__nextSibling !== void 0 || !globalThis.Node) return;
984
- patchNextSibling(node);
985
- patchPreviousSibling(node);
986
- patchParentNode(node);
987
- if (node.nodeType === Node.ELEMENT_NODE) {
988
- patchNextElementSibling(node);
989
- patchPreviousElementSibling(node);
990
- }
991
- };
992
- /**
993
- * Patches the `nextSibling` accessor of a non-shadow slotted node
994
- *
995
- * @param node the slotted node to be patched
996
- */
997
- const patchNextSibling = (node) => {
998
- if (!node || node.__nextSibling) return;
999
- patchHostOriginalAccessor("nextSibling", node);
1000
- Object.defineProperty(node, "nextSibling", { get: function() {
1001
- const parentNodes = this["s-ol"]?.parentNode.childNodes;
1002
- const index = parentNodes?.indexOf(this);
1003
- if (parentNodes && index > -1) return parentNodes[index + 1] || null;
1004
- return this.__nextSibling;
1005
- } });
1006
- };
1007
- /**
1008
- * Patches the `nextElementSibling` accessor of a non-shadow slotted node
1009
- *
1010
- * @param element the slotted element node to be patched
1011
- */
1012
- const patchNextElementSibling = (element) => {
1013
- if (!element || element.__nextElementSibling) return;
1014
- patchHostOriginalAccessor("nextElementSibling", element);
1015
- Object.defineProperty(element, "nextElementSibling", { get: function() {
1016
- const parentEles = this["s-ol"]?.parentNode.children;
1017
- const index = parentEles?.indexOf(this);
1018
- if (parentEles && index > -1) return parentEles[index + 1] || null;
1019
- return this.__nextElementSibling;
1020
- } });
1021
- };
1022
- /**
1023
- * Patches the `previousSibling` accessor of a non-shadow slotted node
1024
- *
1025
- * @param node the slotted node to be patched
1026
- */
1027
- const patchPreviousSibling = (node) => {
1028
- if (!node || node.__previousSibling) return;
1029
- patchHostOriginalAccessor("previousSibling", node);
1030
- Object.defineProperty(node, "previousSibling", { get: function() {
1031
- const parentNodes = this["s-ol"]?.parentNode.childNodes;
1032
- const index = parentNodes?.indexOf(this);
1033
- if (parentNodes && index > -1) return parentNodes[index - 1] || null;
1034
- return this.__previousSibling;
1035
- } });
1036
- };
1037
- /**
1038
- * Patches the `previousElementSibling` accessor of a non-shadow slotted node
1039
- *
1040
- * @param element the slotted element node to be patched
1041
- */
1042
- const patchPreviousElementSibling = (element) => {
1043
- if (!element || element.__previousElementSibling) return;
1044
- patchHostOriginalAccessor("previousElementSibling", element);
1045
- Object.defineProperty(element, "previousElementSibling", { get: function() {
1046
- const parentNodes = this["s-ol"]?.parentNode.children;
1047
- const index = parentNodes?.indexOf(this);
1048
- if (parentNodes && index > -1) return parentNodes[index - 1] || null;
1049
- return this.__previousElementSibling;
1050
- } });
1051
- };
1052
- /**
1053
- * Patches the `parentNode` accessor of a non-shadow slotted node
1054
- *
1055
- * @param node the slotted node to be patched
1056
- */
1057
- const patchParentNode = (node) => {
1058
- if (!node || node.__parentNode) return;
1059
- patchHostOriginalAccessor("parentNode", node);
1060
- Object.defineProperty(node, "parentNode", {
1061
- get: function() {
1062
- return this["s-ol"]?.parentNode || this.__parentNode;
1063
- },
1064
- set: function(value) {
1065
- this.__parentNode = value;
1066
- }
1067
- });
1068
- };
1069
- const validElementPatches = [
1070
- "children",
1071
- "nextElementSibling",
1072
- "previousElementSibling"
1073
- ];
1074
- const validNodesPatches = [
1075
- "childNodes",
1076
- "firstChild",
1077
- "lastChild",
1078
- "nextSibling",
1079
- "previousSibling",
1080
- "textContent",
1081
- "parentNode"
1082
- ];
1083
- /**
1084
- * Patches a node or element; making it's original accessor method available under a new name.
1085
- * e.g. `nextSibling` -> `__nextSibling`
1086
- *
1087
- * @param accessorName - the name of the accessor to patch
1088
- * @param node - the node to patch
1089
- */
1090
- function patchHostOriginalAccessor(accessorName, node) {
1091
- /**
1092
- * skip this method if a component was imported from a non-browser environment
1093
- */
1094
- if (!globalThis.Node || !globalThis.Element) return;
1095
- let accessor;
1096
- if (validElementPatches.includes(accessorName)) accessor = Object.getOwnPropertyDescriptor(Element.prototype, accessorName);
1097
- else if (validNodesPatches.includes(accessorName)) accessor = Object.getOwnPropertyDescriptor(Node.prototype, accessorName);
1098
- if (!accessor) accessor = Object.getOwnPropertyDescriptor(node, accessorName);
1099
- if (accessor) Object.defineProperty(node, "__" + accessorName, accessor);
1100
- }
1101
- /**
1102
- * Get the original / internal accessor or method of a node or element.
1103
- *
1104
- * @param node - the node to get the accessor from
1105
- * @param method - the name of the accessor to get
1106
- *
1107
- * @returns the original accessor or method of the node
1108
- */
1109
- function internalCall(node, method) {
1110
- if ("__" + method in node) {
1111
- const toReturn = node["__" + method];
1112
- if (typeof toReturn !== "function") return toReturn;
1113
- return toReturn.bind(node);
1114
- } else {
1115
- if (typeof node[method] !== "function") return node[method];
1116
- return node[method].bind(node);
1117
- }
1118
- }
1119
- //#endregion
1120
- //#region src/runtime/element.ts
1121
- const getElement = (ref) => BUILD.lazyLoad ? getHostRef(ref)?.$hostElement$ : ref;
1122
- /**
1123
- * Get the shadow root for a Stencil component's host element.
1124
- * This works for both open and closed shadow DOM modes.
1125
- *
1126
- * For closed shadow DOM, `element.shadowRoot` returns `null` by design,
1127
- * but Stencil stores the reference internally so components can still
1128
- * access their own shadow root.
1129
- *
1130
- * @param element The host element (from @Element() decorator)
1131
- * @returns The shadow root, or null if no shadow root exists
1132
- */
1133
- const getShadowRoot = (element) => {
1134
- if (BUILD.shadowModeClosed && element.__shadowRoot) return element.__shadowRoot;
1135
- return element.shadowRoot;
1136
- };
1137
- //#endregion
1138
- //#region src/runtime/profile.ts
1139
- let i = 0;
1140
- const createTime = (fnName, tagName = "") => {
1141
- if (BUILD.profile && performance.mark) {
1142
- const key = `st:${fnName}:${tagName}:${i++}`;
1143
- performance.mark(key);
1144
- return () => performance.measure(`[Stencil] ${fnName}() <${tagName}>`, key);
1145
- } else return () => {};
1146
- };
1147
- const uniqueTime = (key, measureText) => {
1148
- if (BUILD.profile && performance.mark) {
1149
- if (performance.getEntriesByName(key, "mark").length === 0) performance.mark(key);
1150
- return () => {
1151
- if (performance.getEntriesByName(measureText, "measure").length === 0) performance.measure(measureText, key);
1152
- };
1153
- } else return () => {};
1154
- };
1155
- const inspect = (ref) => {
1156
- const hostRef = getHostRef(ref);
1157
- if (!hostRef) return;
1158
- const flags = hostRef.$flags$;
1159
- const hostElement = hostRef.$hostElement$;
1160
- return {
1161
- renderCount: hostRef.$renderCount$,
1162
- flags: {
1163
- hasRendered: !!(flags & HOST_FLAGS.hasRendered),
1164
- hasConnected: !!(flags & HOST_FLAGS.hasConnected),
1165
- isWaitingForChildren: !!(flags & HOST_FLAGS.isWaitingForChildren),
1166
- isConstructingInstance: !!(flags & HOST_FLAGS.isConstructingInstance),
1167
- isQueuedForUpdate: !!(flags & HOST_FLAGS.isQueuedForUpdate),
1168
- hasInitializedComponent: !!(flags & HOST_FLAGS.hasInitializedComponent),
1169
- hasLoadedComponent: !!(flags & HOST_FLAGS.hasLoadedComponent),
1170
- isWatchReady: !!(flags & HOST_FLAGS.isWatchReady),
1171
- isListenReady: !!(flags & HOST_FLAGS.isListenReady),
1172
- needsRerender: !!(flags & HOST_FLAGS.needsRerender)
1173
- },
1174
- instanceValues: hostRef.$instanceValues$,
1175
- serializerValues: hostRef.$serializerValues$,
1176
- ancestorComponent: hostRef.$ancestorComponent$,
1177
- hostElement,
1178
- lazyInstance: hostRef.$lazyInstance$,
1179
- vnode: hostRef.$vnode$,
1180
- modeName: hostRef.$modeName$,
1181
- fetchedCbList: hostRef.$fetchedCbList$,
1182
- onReadyPromise: hostRef.$onReadyPromise$,
1183
- onReadyResolve: hostRef.$onReadyResolve$,
1184
- onInstancePromise: hostRef.$onInstancePromise$,
1185
- onInstanceResolve: hostRef.$onInstanceResolve$,
1186
- onRenderResolve: hostRef.$onRenderResolve$,
1187
- queuedListeners: hostRef.$queuedListeners$,
1188
- rmListeners: hostRef.$rmListeners$,
1189
- ["s-id"]: hostElement["s-id"],
1190
- ["s-cr"]: hostElement["s-cr"],
1191
- ["s-lr"]: hostElement["s-lr"],
1192
- ["s-p"]: hostElement["s-p"],
1193
- ["s-rc"]: hostElement["s-rc"],
1194
- ["s-sc"]: hostElement["s-sc"]
1195
- };
1196
- };
1197
- const installDevTools = () => {
1198
- if (BUILD.devTools) {
1199
- const stencil = win.stencil = win.stencil || {};
1200
- const originalInspect = stencil.inspect;
1201
- stencil.inspect = (ref) => {
1202
- let result = inspect(ref);
1203
- if (!result && typeof originalInspect === "function") result = originalInspect(ref);
1204
- return result;
1205
- };
1206
- }
1207
- };
1208
- //#endregion
1209
- //#region src/runtime/styles.ts
1210
- const rootAppliedStyles = /*@__PURE__*/ new WeakMap();
1211
- /**
1212
- * Get or initialize the set of applied style scope IDs for a container element.
1213
- *
1214
- * @param container the container element to track styles for
1215
- * @returns the set of applied scope IDs
1216
- */
1217
- const getAppliedStyles = (container) => {
1218
- let applied = rootAppliedStyles.get(container);
1219
- if (!applied) {
1220
- applied = /* @__PURE__ */ new Set();
1221
- rootAppliedStyles.set(container, applied);
1222
- }
1223
- return applied;
1224
- };
1225
- /**
1226
- * Safely adopt a stylesheet into a container's adoptedStyleSheets.
1227
- * Handles both mutable and immutable adoptedStyleSheets arrays.
1228
- *
1229
- * @param container the shadow root or document to adopt styles into
1230
- * @param sheet the CSSStyleSheet to adopt
1231
- * @param prepend if true, add to beginning; if false, add to end
1232
- */
1233
- const adoptStylesheet = (container, sheet, prepend = false) => {
1234
- if (supportsMutableAdoptedStyleSheets) {
1235
- if (prepend) container.adoptedStyleSheets.unshift(sheet);
1236
- else container.adoptedStyleSheets.push(sheet);
1237
- } else if (prepend) container.adoptedStyleSheets = [sheet, ...container.adoptedStyleSheets];
1238
- else container.adoptedStyleSheets = [...container.adoptedStyleSheets, sheet];
1239
- };
1240
- /**
1241
- * Create a CSSStyleSheet for the correct window context.
1242
- * Constructable stylesheets can't be shared between windows,
1243
- * so we need to create one for the current window.
1244
- *
1245
- * @param container the container node (used to determine the window context)
1246
- * @param cssText the CSS text to populate the stylesheet with
1247
- * @returns a new CSSStyleSheet for the correct window
1248
- */
1249
- const createStylesheetForWindow = (container, cssText) => {
1250
- const sheet = new (container.defaultView ?? (container.ownerDocument?.defaultView) ?? win).CSSStyleSheet();
1251
- sheet.replaceSync(cssText);
1252
- return sheet;
1253
- };
1254
- /**
1255
- * Get the style for a component, appending slot fallback CSS if needed.
1256
- * Returns a new value without mutating the cached style.
1257
- *
1258
- * @param style - the style string or CSSStyleSheet to process
1259
- * @returns the style (string or CSSStyleSheet) with slot CSS appended if needed, or undefined
1260
- */
1261
- const getStyleWithSlotCss = (style) => {
1262
- if (!style) return SLOT_FB_CSS;
1263
- if (typeof style === "string") return style + SLOT_FB_CSS;
1264
- return style;
1265
- };
1266
- /**
1267
- * Register the styles for a component by creating a stylesheet and then
1268
- * registering it under the component's scope ID in a `WeakMap` for later use.
1269
- *
1270
- * If constructable stylesheet are not supported or `allowCS` is set to
1271
- * `false` then the styles will be registered as a string instead.
1272
- *
1273
- * @param scopeId the scope ID for the component of interest
1274
- * @param cssText styles for the component of interest
1275
- * @param allowCS whether or not to use a constructable stylesheet
1276
- */
1277
- const registerStyle = (scopeId, cssText, allowCS) => {
1278
- if (supportsConstructableStylesheets && allowCS) {
1279
- const sheet = styles.get(scopeId) ?? new CSSStyleSheet();
1280
- sheet.replaceSync(cssText);
1281
- styles.set(scopeId, sheet);
1282
- } else styles.set(scopeId, cssText);
1283
- };
1284
- /**
1285
- * Attach the styles for a given component to the DOM
1286
- *
1287
- * If the element uses shadow or is already attached to the DOM then we can
1288
- * create a stylesheet inside of its associated document fragment, otherwise
1289
- * we'll stick the stylesheet into the document head.
1290
- *
1291
- * @param styleContainerNode the node within which a style element for the
1292
- * component of interest should be added
1293
- * @param cmpMeta runtime metadata for the component of interest
1294
- * @param mode an optional current mode
1295
- * @returns the scope ID for the component of interest
1296
- */
1297
- const addStyle = (styleContainerNode, cmpMeta, mode) => {
1298
- const scopeId = getScopeId(cmpMeta, mode);
1299
- if (!win.document) return scopeId;
1300
- let style = styles.get(scopeId);
1301
- if (cmpMeta.$flags$ & CMP_FLAGS.hasSlotRelocation) style = getStyleWithSlotCss(style);
1302
- const isClosedShadowSSR = BUILD.hydrateServerSide && BUILD.shadowModeClosed && cmpMeta.$flags$ & CMP_FLAGS.shadowNeedsScopedCss && cmpMeta.$flags$ & CMP_FLAGS.shadowModeClosed;
1303
- if (styleContainerNode.nodeType !== NODE_TYPE.DocumentFragment && !isClosedShadowSSR) styleContainerNode = win.document;
1304
- if (style) {
1305
- if (typeof style === "string") {
1306
- styleContainerNode = styleContainerNode.head || styleContainerNode;
1307
- const appliedStyles = getAppliedStyles(styleContainerNode);
1308
- let styleElm;
1309
- const existingStyleElm = (BUILD.hydrateClientSide || BUILD.hotModuleReplacement) && styleContainerNode.querySelector(`[sty-id="${scopeId}"]`);
1310
- if (existingStyleElm) existingStyleElm.textContent = style;
1311
- else if (!appliedStyles.has(scopeId)) {
1312
- styleElm = win.document.createElement("style");
1313
- styleElm.textContent = style;
1314
- const nonce = plt.$nonce$ ?? queryNonceMetaTagContent(win.document);
1315
- if (nonce != null) styleElm.setAttribute("nonce", nonce);
1316
- if (BUILD.hydrateServerSide && (cmpMeta.$flags$ & CMP_FLAGS.scopedCssEncapsulation || cmpMeta.$flags$ & CMP_FLAGS.shadowNeedsScopedCss || cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) || BUILD.hotModuleReplacement) styleElm.setAttribute(HYDRATED_STYLE_ID, scopeId);
1317
- if (BUILD.hotModuleReplacement && cmpMeta.$flags$ & CMP_FLAGS.hasSlotRelocation) styleElm.setAttribute("data-slot-fb", "");
1318
- /**
1319
- * attach styles at the end of the head tag if we render scoped components
1320
- */
1321
- if (!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation)) {
1322
- if (styleContainerNode.nodeName === "HEAD") {
1323
- /**
1324
- * if the page contains preconnect links, we want to insert the styles
1325
- * after the last preconnect link to ensure the styles are preloaded
1326
- */
1327
- const preconnectLinks = styleContainerNode.querySelectorAll("link[rel=preconnect]");
1328
- const referenceNode = preconnectLinks.length > 0 ? preconnectLinks[preconnectLinks.length - 1].nextSibling : styleContainerNode.querySelector("style");
1329
- styleContainerNode.insertBefore(styleElm, referenceNode?.parentNode === styleContainerNode ? referenceNode : null);
1330
- } else if ("host" in styleContainerNode) {
1331
- if (supportsConstructableStylesheets) {
1332
- const stylesheet = createStylesheetForWindow(styleContainerNode, style);
1333
- adoptStylesheet(styleContainerNode, stylesheet, true);
1334
- } else {
1335
- /**
1336
- * If a scoped component is used within a shadow root and constructable stylesheets are
1337
- * not supported, we want to insert the styles at the beginning of the shadow root node.
1338
- *
1339
- * However, if there is already a style node in the shadow root, we just append
1340
- * the styles to the existing node.
1341
- *
1342
- * Note: order of how styles are applied is important. The new style node
1343
- * should be inserted before the existing style node.
1344
- *
1345
- * During HMR, create separate style elements for scoped components so they can be
1346
- * updated independently without affecting other components' styles.
1347
- */
1348
- const existingStyleContainer = styleContainerNode.querySelector("style");
1349
- if (existingStyleContainer && !BUILD.hotModuleReplacement) existingStyleContainer.textContent = style + existingStyleContainer.textContent;
1350
- else styleContainerNode.prepend(styleElm);
1351
- }
1352
- } else styleContainerNode.append(styleElm);
1353
- }
1354
- /**
1355
- * attach styles at the beginning of a shadow root node if we render shadow components
1356
- */
1357
- if (cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) {
1358
- if (isClosedShadowSSR) styleContainerNode.prepend(styleElm);
1359
- else styleContainerNode.insertBefore(styleElm, null);
1360
- }
1361
- if (appliedStyles) appliedStyles.add(scopeId);
1362
- }
1363
- } else if (BUILD.constructableCSS) {
1364
- const appliedStyles = getAppliedStyles(styleContainerNode);
1365
- if (!appliedStyles.has(scopeId)) {
1366
- const currentWindow = styleContainerNode.defaultView ?? styleContainerNode.ownerDocument.defaultView;
1367
- let stylesheet;
1368
- if (style.constructor === currentWindow.CSSStyleSheet) stylesheet = style;
1369
- else {
1370
- stylesheet = new currentWindow.CSSStyleSheet();
1371
- for (let i = 0; i < style.cssRules.length; i++) stylesheet.insertRule(style.cssRules[i].cssText, i);
1372
- }
1373
- adoptStylesheet(styleContainerNode, stylesheet);
1374
- appliedStyles.add(scopeId);
1375
- if (BUILD.hydrateClientSide && "host" in styleContainerNode) {
1376
- const ssrStyleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}="${scopeId}"]`);
1377
- if (ssrStyleElm) writeTask(() => ssrStyleElm.remove());
1378
- }
1379
- }
1380
- }
1381
- }
1382
- return scopeId;
1383
- };
1384
- /**
1385
- * Add styles for a given component to the DOM, optionally handling 'scoped'
1386
- * encapsulation by adding an appropriate class name to the host element.
1387
- *
1388
- * @param hostRef the host reference for the component of interest
1389
- */
1390
- const attachStyles = (hostRef) => {
1391
- const cmpMeta = hostRef.$cmpMeta$;
1392
- const elm = hostRef.$hostElement$;
1393
- const flags = cmpMeta.$flags$;
1394
- const endAttachStyles = createTime("attachStyles", cmpMeta.$tagName$);
1395
- let styleContainerNode;
1396
- const shadowRoot = BUILD.shadowDom ? getShadowRoot(elm) : null;
1397
- if (shadowRoot) styleContainerNode = shadowRoot;
1398
- else if (BUILD.hydrateServerSide && BUILD.shadowModeClosed && flags & CMP_FLAGS.shadowNeedsScopedCss && flags & CMP_FLAGS.shadowModeClosed) styleContainerNode = elm;
1399
- else styleContainerNode = elm.getRootNode();
1400
- const scopeId = addStyle(styleContainerNode, cmpMeta, hostRef.$modeName$);
1401
- if ((BUILD.shadowDom || BUILD.scoped) && BUILD.cssAnnotations && flags & CMP_FLAGS.needsScopedEncapsulation) {
1402
- elm["s-sc"] = scopeId;
1403
- elm.classList.add(scopeId + "-h");
1404
- }
1405
- endAttachStyles();
1406
- };
1407
- /**
1408
- * Get the scope ID for a given component
1409
- *
1410
- * @param cmp runtime metadata for the component of interest
1411
- * @param mode the current mode (optional)
1412
- * @returns a scope ID for the component of interest
1413
- */
1414
- const getScopeId = (cmp, mode) => "sc-" + (BUILD.mode && mode && cmp.$flags$ & CMP_FLAGS.hasMode ? cmp.$tagName$ + "-" + mode : cmp.$tagName$);
1415
- /**
1416
- * Convert a 'scoped' CSS string to one appropriate for use in the shadow DOM.
1417
- *
1418
- * Given a 'scoped' CSS string that looks like this:
1419
- *
1420
- * ```
1421
- * /*!@div*\/div.class-name { display: flex };
1422
- * ```
1423
- *
1424
- * Convert it to a 'shadow' appropriate string, like so:
1425
- *
1426
- * ```
1427
- * /*!@div*\/div.class-name { display: flex }
1428
- * ─┬─ ────────┬────────
1429
- * │ │
1430
- * │ ┌─────────────────┘
1431
- * ▼ ▼
1432
- * div{ display: flex }
1433
- * ```
1434
- *
1435
- * Note that forward-slashes in the above are escaped so they don't end the
1436
- * comment.
1437
- *
1438
- * @param css a CSS string to convert
1439
- * @returns the converted string
1440
- */
1441
- const convertScopedToShadow = (css) => css.replace(/\/\*!@([^/]+)\*\/[^{]+\{/g, "$1{");
1442
- /**
1443
- * Hydrate styles after SSR for components *not* using DSD. Convert 'scoped' styles to 'shadow'
1444
- * and add them to a constructable stylesheet.
1445
- *
1446
- * @returns void
1447
- */
1448
- const hydrateScopedToShadow = () => {
1449
- if (!win.document) return;
1450
- const styleElements = win.document.querySelectorAll(`[${HYDRATED_STYLE_ID}]`);
1451
- let i = 0;
1452
- for (; i < styleElements.length; i++) {
1453
- const scopeId = styleElements[i].getAttribute(HYDRATED_STYLE_ID);
1454
- const existing = styles.get(scopeId);
1455
- const allowCS = existing !== void 0 ? existing instanceof CSSStyleSheet : true;
1456
- registerStyle(scopeId, convertScopedToShadow(styleElements[i].innerHTML), allowCS);
1457
- }
1458
- };
1459
- //#endregion
1460
- //#region src/runtime/event-emitter.ts
1461
- const createEvent = (ref, name, flags) => {
1462
- const elm = getElement(ref);
1463
- return { emit: (detail) => {
1464
- if (BUILD.isDev && !elm.isConnected) consoleDevWarn(`The "${name}" event was emitted, but the dispatcher node is no longer connected to the dom.`);
1465
- return emitEvent(elm, name, {
1466
- bubbles: !!(flags & EVENT_FLAGS.Bubbles),
1467
- composed: !!(flags & EVENT_FLAGS.Composed),
1468
- cancelable: !!(flags & EVENT_FLAGS.Cancellable),
1469
- detail
1470
- });
1471
- } };
1472
- };
1473
- /**
1474
- * Helper function to create & dispatch a custom Event on a provided target
1475
- * @param elm the target of the Event
1476
- * @param name the name to give the custom Event
1477
- * @param opts options for configuring a custom Event
1478
- * @returns the custom Event
1479
- */
1480
- const emitEvent = (elm, name, opts) => {
1481
- const ev = plt.ce(name, opts);
1482
- elm.dispatchEvent(ev);
1483
- return ev;
1484
- };
1485
- const getRegistry = () => customElements;
1486
- //#endregion
1487
- //#region src/runtime/vdom/set-accessor.ts
1488
- /**
1489
- * Production setAccessor() function based on Preact by
1490
- * Jason Miller (@developit)
1491
- * Licensed under the MIT License
1492
- * https://github.com/developit/preact/blob/master/LICENSE
1493
- *
1494
- * Modified for Stencil's compiler and vdom
1495
- */
1496
- /** Per-element, per-attribute signal subscription disposers. */
1497
- const signalAttrDisposers = /* @__PURE__ */ new WeakMap();
1498
- const disposeAllSignalAttrs = (elm) => {
1499
- if (!BUILD.vdomSignals) return;
1500
- const map = signalAttrDisposers.get(elm);
1501
- if (map) {
1502
- map.forEach((d) => d());
1503
- signalAttrDisposers.delete(elm);
1504
- }
1505
- };
1506
- /**
1507
- * When running a VDom render set properties present on a VDom node onto the
1508
- * corresponding HTML element.
1509
- *
1510
- * Note that this function has special functionality for the `class`,
1511
- * `style`, `key`, and `ref` attributes, as well as event handlers (like
1512
- * `onClick`, etc). All others are just passed through as-is.
1513
- *
1514
- * @param elm the HTMLElement onto which attributes should be set
1515
- * @param memberName the name of the attribute to set
1516
- * @param oldValue the old value for the attribute
1517
- * @param newValue the new value for the attribute
1518
- * @param isSvg whether we're in an svg context or not
1519
- * @param flags bitflags for Vdom variables
1520
- * @param initialRender whether this is the first render of the VDom
1521
- */
1522
- const setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRender) => {
1523
- if (oldValue === newValue) return;
1524
- if (BUILD.vdomSignals && isSignalLike(newValue)) {
1525
- const attrMap = signalAttrDisposers.get(elm) ?? /* @__PURE__ */ new Map();
1526
- attrMap.get(memberName)?.();
1527
- if (!signalAttrDisposers.has(elm)) signalAttrDisposers.set(elm, attrMap);
1528
- let prevVal = oldValue;
1529
- attrMap.set(memberName, effect$1(() => {
1530
- const curVal = newValue.value;
1531
- setAccessor(elm, memberName, prevVal, curVal, isSvg, flags);
1532
- prevVal = curVal;
1533
- }));
1534
- return;
1535
- }
1536
- if (BUILD.vdomSignals && isSignalLike(oldValue)) {
1537
- const attrMap = signalAttrDisposers.get(elm);
1538
- if (attrMap) {
1539
- attrMap.get(memberName)?.();
1540
- attrMap.delete(memberName);
1541
- }
1542
- }
1543
- let isProp = isMemberInElement(elm, memberName);
1544
- let ln = memberName.toLowerCase();
1545
- if (BUILD.vdomClass && memberName === "class") {
1546
- const classList = elm.classList;
1547
- const oldClasses = parseClassList(oldValue);
1548
- let newClasses = parseClassList(newValue);
1549
- if (BUILD.hydrateClientSide && (elm["s-si"] || elm["s-sc"]) && initialRender) {
1550
- const scopeId = elm["s-sc"] || elm["s-si"];
1551
- newClasses.push(scopeId);
1552
- oldClasses.forEach((c) => {
1553
- if (c.startsWith(scopeId)) newClasses.push(c);
1554
- });
1555
- newClasses = [...new Set(newClasses)].filter((c) => c);
1556
- classList.add(...newClasses);
1557
- } else {
1558
- classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));
1559
- classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c)));
1560
- }
1561
- } else if (BUILD.vdomStyle && memberName === "style") {
1562
- if (BUILD.updatable) {
1563
- for (const prop in oldValue) if (!newValue || newValue[prop] == null) {
1564
- if (!BUILD.hydrateServerSide && prop.includes("-")) elm.style.removeProperty(prop);
1565
- else elm.style[prop] = "";
1566
- }
1567
- }
1568
- for (const prop in newValue) if (!oldValue || newValue[prop] !== oldValue[prop]) {
1569
- if (!BUILD.hydrateServerSide && prop.includes("-")) elm.style.setProperty(prop, newValue[prop]);
1570
- else elm.style[prop] = newValue[prop];
1571
- }
1572
- } else if (BUILD.vdomKey && memberName === "key") {} else if (BUILD.vdomRef && memberName === "ref") {
1573
- if (newValue) queueRefAttachment(newValue, elm);
1574
- } else if (BUILD.vdomListener && (BUILD.lazyLoad ? !isProp : !elm.__lookupSetter__(memberName)) && memberName[0] === "o" && memberName[1] === "n") {
1575
- if (memberName[2] === "-") memberName = memberName.slice(3);
1576
- else if (isMemberInElement(win, ln)) memberName = ln.slice(2);
1577
- else memberName = ln[2] + memberName.slice(3);
1578
- if (oldValue || newValue) {
1579
- const capture = memberName.endsWith(CAPTURE_EVENT_SUFFIX);
1580
- memberName = memberName.replace(/*@__PURE__*/ new RegExp(CAPTURE_EVENT_SUFFIX + "$"), "");
1581
- if (oldValue) plt.rel(elm, memberName, oldValue, capture);
1582
- if (newValue) plt.ael(elm, memberName, newValue, capture);
1583
- }
1584
- } else if (BUILD.vdomPropOrAttr && memberName[0] === "a" && memberName.startsWith("attr:")) {
1585
- const propName = memberName.slice(5);
1586
- let attrName;
1587
- if (BUILD.member) {
1588
- const hostRef = getHostRef(elm);
1589
- if (hostRef && hostRef.$cmpMeta$ && hostRef.$cmpMeta$.$members$) {
1590
- const memberMeta = hostRef.$cmpMeta$.$members$[propName];
1591
- if (memberMeta && memberMeta[1]) attrName = memberMeta[1];
1592
- }
1593
- }
1594
- if (!attrName) attrName = propName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
1595
- if (newValue == null || newValue === false) {
1596
- if (newValue !== false || elm.getAttribute(attrName) === "") elm.removeAttribute(attrName);
1597
- } else elm.setAttribute(attrName, newValue === true ? "" : newValue);
1598
- return;
1599
- } else if (BUILD.vdomPropOrAttr && memberName[0] === "p" && memberName.startsWith("prop:")) {
1600
- const propName = memberName.slice(5);
1601
- try {
1602
- elm[propName] = newValue;
1603
- } catch {}
1604
- return;
1605
- } else if (BUILD.vdomPropOrAttr) {
1606
- const isComplex = isComplexType(newValue);
1607
- if (!BUILD.lazyLoad) {
1608
- const isStandardAttr = ln.startsWith("aria-") || ln.startsWith("data-");
1609
- if (!isProp && !isStandardAttr && elm.tagName?.includes("-") && elm.tagName !== "SLOT-FB" && typeof customElements !== "undefined" && !customElements.get(elm.tagName.toLowerCase())) {
1610
- if (!elm["s-pp"]) elm["s-pp"] = /* @__PURE__ */ new Map();
1611
- elm["s-pp"].set(memberName, newValue);
1612
- return;
1613
- }
1614
- }
1615
- if ((isProp || isComplex && newValue !== null) && !isSvg) try {
1616
- if (!elm.tagName.includes("-")) {
1617
- const n = newValue == null ? "" : newValue;
1618
- if (memberName === "list") isProp = false;
1619
- else if (oldValue == null || elm[memberName] !== n) {
1620
- if (typeof elm.__lookupSetter__(memberName) === "function") elm[memberName] = n;
1621
- else elm.setAttribute(memberName, n);
1622
- }
1623
- } else if (elm[memberName] !== newValue) elm[memberName] = newValue;
1624
- } catch {}
1625
- /**
1626
- * Need to manually update attribute if:
1627
- * - memberName is not an attribute
1628
- * - if we are rendering the host element in order to reflect attribute
1629
- * - if it's a SVG, since properties might not work in <svg>
1630
- * - if the newValue is null/undefined or 'false'.
1631
- */
1632
- let xlink = false;
1633
- if (BUILD.vdomXlink) {
1634
- if (ln !== (ln = ln.replace(/^xlink:?/, ""))) {
1635
- memberName = ln;
1636
- xlink = true;
1637
- }
1638
- }
1639
- if (newValue == null || newValue === false) {
1640
- if (newValue !== false || elm.getAttribute(memberName) === "" || flags & VNODE_FLAGS.isHost && !isEnumeratedAttribute(memberName)) {
1641
- if (BUILD.vdomXlink && xlink) elm.removeAttributeNS(XLINK_NS, memberName);
1642
- else elm.removeAttribute(memberName);
1643
- }
1644
- } else if ((!isProp || flags & VNODE_FLAGS.isHost || isSvg) && !isComplex && elm.nodeType === NODE_TYPE.ElementNode) {
1645
- newValue = newValue === true ? "" : newValue;
1646
- if (BUILD.vdomXlink && xlink) elm.setAttributeNS(XLINK_NS, memberName, newValue);
1647
- else elm.setAttribute(memberName, newValue);
1648
- }
1649
- }
1650
- };
1651
- /**
1652
- * Attribute names that are enumerated (tri-state true/false/unset) rather than
1653
- * plain boolean-presence attributes. An explicit `"false"` string on one of
1654
- * these is semantically different from the attribute being absent, so a
1655
- * reflected `false` value must not clear a pre-existing literal value.
1656
- */
1657
- const ENUMERATED_ATTRIBUTES = /*@__PURE__*/ new Set([
1658
- "draggable",
1659
- "contenteditable",
1660
- "spellcheck"
1661
- ]);
1662
- const isEnumeratedAttribute = (attrName) => ENUMERATED_ATTRIBUTES.has(attrName) || attrName.startsWith("aria-");
1663
- const parseClassListRegex = /\s/;
1664
- /**
1665
- * Parsed a string of classnames into an array
1666
- * @param value className string, e.g. "foo bar baz"
1667
- * @returns list of classes, e.g. ["foo", "bar", "baz"]
1668
- */
1669
- const parseClassList = (value) => {
1670
- if (typeof value === "object" && value && "baseVal" in value) value = value.baseVal;
1671
- if (!value || typeof value !== "string") return [];
1672
- return value.split(parseClassListRegex);
1673
- };
1674
- const CAPTURE_EVENT_SUFFIX = "Capture";
1675
- //#endregion
1676
- //#region src/runtime/vdom/update-element.ts
1677
- /**
1678
- * Handle updating attributes on the component element based on the current
1679
- * values present in the virtual DOM.
1680
- *
1681
- * If the component of interest uses shadow DOM these are added to the shadow
1682
- * root's host element.
1683
- *
1684
- * @param oldVnode an old virtual DOM node or null
1685
- * @param newVnode a new virtual DOM node
1686
- * @param isSvgMode whether or not we're in an SVG context
1687
- * @param isInitialRender whether this is the first render of the VDOM
1688
- */
1689
- const updateElement = (oldVnode, newVnode, isSvgMode, isInitialRender) => {
1690
- const oldVnodeAttrs = oldVnode && oldVnode.$attrs$ || {};
1691
- const newVnodeAttrs = newVnode.$attrs$ || {};
1692
- const oldKeys = Object.keys(oldVnodeAttrs);
1693
- const newKeys = Object.keys(newVnodeAttrs);
1694
- if (!BUILD.updatable && newKeys.length === 0) return;
1695
- if (BUILD.updatable && oldKeys.length === 0 && newKeys.length === 0) return;
1696
- const elm = newVnode.$elm$.nodeType === NODE_TYPE.DocumentFragment && newVnode.$elm$.host ? newVnode.$elm$.host : newVnode.$elm$;
1697
- if (BUILD.updatable) {
1698
- for (const memberName of sortedAttrNames(oldKeys)) if (!(memberName in newVnodeAttrs)) setAccessor(elm, memberName, oldVnodeAttrs[memberName], void 0, isSvgMode, newVnode.$flags$, isInitialRender);
1699
- }
1700
- for (const memberName of sortedAttrNames(newKeys)) setAccessor(elm, memberName, oldVnodeAttrs[memberName], newVnodeAttrs[memberName], isSvgMode, newVnode.$flags$, isInitialRender);
1701
- };
1702
- /**
1703
- * Sort a list of attribute names to ensure that all the attribute names which
1704
- * are _not_ `"ref"` come before `"ref"`. Preserve the order of the non-ref
1705
- * attributes.
1706
- *
1707
- * **Note**: if the supplied attributes do not include `'ref'` then the same
1708
- * (by reference) array will be returned without modification.
1709
- *
1710
- * @param attrNames attribute names to sort
1711
- * @returns a list of attribute names, sorted if they include `"ref"`
1712
- */
1713
- function sortedAttrNames(attrNames) {
1714
- if (!BUILD.vdomRef) return attrNames;
1715
- return attrNames.includes("ref") ? [...attrNames.filter((attr) => attr !== "ref"), "ref"] : attrNames;
1716
- }
1717
- //#endregion
1718
- //#region src/runtime/vdom/vdom-render.ts
1719
- /**
1720
- * Virtual DOM patching algorithm based on Snabbdom by
1721
- * Simon Friis Vindum (@paldepind)
1722
- * Licensed under the MIT License
1723
- * https://github.com/snabbdom/snabbdom/blob/master/LICENSE
1724
- *
1725
- * Modified for Stencil's renderer and slot projection
1726
- */
1727
- let scopeId;
1728
- let contentRef;
1729
- let hostTagName;
1730
- let useNativeShadowDom = false;
1731
- let checkSlotFallbackVisibility = false;
1732
- let checkSlotRelocate = false;
1733
- let isSvgMode = false;
1734
- /**
1735
- * Queues for ref callbacks that need to be called during rendering.
1736
- * These ensure that ref callbacks are called in the correct order:
1737
- * first all removal callbacks (with null), then all attachment callbacks (with elements).
1738
- */
1739
- const refCallbacksToRemove = [];
1740
- const refCallbacksToAttach = [];
1741
- /** Disposers for signal subscriptions on individual DOM nodes (text nodes, <s-show> wrappers). */
1742
- const signalNodeDisposers = /* @__PURE__ */ new WeakMap();
1743
- const disposeSignalVNode = (vnode) => {
1744
- const elm = vnode.$elm$;
1745
- if (elm) {
1746
- const dispose = signalNodeDisposers.get(elm);
1747
- if (dispose) {
1748
- dispose();
1749
- signalNodeDisposers.delete(elm);
1750
- }
1751
- disposeAllSignalAttrs(elm);
1752
- }
1753
- vnode.$children$?.forEach(disposeSignalVNode);
1754
- };
1755
- /**
1756
- * Create a DOM Node corresponding to one of the children of a given VNode.
1757
- *
1758
- * @param oldParentVNode the parent VNode from the previous render
1759
- * @param newParentVNode the parent VNode from the current render
1760
- * @param childIndex the index of the VNode, in the _new_ parent node's
1761
- * children, for which we will create a new DOM node
1762
- * @returns the newly created node
1763
- */
1764
- const createElm = (oldParentVNode, newParentVNode, childIndex) => {
1765
- const newVNode = newParentVNode.$children$[childIndex];
1766
- let i = 0;
1767
- let elm;
1768
- let childNode;
1769
- let oldVNode;
1770
- if (BUILD.slotRelocation && !useNativeShadowDom) {
1771
- checkSlotRelocate = true;
1772
- if (newVNode.$tag$ === "slot") newVNode.$flags$ |= newVNode.$children$ ? VNODE_FLAGS.isSlotFallback : VNODE_FLAGS.isSlotReference;
1773
- }
1774
- if (BUILD.isDev && newVNode.$elm$) consoleDevError(`The JSX ${newVNode.$text$ !== null ? `"${newVNode.$text$}" text` : `"${String(newVNode.$tag$)}" element`} node should not be shared within the same renderer. The renderer caches element lookups in order to improve performance. However, a side effect from this is that the exact same JSX node should not be reused. For more information please see https://stenciljs.com/docs/templating-jsx#avoid-shared-jsx-nodes`);
1775
- if (BUILD.vdomText && newVNode.$text$ != null) {
1776
- elm = newVNode.$elm$ = win.document.createTextNode(newVNode.$text$);
1777
- if (BUILD.vdomSignals && newVNode.$signal$) {
1778
- const textSig = newVNode.$signal$;
1779
- const textNode = elm;
1780
- signalNodeDisposers.set(textNode, effect$1(() => {
1781
- textNode.data = String(textSig.value);
1782
- }));
1783
- }
1784
- } else if (BUILD.slotRelocation && newVNode.$flags$ & VNODE_FLAGS.isSlotReference) {
1785
- elm = newVNode.$elm$ = BUILD.isDebug || BUILD.hydrateServerSide ? slotReferenceDebugNode(newVNode) : win.document.createTextNode("");
1786
- if (typeof newVNode.$attrs$?.slot === "string") elm["s-sa"] = newVNode.$attrs$.slot;
1787
- if (BUILD.vdomAttribute) updateElement(null, newVNode, isSvgMode);
1788
- } else {
1789
- if (BUILD.svg && !isSvgMode) isSvgMode = newVNode.$tag$ === "svg";
1790
- if (!win.document) throw new Error("No DOM environment available for rendering.");
1791
- const tag = !useNativeShadowDom && BUILD.slotRelocation && newVNode.$flags$ & VNODE_FLAGS.isSlotFallback ? "slot-fb" : newVNode.$tag$;
1792
- const _reg = getRegistry();
1793
- const registryOpts = _reg !== win.customElements && tag.includes("-") ? { customElementRegistry: _reg } : void 0;
1794
- elm = newVNode.$elm$ = BUILD.svg && isSvgMode ? win.document.createElementNS(SVG_NS, tag) : win.document.createElement(tag, registryOpts);
1795
- if (BUILD.svg && isSvgMode && newVNode.$tag$ === "foreignObject") isSvgMode = false;
1796
- if (BUILD.vdomAttribute) updateElement(null, newVNode, isSvgMode);
1797
- if ((BUILD.scoped || BUILD.hydrateServerSide && CMP_FLAGS.shadowNeedsScopedCss) && isDef(scopeId) && elm["s-si"] !== scopeId) elm.classList.add(elm["s-si"] = scopeId);
1798
- if (newVNode.$children$) {
1799
- const appendTarget = newVNode.$tag$ === "template" ? elm.content : elm;
1800
- for (i = 0; i < newVNode.$children$.length; ++i) {
1801
- childNode = createElm(oldParentVNode, newVNode, i);
1802
- if (childNode) appendTarget.appendChild(childNode);
1803
- }
1804
- }
1805
- if (BUILD.svg) {
1806
- if (newVNode.$tag$ === "svg") isSvgMode = false;
1807
- else if (elm.tagName === "foreignObject") isSvgMode = true;
1808
- }
1809
- }
1810
- elm["s-hn"] = hostTagName;
1811
- if (BUILD.slotRelocation) {
1812
- if (newVNode.$flags$ & (VNODE_FLAGS.isSlotFallback | VNODE_FLAGS.isSlotReference)) {
1813
- elm["s-sr"] = true;
1814
- elm["s-cr"] = contentRef;
1815
- elm["s-sn"] = newVNode.$name$ || "";
1816
- elm["s-rf"] = newVNode.$attrs$?.ref;
1817
- patchSlotNode(elm);
1818
- oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex];
1819
- if (oldVNode && oldVNode.$tag$ === newVNode.$tag$ && oldParentVNode.$elm$) relocateToHostRoot(oldParentVNode.$elm$);
1820
- if (BUILD.scoped || BUILD.hydrateServerSide && CMP_FLAGS.shadowNeedsScopedCss) addRemoveSlotScopedClass(contentRef, elm, newParentVNode.$elm$, oldParentVNode?.$elm$);
1821
- }
1822
- }
1823
- return elm;
1824
- };
1825
- /**
1826
- * Relocates all child nodes of an element that were a part of a previous slot relocation
1827
- * to the root of the Stencil component currently being rendered. This happens when a parent
1828
- * element of a slot reference node dynamically changes and triggers a re-render. We cannot use
1829
- * `putBackInOriginalLocation()` because that may relocate nodes to elements that will not be re-rendered
1830
- * and so they will not be relocated again.
1831
- *
1832
- * @param parentElm The element potentially containing relocated nodes.
1833
- */
1834
- const relocateToHostRoot = (parentElm) => {
1835
- plt.$flags$ |= PLATFORM_FLAGS.isTmpDisconnected;
1836
- const host = parentElm.closest(hostTagName.toLowerCase());
1837
- if (host != null) {
1838
- const contentRefNode = Array.from(host.__childNodes || host.childNodes).find((ref) => ref["s-cr"]);
1839
- const childNodeArray = Array.from(parentElm.__childNodes || parentElm.childNodes);
1840
- for (const childNode of contentRefNode ? childNodeArray.reverse() : childNodeArray) if (childNode["s-sh"] != null) {
1841
- insertBefore(host, childNode, contentRefNode ?? null);
1842
- childNode["s-sh"] = void 0;
1843
- checkSlotRelocate = true;
1844
- }
1845
- }
1846
- plt.$flags$ &= ~PLATFORM_FLAGS.isTmpDisconnected;
1847
- };
1848
- /**
1849
- * Puts `<slot>` nodes and any slotted nodes back to their original location (wherever they were before being slotted).
1850
- *
1851
- * @param parentElm - The parent element of the nodes to relocate.
1852
- * @param recursive - Whether or not to relocate nodes in child nodes as well.
1853
- */
1854
- const putBackInOriginalLocation = (parentElm, recursive) => {
1855
- plt.$flags$ |= PLATFORM_FLAGS.isTmpDisconnected;
1856
- const oldSlotChildNodes = Array.from(parentElm.__childNodes || parentElm.childNodes);
1857
- if (parentElm["s-sr"]) {
1858
- let node = parentElm;
1859
- while (node = node.nextSibling) if (node && node["s-sn"] === parentElm["s-sn"] && node["s-sh"] === hostTagName) oldSlotChildNodes.push(node);
1860
- }
1861
- for (let i = oldSlotChildNodes.length - 1; i >= 0; i--) {
1862
- const childNode = oldSlotChildNodes[i];
1863
- if (childNode["s-hn"] !== hostTagName && childNode["s-ol"]) {
1864
- insertBefore(referenceNode(childNode).parentNode, childNode, referenceNode(childNode));
1865
- childNode["s-ol"].remove();
1866
- childNode["s-ol"] = void 0;
1867
- childNode["s-sh"] = void 0;
1868
- checkSlotRelocate = true;
1869
- }
1870
- if (recursive) putBackInOriginalLocation(childNode, recursive);
1871
- }
1872
- plt.$flags$ &= ~PLATFORM_FLAGS.isTmpDisconnected;
1873
- };
1874
- /**
1875
- * Create DOM nodes corresponding to a list of {@link d.Vnode} objects and
1876
- * add them to the DOM in the appropriate place.
1877
- *
1878
- * @param parentElm the DOM node which should be used as a parent for the new
1879
- * DOM nodes
1880
- * @param before a child of the `parentElm` which the new children should be
1881
- * inserted before (optional)
1882
- * @param parentVNode the parent virtual DOM node
1883
- * @param vnodes the new child virtual DOM nodes to produce DOM nodes for
1884
- * @param startIdx the index in the child virtual DOM nodes at which to start
1885
- * creating DOM nodes (inclusive)
1886
- * @param endIdx the index in the child virtual DOM nodes at which to stop
1887
- * creating DOM nodes (inclusive)
1888
- */
1889
- const addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {
1890
- let containerElm = BUILD.slotRelocation && parentElm["s-cr"] && parentElm["s-cr"].parentNode || parentElm;
1891
- let childNode;
1892
- if (BUILD.shadowDom && containerElm.tagName === hostTagName) {
1893
- const shadow = getShadowRoot(containerElm);
1894
- if (shadow) containerElm = shadow;
1895
- }
1896
- if (parentVNode.$tag$ === "template") containerElm = containerElm.content;
1897
- for (; startIdx <= endIdx; ++startIdx) if (vnodes[startIdx]) {
1898
- childNode = createElm(null, parentVNode, startIdx);
1899
- if (childNode) {
1900
- vnodes[startIdx].$elm$ = childNode;
1901
- insertBefore(containerElm, childNode, BUILD.slotRelocation ? referenceNode(before) : before);
1902
- }
1903
- }
1904
- };
1905
- /**
1906
- * Remove the DOM elements corresponding to a list of {@link d.VNode} objects.
1907
- * This can be used to, for instance, clean up after a list of children which
1908
- * should no longer be shown.
1909
- *
1910
- * This function also handles some of Stencil's slot relocation logic.
1911
- *
1912
- * @param vnodes a list of virtual DOM nodes to remove
1913
- * @param startIdx the index at which to start removing nodes (inclusive)
1914
- * @param endIdx the index at which to stop removing nodes (inclusive)
1915
- */
1916
- const removeVnodes = (vnodes, startIdx, endIdx) => {
1917
- for (let index = startIdx; index <= endIdx; ++index) {
1918
- const vnode = vnodes[index];
1919
- if (vnode) {
1920
- const elm = vnode.$elm$;
1921
- nullifyVNodeRefs(vnode);
1922
- if (BUILD.vdomSignals) disposeSignalVNode(vnode);
1923
- if (elm) {
1924
- if (BUILD.slotRelocation) {
1925
- checkSlotFallbackVisibility = true;
1926
- if (elm["s-ol"]) elm["s-ol"].remove();
1927
- else putBackInOriginalLocation(elm, true);
1928
- }
1929
- elm.remove();
1930
- }
1931
- }
1932
- }
1933
- };
1934
- /**
1935
- * Reconcile the children of a new VNode with the children of an old VNode by
1936
- * traversing the two collections of children, identifying nodes that are
1937
- * conserved or changed, calling out to `patch` to make any necessary
1938
- * updates to the DOM, and rearranging DOM nodes as needed.
1939
- *
1940
- * The algorithm for reconciling children works by analyzing two 'windows' onto
1941
- * the two arrays of children (`oldCh` and `newCh`). We keep track of the
1942
- * 'windows' by storing start and end indices and references to the
1943
- * corresponding array entries. Initially the two 'windows' are basically equal
1944
- * to the entire array, but we progressively narrow the windows until there are
1945
- * no children left to update by doing the following:
1946
- *
1947
- * 1. Skip any `null` entries at the beginning or end of the two arrays, so
1948
- * that if we have an initial array like the following we'll end up dealing
1949
- * only with a window bounded by the highlighted elements:
1950
- *
1951
- * [null, null, VNode1 , ... , VNode2, null, null]
1952
- * ^^^^^^ ^^^^^^
1953
- *
1954
- * 2. Check to see if the elements at the head and tail positions are equal
1955
- * across the windows. This will basically detect elements which haven't
1956
- * been added, removed, or changed position, i.e. if you had the following
1957
- * VNode elements (represented as HTML):
1958
- *
1959
- * oldVNode: `<div><p><span>HEY</span></p></div>`
1960
- * newVNode: `<div><p><span>THERE</span></p></div>`
1961
- *
1962
- * Then when comparing the children of the `<div>` tag we check the equality
1963
- * of the VNodes corresponding to the `<p>` tags and, since they are the
1964
- * same tag in the same position, we'd be able to avoid completely
1965
- * re-rendering the subtree under them with a new DOM element and would just
1966
- * call out to `patch` to handle reconciling their children and so on.
1967
- *
1968
- * 3. Check, for both windows, to see if the element at the beginning of the
1969
- * window corresponds to the element at the end of the other window. This is
1970
- * a heuristic which will let us identify _some_ situations in which
1971
- * elements have changed position, for instance it _should_ detect that the
1972
- * children nodes themselves have not changed but merely moved in the
1973
- * following example:
1974
- *
1975
- * oldVNode: `<div><element-one /><element-two /></div>`
1976
- * newVNode: `<div><element-two /><element-one /></div>`
1977
- *
1978
- * If we find cases like this then we also need to move the concrete DOM
1979
- * elements corresponding to the moved children to write the re-order to the
1980
- * DOM.
1981
- *
1982
- * 4. Finally, if VNodes have the `key` attribute set on them we check for any
1983
- * nodes in the old children which have the same key as the first element in
1984
- * our window on the new children. If we find such a node we handle calling
1985
- * out to `patch`, moving relevant DOM nodes, and so on, in accordance with
1986
- * what we find.
1987
- *
1988
- * Finally, once we've narrowed our 'windows' to the point that either of them
1989
- * collapse (i.e. they have length 0) we then handle any remaining VNode
1990
- * insertion or deletion that needs to happen to get a DOM state that correctly
1991
- * reflects the new child VNodes. If, for instance, after our window on the old
1992
- * children has collapsed we still have more nodes on the new children that
1993
- * we haven't dealt with yet then we need to add them, or if the new children
1994
- * collapse but we still have unhandled _old_ children then we need to make
1995
- * sure the corresponding DOM nodes are removed.
1996
- *
1997
- * @param parentElm the node into which the parent VNode is rendered
1998
- * @param oldCh the old children of the parent node
1999
- * @param newVNode the new VNode which will replace the parent
2000
- * @param newCh the new children of the parent node
2001
- * @param isInitialRender whether or not this is the first render of the vdom
2002
- */
2003
- const updateChildren = (parentElm, oldCh, newVNode, newCh, isInitialRender = false) => {
2004
- let oldStartIdx = 0;
2005
- let newStartIdx = 0;
2006
- let idxInOld = 0;
2007
- let i = 0;
2008
- let oldEndIdx = oldCh.length - 1;
2009
- let oldStartVnode = oldCh[0];
2010
- let oldEndVnode = oldCh[oldEndIdx];
2011
- let newEndIdx = newCh.length - 1;
2012
- let newStartVnode = newCh[0];
2013
- let newEndVnode = newCh[newEndIdx];
2014
- let node;
2015
- let elmToMove;
2016
- const containerElm = newVNode.$tag$ === "template" ? parentElm.content : parentElm;
2017
- while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) if (oldStartVnode == null) oldStartVnode = oldCh[++oldStartIdx];
2018
- else if (oldEndVnode == null) oldEndVnode = oldCh[--oldEndIdx];
2019
- else if (newStartVnode == null) newStartVnode = newCh[++newStartIdx];
2020
- else if (newEndVnode == null) newEndVnode = newCh[--newEndIdx];
2021
- else if (isSameVnode(oldStartVnode, newStartVnode, isInitialRender)) {
2022
- patch(oldStartVnode, newStartVnode, isInitialRender);
2023
- oldStartVnode = oldCh[++oldStartIdx];
2024
- newStartVnode = newCh[++newStartIdx];
2025
- } else if (isSameVnode(oldEndVnode, newEndVnode, isInitialRender)) {
2026
- patch(oldEndVnode, newEndVnode, isInitialRender);
2027
- oldEndVnode = oldCh[--oldEndIdx];
2028
- newEndVnode = newCh[--newEndIdx];
2029
- } else if (isSameVnode(oldStartVnode, newEndVnode, isInitialRender)) {
2030
- if (BUILD.slotRelocation && (oldStartVnode.$tag$ === "slot" || newEndVnode.$tag$ === "slot")) putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false);
2031
- patch(oldStartVnode, newEndVnode, isInitialRender);
2032
- insertBefore(containerElm, oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);
2033
- oldStartVnode = oldCh[++oldStartIdx];
2034
- newEndVnode = newCh[--newEndIdx];
2035
- } else if (isSameVnode(oldEndVnode, newStartVnode, isInitialRender)) {
2036
- if (BUILD.slotRelocation && (oldStartVnode.$tag$ === "slot" || newEndVnode.$tag$ === "slot")) putBackInOriginalLocation(oldEndVnode.$elm$.parentNode, false);
2037
- patch(oldEndVnode, newStartVnode, isInitialRender);
2038
- insertBefore(containerElm, oldEndVnode.$elm$, oldStartVnode.$elm$);
2039
- oldEndVnode = oldCh[--oldEndIdx];
2040
- newStartVnode = newCh[++newStartIdx];
2041
- } else {
2042
- idxInOld = -1;
2043
- if (BUILD.vdomKey) {
2044
- for (i = oldStartIdx; i <= oldEndIdx; ++i) if (oldCh[i] && oldCh[i].$key$ !== null && oldCh[i].$key$ === newStartVnode.$key$) {
2045
- idxInOld = i;
2046
- break;
2047
- }
2048
- }
2049
- if (BUILD.vdomKey && idxInOld >= 0) {
2050
- elmToMove = oldCh[idxInOld];
2051
- if (elmToMove.$tag$ !== newStartVnode.$tag$) node = createElm(oldCh && oldCh[newStartIdx], newVNode, idxInOld);
2052
- else {
2053
- patch(elmToMove, newStartVnode, isInitialRender);
2054
- oldCh[idxInOld] = void 0;
2055
- node = elmToMove.$elm$;
2056
- }
2057
- newStartVnode = newCh[++newStartIdx];
2058
- } else {
2059
- node = createElm(oldCh && oldCh[newStartIdx], newVNode, newStartIdx);
2060
- newStartVnode = newCh[++newStartIdx];
2061
- }
2062
- if (node) {
2063
- if (BUILD.slotRelocation) insertBefore(referenceNode(oldStartVnode.$elm$).parentNode, node, referenceNode(oldStartVnode.$elm$));
2064
- else insertBefore(oldStartVnode.$elm$.parentNode, node, oldStartVnode.$elm$);
2065
- }
2066
- }
2067
- if (oldStartIdx > oldEndIdx) addVnodes(parentElm, newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$, newVNode, newCh, newStartIdx, newEndIdx);
2068
- else if (BUILD.updatable && newStartIdx > newEndIdx) removeVnodes(oldCh, oldStartIdx, oldEndIdx);
2069
- };
2070
- /**
2071
- * Compare two VNodes to determine if they are the same
2072
- *
2073
- * **NB**: This function is an equality _heuristic_ based on the available
2074
- * information set on the two VNodes and can be misleading under certain
2075
- * circumstances. In particular, if the two nodes do not have `key` attrs
2076
- * (available under `$key$` on VNodes) then the function falls back on merely
2077
- * checking that they have the same tag.
2078
- *
2079
- * So, in other words, if `key` attrs are not set on VNodes which may be
2080
- * changing order within a `children` array or something along those lines then
2081
- * we could obtain a false negative and then have to do needless re-rendering
2082
- * (i.e. we'd say two VNodes aren't equal when in fact they should be).
2083
- *
2084
- * @param leftVNode the first VNode to check
2085
- * @param rightVNode the second VNode to check
2086
- * @param isInitialRender whether or not this is the first render of the vdom
2087
- * @returns whether they're equal or not
2088
- */
2089
- const isSameVnode = (leftVNode, rightVNode, isInitialRender = false) => {
2090
- if (leftVNode.$tag$ === rightVNode.$tag$) {
2091
- if (BUILD.slotRelocation && leftVNode.$tag$ === "slot") return leftVNode.$name$ === rightVNode.$name$;
2092
- if (BUILD.vdomKey && !isInitialRender) return leftVNode.$key$ === rightVNode.$key$;
2093
- if (isInitialRender && !leftVNode.$key$ && rightVNode.$key$) leftVNode.$key$ = rightVNode.$key$;
2094
- return true;
2095
- }
2096
- return false;
2097
- };
2098
- /**
2099
- * Returns the reference node (a comment which represents the
2100
- * original location of a node in the vdom - before it was moved to its slot)
2101
- * of a given node.
2102
- *
2103
- * (slot nodes can be relocated to a new location in the dom because of
2104
- * some other component's slot)
2105
- * @param node the node to find the original location reference node for
2106
- * @returns reference node
2107
- */
2108
- const referenceNode = (node) => node && node["s-ol"] || node;
2109
- /**
2110
- * Handle reconciling an outdated VNode with a new one which corresponds to
2111
- * it. This function handles flushing updates to the DOM and reconciling the
2112
- * children of the two nodes (if any).
2113
- *
2114
- * @param oldVNode an old VNode whose DOM element and children we want to update
2115
- * @param newVNode a new VNode representing an updated version of the old one
2116
- * @param isInitialRender whether or not this is the first render of the vdom
2117
- */
2118
- const patch = (oldVNode, newVNode, isInitialRender = false) => {
2119
- const elm = newVNode.$elm$ = oldVNode.$elm$;
2120
- const oldChildren = oldVNode.$children$;
2121
- const newChildren = newVNode.$children$;
2122
- const tag = newVNode.$tag$;
2123
- const text = newVNode.$text$;
2124
- let defaultHolder;
2125
- if (!BUILD.vdomText || text == null) {
2126
- if (BUILD.svg) isSvgMode = tag === "svg" ? true : tag === "foreignObject" ? false : isSvgMode;
2127
- if (BUILD.vdomAttribute || BUILD.reflect) {
2128
- if (BUILD.slot && tag === "slot" && !useNativeShadowDom) {
2129
- if (oldVNode.$name$ !== newVNode.$name$) {
2130
- newVNode.$elm$["s-sn"] = newVNode.$name$ || "";
2131
- relocateToHostRoot(newVNode.$elm$.parentElement);
2132
- }
2133
- }
2134
- updateElement(oldVNode, newVNode, isSvgMode, isInitialRender);
2135
- }
2136
- if (BUILD.updatable && oldChildren !== null && newChildren !== null) updateChildren(elm, oldChildren, newVNode, newChildren, isInitialRender);
2137
- else if (newChildren !== null) {
2138
- if (BUILD.updatable && BUILD.vdomText && oldVNode.$text$ !== null) elm.textContent = "";
2139
- addVnodes(elm, null, newVNode, newChildren, 0, newChildren.length - 1);
2140
- } else if (!isInitialRender && BUILD.updatable && oldChildren !== null) removeVnodes(oldChildren, 0, oldChildren.length - 1);
2141
- else if (BUILD.hydrateClientSide && isInitialRender && BUILD.updatable && oldChildren !== null && newChildren === null) newVNode.$children$ = oldChildren;
2142
- if (BUILD.svg && isSvgMode && tag === "svg") isSvgMode = false;
2143
- } else if (BUILD.vdomText && BUILD.slotRelocation && (defaultHolder = elm["s-cr"])) defaultHolder.parentNode.textContent = text;
2144
- else if (BUILD.vdomText && oldVNode.$text$ !== text) elm.data = text;
2145
- };
2146
- /**
2147
- * Component-global information about nodes which are either currently being
2148
- * relocated or will be shortly.
2149
- */
2150
- const relocateNodes = [];
2151
- /**
2152
- * When a forwarded `<slot>` gets relocated, drag along any content already forwarded through it,
2153
- * to wherever it just landed (or nowhere, to be hidden, if it didn't match anything).
2154
- *
2155
- * Runs as its own pass after {@link markSlotContentForRelocation} rather than inside it, so that
2156
- * function's matching order - which hydration's node/comment ordering depends on - is untouched.
2157
- */
2158
- const carryContentWithRelocatedSlotRefs = () => {
2159
- for (const relocateData of relocateNodes.slice()) {
2160
- const marker = relocateData.$nodeToRelocate$;
2161
- if (!marker["s-sr"]) continue;
2162
- const carriedSiblings = getSlotChildSiblings(marker, marker["s-sn"] || "", false);
2163
- for (const carriedSibling of carriedSiblings) {
2164
- if (!carriedSibling["s-ol"]) continue;
2165
- let siblingRelocateData = relocateNodes.find((r) => r.$nodeToRelocate$ === carriedSibling);
2166
- if (!siblingRelocateData) {
2167
- siblingRelocateData = { $nodeToRelocate$: carriedSibling };
2168
- relocateNodes.push(siblingRelocateData);
2169
- }
2170
- siblingRelocateData.$slotRefNode$ = relocateData.$slotRefNode$;
2171
- if (relocateData.$slotRefNode$) carriedSibling["s-sh"] = relocateData.$slotRefNode$["s-hn"];
2172
- }
2173
- }
2174
- };
2175
- /**
2176
- * Mark the contents of a slot for relocation via adding references to them to
2177
- * the {@link relocateNodes} data structure. The actual work of relocating them
2178
- * will then be handled in {@link renderVdom}.
2179
- *
2180
- * @param elm a render node whose child nodes need to be relocated
2181
- */
2182
- const markSlotContentForRelocation = (elm) => {
2183
- let node;
2184
- let hostContentNodes;
2185
- let j;
2186
- const children = elm.__childNodes || elm.childNodes;
2187
- for (const childNode of children) {
2188
- if (childNode["s-sr"] && (node = childNode["s-cr"]) && node.parentNode) {
2189
- hostContentNodes = node.parentNode.__childNodes || node.parentNode.childNodes;
2190
- const slotName = childNode["s-sn"];
2191
- for (j = hostContentNodes.length - 1; j >= 0; j--) {
2192
- node = hostContentNodes[j];
2193
- if (!node["s-cn"] && !node["s-nr"] && node["s-hn"] !== childNode["s-hn"] && (!node["s-sh"] || node["s-sh"] !== childNode["s-hn"])) {
2194
- if (isNodeLocatedInSlot(node, slotName)) {
2195
- let relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
2196
- checkSlotFallbackVisibility = true;
2197
- node["s-sn"] = node["s-sn"] || slotName;
2198
- if (relocateNodeData) {
2199
- relocateNodeData.$nodeToRelocate$["s-sh"] = childNode["s-hn"];
2200
- relocateNodeData.$slotRefNode$ = childNode;
2201
- } else {
2202
- node["s-sh"] = childNode["s-hn"];
2203
- relocateNodes.push({
2204
- $slotRefNode$: childNode,
2205
- $nodeToRelocate$: node
2206
- });
2207
- }
2208
- if (node["s-sr"]) relocateNodes.map((relocateNode) => {
2209
- if (isNodeLocatedInSlot(relocateNode.$nodeToRelocate$, node["s-sn"])) {
2210
- relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
2211
- if (relocateNodeData && !relocateNode.$slotRefNode$) relocateNode.$slotRefNode$ = relocateNodeData.$slotRefNode$;
2212
- }
2213
- });
2214
- } else if (!relocateNodes.some((r) => r.$nodeToRelocate$ === node)) relocateNodes.push({ $nodeToRelocate$: node });
2215
- }
2216
- }
2217
- }
2218
- if (childNode.nodeType === NODE_TYPE.ElementNode) markSlotContentForRelocation(childNode);
2219
- }
2220
- };
2221
- /**
2222
- * 'Nullify' any VDom `ref` callbacks on a VDom node or its children by calling
2223
- * them with `null`. This signals that the DOM element corresponding to the VDom
2224
- * node has been removed from the DOM.
2225
- *
2226
- * @param vNode a virtual DOM node
2227
- */
2228
- const nullifyVNodeRefs = (vNode) => {
2229
- if (BUILD.vdomRef) {
2230
- if (vNode.$attrs$ && vNode.$attrs$.ref) refCallbacksToRemove.push(() => vNode.$attrs$.ref(null));
2231
- if (vNode.$children$) vNode.$children$.map(nullifyVNodeRefs);
2232
- }
2233
- };
2234
- /**
2235
- * Queue a ref callback to be called with an element during rendering.
2236
- * This ensures ref callbacks are called in the correct order.
2237
- *
2238
- * @param refCallback the ref callback function to queue
2239
- * @param elm the element to pass to the callback
2240
- */
2241
- const queueRefAttachment = (refCallback, elm) => {
2242
- if (BUILD.vdomRef) refCallbacksToAttach.push(() => refCallback(elm));
2243
- };
2244
- /**
2245
- * Flush all queued ref callbacks in the correct order:
2246
- * first all removal callbacks (with null), then all attachment callbacks (with elements).
2247
- * This ensures that when elements are replaced/reordered, the ref is always left
2248
- * pointing to the current element, not null.
2249
- */
2250
- const flushQueuedRefCallbacks = () => {
2251
- if (BUILD.vdomRef) {
2252
- refCallbacksToRemove.forEach((cb) => cb());
2253
- refCallbacksToRemove.length = 0;
2254
- refCallbacksToAttach.forEach((cb) => cb());
2255
- refCallbacksToAttach.length = 0;
2256
- }
2257
- };
2258
- /**
2259
- * Inserts a node before a reference node as a child of a specified parent node.
2260
- * Additionally, adds parent elements' scope ids as class names to the new node.
2261
- *
2262
- * @param parent parent node
2263
- * @param newNode element to be inserted
2264
- * @param reference anchor element
2265
- * @param isInitialLoad whether or not this is the first render
2266
- * @returns inserted node
2267
- */
2268
- const insertBefore = (parent, newNode, reference, isInitialLoad) => {
2269
- if (BUILD.slotRelocation) {
2270
- if (BUILD.scoped && typeof newNode["s-sn"] === "string" && !!newNode["s-sr"] && !!newNode["s-cr"]) addRemoveSlotScopedClass(newNode["s-cr"], newNode, parent, newNode.parentElement);
2271
- else if (typeof newNode["s-sn"] === "string") {
2272
- const hostElm = newNode["s-hn"] && parent.closest?.(newNode["s-hn"]);
2273
- if ((BUILD.lightDomPatches || BUILD.slotChildNodes || BUILD.patchAll && !!(hostElm && getHostRef(hostElm)?.$cmpMeta$.$flags$ & CMP_FLAGS.patchAll)) && parent.getRootNode().nodeType !== NODE_TYPES.DOCUMENT_FRAGMENT_NODE) patchParentNode(newNode);
2274
- parent.insertBefore(newNode, reference);
2275
- const { slotNode } = findSlotFromSlottedNode(newNode);
2276
- if (slotNode && !isInitialLoad) dispatchSlotChangeEvent(slotNode);
2277
- return newNode;
2278
- }
2279
- }
2280
- if (BUILD.slotRelocation && parent?.__insertBefore) return parent.__insertBefore(newNode, reference);
2281
- else return parent?.insertBefore(newNode, reference);
2282
- };
2283
- /**
2284
- * Adds or removes a scoped class to the parent element of a slotted node.
2285
- * This is used for styling slotted content (e.g. with `::scoped(...) {...}` selectors )
2286
- * in `scoped: true` components.
2287
- *
2288
- * @param reference - Content Reference Node. Used to get the scope id of the parent component.
2289
- * @param slotNode - the `<slot>` node to apply the class for
2290
- * @param newParent - the slots' new parent element that requires the scoped class
2291
- * @param oldParent - optionally, an old parent element that may no longer require the scoped class
2292
- */
2293
- function addRemoveSlotScopedClass(reference, slotNode, newParent, oldParent) {
2294
- let slotScopeId;
2295
- if (reference && typeof slotNode["s-sn"] === "string" && !!slotNode["s-sr"] && reference.parentNode && reference.parentNode["s-sc"] && (slotScopeId = slotNode["s-si"] || reference.parentNode["s-sc"])) {
2296
- const scopeName = slotNode["s-sn"];
2297
- const hostName = slotNode["s-hn"];
2298
- newParent.classList?.add(slotScopeId + "-s");
2299
- if (oldParent && oldParent.classList?.contains(slotScopeId + "-s")) {
2300
- let child = (oldParent.__childNodes || oldParent.childNodes)[0];
2301
- let found = false;
2302
- while (child) {
2303
- if (child["s-sn"] !== scopeName && child["s-hn"] === hostName && !!child["s-sr"]) {
2304
- found = true;
2305
- break;
2306
- }
2307
- child = child.nextSibling;
2308
- }
2309
- if (!found) oldParent.classList.remove(slotScopeId + "-s");
2310
- }
2311
- }
2312
- }
2313
- /**
2314
- * The main entry point for Stencil's virtual DOM-based rendering engine
2315
- *
2316
- * Given a {@link d.HostRef} container and some virtual DOM nodes, this
2317
- * function will handle creating a virtual DOM tree with a single root, patching
2318
- * the current virtual DOM tree onto an old one (if any), dealing with slot
2319
- * relocation, and reflecting attributes.
2320
- *
2321
- * @param hostRef data needed to root and render the virtual DOM tree, such as
2322
- * the DOM node into which it should be rendered.
2323
- * @param renderFnResults the virtual DOM nodes to be rendered
2324
- * @param isInitialLoad whether or not this is the first call after page load
2325
- */
2326
- const renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
2327
- const hostElm = hostRef.$hostElement$;
2328
- const cmpMeta = hostRef.$cmpMeta$;
2329
- const oldVNode = hostRef.$vnode$ || newVNode(null, null);
2330
- const rootVnode = isHost(renderFnResults) ? renderFnResults : h(null, null, renderFnResults);
2331
- hostTagName = hostElm.tagName;
2332
- if (BUILD.isDev && Array.isArray(renderFnResults) && renderFnResults.some(isHost)) throw new Error(`The <Host> must be the single root component.
2333
- Looks like the render() function of "${hostTagName.toLowerCase()}" is returning an array that contains the <Host>.
2334
-
2335
- The render() function should look like this instead:
2336
-
2337
- render() {
2338
- // Do not return an array
2339
- return (
2340
- <Host>{content}</Host>
2341
- );
2342
- }
2343
- `);
2344
- if (BUILD.reflect && cmpMeta.$attrsToReflect$) {
2345
- rootVnode.$attrs$ = rootVnode.$attrs$ || {};
2346
- cmpMeta.$attrsToReflect$.forEach(([propName, attribute]) => {
2347
- if (BUILD.serializer && hostRef.$serializerValues$.has(propName)) rootVnode.$attrs$[attribute] = hostRef.$serializerValues$.get(propName);
2348
- else rootVnode.$attrs$[attribute] = hostElm[propName];
2349
- });
2350
- }
2351
- if (isInitialLoad && rootVnode.$attrs$) {
2352
- for (const key of Object.keys(rootVnode.$attrs$)) if (hostElm.hasAttribute(key) && ![
2353
- "key",
2354
- "ref",
2355
- "style",
2356
- "class"
2357
- ].includes(key)) rootVnode.$attrs$[key] = hostElm[key];
2358
- }
2359
- rootVnode.$tag$ = null;
2360
- rootVnode.$flags$ |= VNODE_FLAGS.isHost;
2361
- hostRef.$vnode$ = rootVnode;
2362
- rootVnode.$elm$ = oldVNode.$elm$ = BUILD.shadowDom ? getShadowRoot(hostElm) || hostElm : hostElm;
2363
- if (BUILD.scoped || BUILD.shadowDom) scopeId = hostElm["s-sc"];
2364
- useNativeShadowDom = !!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) && !(cmpMeta.$flags$ & CMP_FLAGS.shadowNeedsScopedCss);
2365
- if (BUILD.slotRelocation) {
2366
- contentRef = hostElm["s-cr"];
2367
- checkSlotFallbackVisibility = false;
2368
- }
2369
- patch(oldVNode, rootVnode, isInitialLoad);
2370
- if (BUILD.slotRelocation) {
2371
- plt.$flags$ |= PLATFORM_FLAGS.isTmpDisconnected;
2372
- if (checkSlotRelocate) {
2373
- markSlotContentForRelocation(rootVnode.$elm$);
2374
- carryContentWithRelocatedSlotRefs();
2375
- for (const relocateData of relocateNodes) {
2376
- const nodeToRelocate = relocateData.$nodeToRelocate$;
2377
- if (!nodeToRelocate["s-ol"] && win.document) {
2378
- const orgLocationNode = BUILD.isDebug || BUILD.hydrateServerSide ? originalLocationDebugNode(nodeToRelocate) : win.document.createTextNode("");
2379
- orgLocationNode["s-nr"] = nodeToRelocate;
2380
- insertBefore(nodeToRelocate.parentNode, nodeToRelocate["s-ol"] = orgLocationNode, nodeToRelocate, isInitialLoad);
2381
- }
2382
- }
2383
- for (const relocateData of relocateNodes) {
2384
- const nodeToRelocate = relocateData.$nodeToRelocate$;
2385
- const slotRefNode = relocateData.$slotRefNode$;
2386
- if (nodeToRelocate.nodeType === NODE_TYPE.ElementNode && isInitialLoad) nodeToRelocate["s-ih"] = !!nodeToRelocate.hidden;
2387
- if (slotRefNode) {
2388
- const parentNodeRef = slotRefNode.parentNode;
2389
- let insertBeforeNode = slotRefNode.nextSibling;
2390
- if (!BUILD.hydrateServerSide && insertBeforeNode && insertBeforeNode.nodeType === NODE_TYPE.ElementNode) {
2391
- let orgLocationNode = nodeToRelocate["s-ol"]?.previousSibling;
2392
- while (orgLocationNode) {
2393
- let refNode = orgLocationNode["s-nr"] ?? null;
2394
- if (refNode && refNode["s-sn"] === nodeToRelocate["s-sn"] && parentNodeRef === (refNode.__parentNode || refNode.parentNode)) {
2395
- refNode = refNode.nextSibling;
2396
- while (refNode === nodeToRelocate || refNode?.["s-sr"]) refNode = refNode?.nextSibling;
2397
- if (!refNode || !refNode["s-nr"]) {
2398
- insertBeforeNode = refNode;
2399
- break;
2400
- }
2401
- }
2402
- orgLocationNode = orgLocationNode.previousSibling;
2403
- }
2404
- }
2405
- const parent = nodeToRelocate.__parentNode || nodeToRelocate.parentNode;
2406
- const nextSibling = nodeToRelocate.__nextSibling || nodeToRelocate.nextSibling;
2407
- if (!insertBeforeNode && parentNodeRef !== parent || nextSibling !== insertBeforeNode) {
2408
- if (nodeToRelocate !== insertBeforeNode) {
2409
- insertBefore(parentNodeRef, nodeToRelocate, insertBeforeNode, isInitialLoad);
2410
- if (nodeToRelocate.nodeType === NODE_TYPE.CommentNode && nodeToRelocate.nodeValue.startsWith("s-nt-")) {
2411
- const textNode = win.document.createTextNode(nodeToRelocate.nodeValue.replace(/^s-nt-/, ""));
2412
- textNode["s-hn"] = nodeToRelocate["s-hn"];
2413
- textNode["s-sn"] = nodeToRelocate["s-sn"];
2414
- textNode["s-sh"] = nodeToRelocate["s-sh"];
2415
- textNode["s-sr"] = nodeToRelocate["s-sr"];
2416
- textNode["s-ol"] = nodeToRelocate["s-ol"];
2417
- textNode["s-ol"]["s-nr"] = textNode;
2418
- insertBefore(nodeToRelocate.parentNode, textNode, nodeToRelocate, isInitialLoad);
2419
- nodeToRelocate.parentNode.removeChild(nodeToRelocate);
2420
- }
2421
- if (nodeToRelocate.nodeType === NODE_TYPE.ElementNode && nodeToRelocate.tagName !== "SLOT-FB") nodeToRelocate.hidden = nodeToRelocate["s-ih"] ?? false;
2422
- }
2423
- }
2424
- if (nodeToRelocate && typeof slotRefNode["s-rf"] === "function") slotRefNode["s-rf"](slotRefNode);
2425
- } else if (nodeToRelocate.nodeType === NODE_TYPE.ElementNode) nodeToRelocate.hidden = true;
2426
- }
2427
- }
2428
- if (checkSlotFallbackVisibility) updateFallbackSlotVisibility(rootVnode.$elm$);
2429
- plt.$flags$ &= ~PLATFORM_FLAGS.isTmpDisconnected;
2430
- relocateNodes.length = 0;
2431
- }
2432
- if (BUILD.slotRelocation && !useNativeShadowDom && !(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) && hostElm["s-cr"]) {
2433
- const children = rootVnode.$elm$.__childNodes || rootVnode.$elm$.childNodes;
2434
- for (const childNode of children) if (childNode["s-hn"] !== hostTagName && childNode["s-sh"] !== hostTagName) {
2435
- if (isInitialLoad && childNode["s-ih"] == null) childNode["s-ih"] = childNode.hidden ?? false;
2436
- if (childNode.nodeType === NODE_TYPE.ElementNode) childNode.hidden = true;
2437
- else if (childNode.nodeType === NODE_TYPE.TextNode && !!childNode.nodeValue.trim()) {
2438
- const textCommentNode = win.document.createComment("s-nt-" + childNode.nodeValue);
2439
- textCommentNode["s-sn"] = childNode["s-sn"];
2440
- insertBefore(childNode.parentNode, textCommentNode, childNode, isInitialLoad);
2441
- childNode.parentNode.removeChild(childNode);
2442
- }
2443
- }
2444
- }
2445
- contentRef = void 0;
2446
- flushQueuedRefCallbacks();
2447
- };
2448
- const slotReferenceDebugNode = (slotVNode) => win.document?.createComment(`<slot${slotVNode.$name$ ? " name=\"" + slotVNode.$name$ + "\"" : ""}> (host=${hostTagName.toLowerCase()})`);
2449
- const originalLocationDebugNode = (nodeToRelocate) => win.document?.createComment(`org-location for ` + (nodeToRelocate.localName ? `<${nodeToRelocate.localName}> (host=${nodeToRelocate["s-hn"]})` : `[${nodeToRelocate.textContent}]`));
2450
- //#endregion
2451
- //#region src/runtime/update-component.ts
2452
- /**
2453
- * Get a promise that resolves once `hostRef`'s real `connectedCallback` has fired for the first time.
2454
- *
2455
- * @param hostRef the component's host reference
2456
- * @returns a promise that resolves once the component's real `connectedCallback` has fired
2457
- */
2458
- const ensureFirstConnectPromise = (hostRef) => {
2459
- if (!hostRef.$onFirstConnectPromise$) hostRef.$onFirstConnectPromise$ = new Promise((r) => hostRef.$onFirstConnectResolve$ = r);
2460
- return hostRef.$onFirstConnectPromise$;
2461
- };
2462
- /**
2463
- * Resolve `hostRef`'s first-connect promise and flag it connected. Called once this
2464
- * component's real `connectedCallback` fires, plus from error/disconnect cleanup so a
2465
- * component that never connects can't hang an ancestor or descendant forever.
2466
- *
2467
- * @param hostRef the component's host reference
2468
- */
2469
- const markFirstConnected = (hostRef) => {
2470
- hostRef.$flags$ |= HOST_FLAGS.hasFiredConnected;
2471
- hostRef.$onFirstConnectResolve$?.();
2472
- hostRef.$onFirstConnectResolve$ = void 0;
2473
- };
2474
- /**
2475
- * Wait for `ancestorElm` to be defined and its real `connectedCallback` to have completed.
2476
- * Shared by the lazy ({@link initializeComponent}) and standalone (`bootstrap-standalone.ts`)
2477
- * `connectedCallback` paths so a component never connects before its nearest Stencil
2478
- * ancestor, regardless of load order. Both call sites already check `BUILD.asyncLoading` and
2479
- * that an ancestor exists before calling this. Lazy's proxy classes are always pre-defined,
2480
- * so the `whenDefined` wait is a no-op there - it only does real work for standalone's
2481
- * autoloader, where the ancestor tag may not be defined yet.
2482
- *
2483
- * @param ancestorElm the nearest Stencil ancestor element
2484
- */
2485
- const awaitAncestorConnected = async (ancestorElm) => {
2486
- let ancestorHostRef = getHostRef(ancestorElm);
2487
- if (!BUILD.lazyLoad && !ancestorHostRef) {
2488
- await getRegistry().whenDefined(ancestorElm.tagName.toLowerCase());
2489
- ancestorHostRef = getHostRef(ancestorElm);
2490
- }
2491
- if (ancestorHostRef && !(ancestorHostRef.$flags$ & HOST_FLAGS.hasFiredConnected)) await ensureFirstConnectPromise(ancestorHostRef);
2492
- };
2493
- const attachToAncestor = (hostRef, ancestorComponent) => {
2494
- if (BUILD.asyncLoading && ancestorComponent && !hostRef.$onRenderResolve$ && ancestorComponent["s-p"]) {
2495
- const index = ancestorComponent["s-p"].push(new Promise((r) => hostRef.$onRenderResolve$ = () => {
2496
- ancestorComponent["s-p"].splice(index - 1, 1);
2497
- r();
2498
- }));
2499
- if (ancestorComponent["s-pc"]) ancestorComponent["s-pc"].push(ensureFirstConnectPromise(hostRef));
2500
- }
2501
- };
2502
- const scheduleUpdate = (hostRef, isInitialLoad) => {
2503
- if (BUILD.updatable) hostRef.$flags$ |= HOST_FLAGS.isQueuedForUpdate;
2504
- if (BUILD.asyncLoading && hostRef.$flags$ & HOST_FLAGS.isWaitingForChildren) {
2505
- hostRef.$flags$ |= HOST_FLAGS.needsRerender;
2506
- return;
2507
- }
2508
- attachToAncestor(hostRef, hostRef.$ancestorComponent$);
2509
- const dispatch = () => dispatchHooks(hostRef, isInitialLoad);
2510
- if (isInitialLoad) {
2511
- const pendingConnects = BUILD.asyncLoading ? hostRef.$hostElement$["s-pc"] : void 0;
2512
- if (pendingConnects && pendingConnects.length > 0) return Promise.all(pendingConnects).then(dispatch).catch(dispatch);
2513
- queueMicrotask(() => {
2514
- dispatch();
2515
- });
2516
- return;
2517
- }
2518
- return BUILD.taskQueue ? writeTask(dispatch) : dispatch();
2519
- };
2520
- /**
2521
- * Dispatch initial-render and update lifecycle hooks, enqueuing calls to
2522
- * component lifecycle methods like `componentWillLoad` as well as
2523
- * {@link updateComponent}, which will kick off the virtual DOM re-render.
2524
- *
2525
- * @param hostRef a reference to a host DOM node
2526
- * @param isInitialLoad whether we're on the initial load or not
2527
- * @returns an empty Promise which is used to enqueue a series of operations for
2528
- * the component
2529
- */
2530
- const dispatchHooks = (hostRef, isInitialLoad) => {
2531
- const elm = hostRef.$hostElement$;
2532
- const endSchedule = createTime("scheduleUpdate", hostRef.$cmpMeta$.$tagName$);
2533
- const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
2534
- /**
2535
- * Given a user imports a component compiled with a `dist-custom-element`
2536
- * output target into a Stencil project compiled with a `dist` output target,
2537
- * then `instance` will be `undefined` as `hostRef` won't have a `lazyInstance`
2538
- * property. In this case, the component will fail to render in one of the
2539
- * subsequent functions.
2540
- *
2541
- * For this scenario to work the user needs to set the `externalRuntime` flag
2542
- * for the `dist-custom-element` component that is being imported into the `dist`
2543
- * Stencil project.
2544
- */
2545
- if (!instance) {
2546
- if (BUILD.isDev) throw new Error(`Can't render <${elm.tagName.toLowerCase()} /> - compiled without externalRuntime: true. See https://stenciljs.com/docs/custom-elements#externalruntime`);
2547
- return;
2548
- }
2549
- let maybePromise;
2550
- if (isInitialLoad) {
2551
- if (BUILD.lazyLoad) {
2552
- if (BUILD.hostListener) {
2553
- hostRef.$flags$ |= HOST_FLAGS.isListenReady;
2554
- if (hostRef.$queuedListeners$) {
2555
- hostRef.$queuedListeners$.map(([methodName, event]) => safeCall(instance, methodName, event, elm));
2556
- hostRef.$queuedListeners$ = void 0;
2557
- }
2558
- }
2559
- if (hostRef.$fetchedCbList$.length) hostRef.$fetchedCbList$.forEach((cb) => cb(elm));
2560
- }
2561
- if (BUILD.lifecycleDOMEvents) emitLifecycleEvent(elm, "componentWillLoad");
2562
- maybePromise = safeCall(instance, "componentWillLoad", void 0, elm);
2563
- } else {
2564
- if (BUILD.updatable && hostRef.$queuedPropChanges$) {
2565
- const changes = hostRef.$queuedPropChanges$;
2566
- hostRef.$queuedPropChanges$ = void 0;
2567
- if (safeCall(instance, "componentShouldUpdate", changes, elm) === false) {
2568
- hostRef.$flags$ &= ~HOST_FLAGS.isQueuedForUpdate;
2569
- return;
2570
- }
2571
- }
2572
- if (BUILD.lifecycleDOMEvents) emitLifecycleEvent(elm, "componentWillUpdate");
2573
- maybePromise = safeCall(instance, "componentWillUpdate", void 0, elm);
2574
- }
2575
- if (BUILD.lifecycleDOMEvents) emitLifecycleEvent(elm, "componentWillRender");
2576
- maybePromise = enqueue(maybePromise, () => safeCall(instance, "componentWillRender", void 0, elm));
2577
- endSchedule();
2578
- return enqueue(maybePromise, () => updateComponent(hostRef, instance, isInitialLoad));
2579
- };
2580
- /**
2581
- * This function uses a Promise to implement a simple first-in, first-out queue
2582
- * of functions to be called.
2583
- *
2584
- * The queue is ordered on the basis of the first argument. If it's
2585
- * `undefined`, then nothing is on the queue yet, so the provided function can
2586
- * be called synchronously (although note that this function may return a
2587
- * `Promise`). The idea is that then the return value of that enqueueing
2588
- * operation is kept around, so that if it was a `Promise` then subsequent
2589
- * functions can be enqueued by calling this function again with that `Promise`
2590
- * as the first argument.
2591
- *
2592
- * @param maybePromise either a `Promise` which should resolve before the next function is called or an 'empty' sentinel
2593
- * @param fn a function to enqueue
2594
- * @returns either a `Promise` or the return value of the provided function
2595
- */
2596
- const enqueue = (maybePromise, fn) => {
2597
- if (isPromisey(maybePromise)) return maybePromise.then(fn).catch((err) => {
2598
- console.error(err);
2599
- fn();
2600
- });
2601
- const result = fn();
2602
- return isPromisey(result) ? result : void 0;
2603
- };
2604
- /**
2605
- * Check that a value is a `Promise`. To check, we first see if the value is an
2606
- * instance of the `Promise` global. In a few circumstances, in particular if
2607
- * the global has been overwritten, this is could be misleading, so we also do
2608
- * a little 'duck typing' check to see if the `.then` property of the value is
2609
- * defined and a function.
2610
- *
2611
- * @param maybePromise it might be a promise!
2612
- * @returns whether it is or not
2613
- */
2614
- const isPromisey = (maybePromise) => maybePromise instanceof Promise || maybePromise && maybePromise.then && typeof maybePromise.then === "function";
2615
- /**
2616
- * Update a component given reference to its host elements and so on.
2617
- *
2618
- * @param hostRef an object containing references to the element's host node,
2619
- * VDom nodes, and other metadata
2620
- * @param instance a reference to the underlying host element where it will be
2621
- * rendered
2622
- * @param isInitialLoad whether or not this function is being called as part of
2623
- * the first render cycle
2624
- * @returns a `Promise` if the update is asynchronous, otherwise `void`
2625
- */
2626
- const updateComponent = (hostRef, instance, isInitialLoad) => {
2627
- const elm = hostRef.$hostElement$;
2628
- const endUpdate = createTime("update", hostRef.$cmpMeta$.$tagName$);
2629
- const rc = elm["s-rc"];
2630
- if (BUILD.style && isInitialLoad) attachStyles(hostRef);
2631
- const endRender = createTime("render", hostRef.$cmpMeta$.$tagName$);
2632
- if (BUILD.isDev) hostRef.$flags$ |= HOST_FLAGS.devOnRender;
2633
- if (BUILD.hydrateServerSide) return callRender(hostRef, instance, elm, isInitialLoad).then(() => {
2634
- afterRender(hostRef, elm, rc, isInitialLoad, endRender, endUpdate);
2635
- });
2636
- callRender(hostRef, instance, elm, isInitialLoad);
2637
- afterRender(hostRef, elm, rc, isInitialLoad, endRender, endUpdate);
2638
- };
2639
- const afterRender = (hostRef, elm, rc, isInitialLoad, endRender, endUpdate) => {
2640
- if (BUILD.isDev) {
2641
- hostRef.$renderCount$ = hostRef.$renderCount$ === void 0 ? 1 : hostRef.$renderCount$ + 1;
2642
- hostRef.$flags$ &= ~HOST_FLAGS.devOnRender;
2643
- }
2644
- if (BUILD.hydrateServerSide) try {
2645
- serverSideConnected(elm);
2646
- if (isInitialLoad) {
2647
- if (hostRef.$cmpMeta$.$flags$ & CMP_FLAGS.shadowDomEncapsulation) elm["s-en"] = "";
2648
- else if (hostRef.$cmpMeta$.$flags$ & CMP_FLAGS.scopedCssEncapsulation) elm["s-en"] = "c";
2649
- }
2650
- } catch (e) {
2651
- consoleError(e, elm);
2652
- }
2653
- if (BUILD.asyncLoading && rc) {
2654
- rc.map((cb) => cb());
2655
- elm["s-rc"] = void 0;
2656
- }
2657
- endRender();
2658
- endUpdate();
2659
- if (BUILD.asyncLoading) {
2660
- const childrenPromises = elm["s-p"] ?? [];
2661
- const postUpdate = () => postUpdateComponent(hostRef);
2662
- if (childrenPromises.length === 0) postUpdate();
2663
- else {
2664
- Promise.all(childrenPromises).then(postUpdate).catch(postUpdate);
2665
- hostRef.$flags$ |= HOST_FLAGS.isWaitingForChildren;
2666
- childrenPromises.length = 0;
2667
- }
2668
- } else postUpdateComponent(hostRef);
2669
- };
2670
- let renderingRef = null;
2671
- /**
2672
- * Handle making the call to the VDom renderer with the proper context given
2673
- * various build variables
2674
- *
2675
- * @param hostRef an object containing references to the element's host node,
2676
- * VDom nodes, and other metadata
2677
- * @param instance a reference to the underlying host element where it will be
2678
- * rendered
2679
- * @param elm the Host element for the component
2680
- * @param isInitialLoad whether or not this function is being called as part of
2681
- * @returns an empty promise
2682
- */
2683
- const callRender = (hostRef, instance, elm, isInitialLoad) => {
2684
- const allRenderFn = !!BUILD.allRenderFn;
2685
- const lazyLoad = !!BUILD.lazyLoad;
2686
- const updatable = !!BUILD.updatable;
2687
- try {
2688
- renderingRef = instance;
2689
- /**
2690
- * minification optimization: `allRenderFn` is `true` if all components have a `render`
2691
- * method, so we can call the method immediately. If not, check before calling it.
2692
- */
2693
- instance = allRenderFn ? instance.render() : instance.render && instance.render();
2694
- if (updatable) hostRef.$flags$ &= ~HOST_FLAGS.isQueuedForUpdate;
2695
- if (updatable || lazyLoad) hostRef.$flags$ |= HOST_FLAGS.hasRendered;
2696
- if (BUILD.hasRenderFn || BUILD.reflect) {
2697
- if (BUILD.vdomRender || BUILD.reflect) {
2698
- if (BUILD.hydrateServerSide) return Promise.resolve(instance).then((value) => renderVdom(hostRef, value, isInitialLoad));
2699
- else renderVdom(hostRef, instance, isInitialLoad);
2700
- } else {
2701
- const shadowRoot = elm.shadowRoot;
2702
- if (hostRef.$cmpMeta$.$flags$ & CMP_FLAGS.shadowDomEncapsulation) shadowRoot.textContent = instance;
2703
- else elm.textContent = instance;
2704
- }
2705
- }
2706
- } catch (e) {
2707
- consoleError(e, hostRef.$hostElement$);
2708
- }
2709
- renderingRef = null;
2710
- return null;
2711
- };
2712
- const getRenderingRef = () => renderingRef;
2713
- const postUpdateComponent = (hostRef) => {
2714
- const tagName = hostRef.$cmpMeta$.$tagName$;
2715
- const elm = hostRef.$hostElement$;
2716
- const endPostUpdate = createTime("postUpdate", tagName);
2717
- const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
2718
- const ancestorComponent = hostRef.$ancestorComponent$;
2719
- if (BUILD.isDev) hostRef.$flags$ |= HOST_FLAGS.devOnRender;
2720
- safeCall(instance, "componentDidRender", void 0, elm);
2721
- if (BUILD.isDev) hostRef.$flags$ &= ~HOST_FLAGS.devOnRender;
2722
- if (BUILD.lifecycleDOMEvents) emitLifecycleEvent(elm, "componentDidRender");
2723
- if (!(hostRef.$flags$ & HOST_FLAGS.hasLoadedComponent)) {
2724
- hostRef.$flags$ |= HOST_FLAGS.hasLoadedComponent;
2725
- if (BUILD.asyncLoading && BUILD.cssAnnotations) addHydratedFlag(elm);
2726
- if (BUILD.isDev) hostRef.$flags$ |= HOST_FLAGS.devOnDidLoad;
2727
- safeCall(instance, "componentDidLoad", void 0, elm);
2728
- if (BUILD.isDev) hostRef.$flags$ &= ~HOST_FLAGS.devOnDidLoad;
2729
- if (BUILD.lifecycleDOMEvents) emitLifecycleEvent(elm, "componentDidLoad");
2730
- if (BUILD.propChangeCallback) hostRef.$flags$ |= HOST_FLAGS.isWatchReady;
2731
- endPostUpdate();
2732
- if (BUILD.asyncLoading) {
2733
- hostRef.$onReadyResolve$(elm);
2734
- if (!ancestorComponent) appDidLoad(tagName);
2735
- }
2736
- } else {
2737
- if (BUILD.isDev) hostRef.$flags$ |= HOST_FLAGS.devOnRender;
2738
- safeCall(instance, "componentDidUpdate", void 0, elm);
2739
- if (BUILD.isDev) hostRef.$flags$ &= ~HOST_FLAGS.devOnRender;
2740
- if (BUILD.lifecycleDOMEvents) emitLifecycleEvent(elm, "componentDidUpdate");
2741
- endPostUpdate();
2742
- }
2743
- if (BUILD.method && BUILD.lazyLoad) hostRef.$onInstanceResolve$(elm);
2744
- if (BUILD.asyncLoading) {
2745
- if (hostRef.$onRenderResolve$) {
2746
- hostRef.$onRenderResolve$();
2747
- hostRef.$onRenderResolve$ = void 0;
2748
- }
2749
- if (hostRef.$flags$ & HOST_FLAGS.needsRerender) nextTick(() => scheduleUpdate(hostRef, false));
2750
- hostRef.$flags$ &= ~(HOST_FLAGS.isWaitingForChildren | HOST_FLAGS.needsRerender);
2751
- }
2752
- };
2753
- const forceUpdate = (ref) => {
2754
- if (BUILD.updatable && (Build.isBrowser || Build.isTesting)) {
2755
- const hostRef = getHostRef(ref);
2756
- const isConnected = hostRef?.$hostElement$?.isConnected;
2757
- if (isConnected && (hostRef.$flags$ & (HOST_FLAGS.hasRendered | HOST_FLAGS.isQueuedForUpdate)) === HOST_FLAGS.hasRendered) scheduleUpdate(hostRef, false);
2758
- return isConnected;
2759
- }
2760
- return false;
2761
- };
2762
- const appDidLoad = (who) => {
2763
- if (BUILD.asyncQueue) plt.$flags$ |= PLATFORM_FLAGS.appLoaded;
2764
- nextTick(() => emitEvent(win, "appload", { detail: { namespace: "app" } }));
2765
- if (BUILD.hydrateClientSide) {
2766
- if (plt.$orgLocNodes$?.size) plt.$orgLocNodes$.clear();
2767
- }
2768
- if (BUILD.profile && performance.measure) performance.measure(`[Stencil] app initial load (by ${who})`, "st:app:start");
2769
- };
2770
- /**
2771
- * Allows to safely call a method, e.g. `componentDidLoad`, on an instance,
2772
- * e.g. custom element node. If a build figures out that e.g. no component
2773
- * has a `componentDidLoad` method, the instance method gets removed from the
2774
- * output bundle and this function returns `undefined`.
2775
- * @param instance any object that may or may not contain methods
2776
- * @param method method name
2777
- * @param arg single arbitrary argument
2778
- * @param elm the element which made the call
2779
- * @returns result of method call if it exists, otherwise `undefined`
2780
- */
2781
- const safeCall = (instance, method, arg, elm) => {
2782
- if (instance && instance[method]) try {
2783
- return instance[method](arg);
2784
- } catch (e) {
2785
- consoleError(e, elm);
2786
- }
2787
- };
2788
- /**
2789
- * For debugging purposes as `BUILD.lifecycleDOMEvents` is `false` by default and will
2790
- * get removed by the compiler. Used for timing events to see how long they take.
2791
- * @param elm the target of the Event
2792
- * @param lifecycleName name of the event
2793
- */
2794
- const emitLifecycleEvent = (elm, lifecycleName) => {
2795
- if (BUILD.lifecycleDOMEvents) emitEvent(elm, "stencil_" + lifecycleName, {
2796
- bubbles: true,
2797
- composed: true,
2798
- detail: { namespace: "app" }
2799
- });
2800
- };
2801
- /**
2802
- * Set the hydrated flag on a DOM element
2803
- *
2804
- * @param elm a reference to a DOM element
2805
- * @returns undefined
2806
- */
2807
- const addHydratedFlag = (elm) => BUILD.hydratedClass ? elm.classList.add(BUILD.hydratedSelectorName ?? "hydrated") : BUILD.hydratedAttribute ? elm.setAttribute(BUILD.hydratedSelectorName ?? "hydrated", "") : void 0;
2808
- const serverSideConnected = (elm) => {
2809
- const children = elm.children;
2810
- if (children != null) for (let i = 0, ii = children.length; i < ii; i++) {
2811
- const childElm = children[i];
2812
- if (typeof childElm.connectedCallback === "function") childElm.connectedCallback();
2813
- serverSideConnected(childElm);
2814
- }
2815
- };
2816
- //#endregion
2817
- //#region src/runtime/signals.ts
2818
- const STENCIL_SIGNALS_SYMBOL = Symbol.for("stencil.signals");
2819
- /**
2820
- * Duck-type check for Signal objects. Cross-bundle-safe (no instanceof).
2821
- * @param v value to test
2822
- * @returns whether `v` implements the SignalLike interface
2823
- */
2824
- const isSignalLike = (v) => v !== null && typeof v === "object" && typeof v.peek === "function" && typeof v.subscribe === "function";
2825
- /**
2826
- * Create Signal.State instances for every @Prop/@State member, copy initial
2827
- * values from $instanceValues$, and wire up:
2828
- * - a per-prop scheduling effect → calls scheduleUpdate when value changes
2829
- * - per-prop watcher effects → call @Watch callbacks with old/new value
2830
- *
2831
- * All dispose functions are collected into hostRef.$signalCleanup$() for
2832
- * teardown on disconnect.
2833
- * @param elm the host element
2834
- * @param hostRef the component's host reference
2835
- * @param cmpMeta the component's runtime metadata
2836
- */
2837
- const initializeSignals = (elm, hostRef, cmpMeta) => {
2838
- if (hostRef.$signalValues$) return;
2839
- hostRef.$signalValues$ = /* @__PURE__ */ new Map();
2840
- const disposers = [];
2841
- const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
2842
- for (const [memberName, [memberFlags]] of Object.entries(cmpMeta.$members$ ?? {})) {
2843
- if (!(memberFlags & MEMBER_FLAGS.PropLike)) continue;
2844
- const initialVal = hostRef.$instanceValues$.get(memberName);
2845
- const sig = signal(initialVal);
2846
- hostRef.$signalValues$.set(memberName, sig);
2847
- let prevScheduleVal = sig.peek();
2848
- disposers.push(effect(() => {
2849
- const newVal = sig.value;
2850
- if (hostRef.$flags$ & HOST_FLAGS.hasRendered) {
2851
- if (instance?.componentShouldUpdate) {
2852
- const changes = hostRef.$queuedPropChanges$ ||= {};
2853
- changes[memberName] = {
2854
- newVal,
2855
- oldVal: changes[memberName]?.oldVal ?? prevScheduleVal
2856
- };
2857
- }
2858
- if (!(hostRef.$flags$ & HOST_FLAGS.isQueuedForUpdate)) scheduleUpdate(hostRef, false);
2859
- }
2860
- prevScheduleVal = newVal;
2861
- }));
2862
- if (BUILD.propChangeCallback && cmpMeta.$watchers$?.[memberName]) {
2863
- const watchMethods = cmpMeta.$watchers$[memberName];
2864
- let prevWatchVal = sig.peek();
2865
- disposers.push(effect(() => {
2866
- const newVal = sig.value;
2867
- const flags = hostRef.$flags$;
2868
- watchMethods.forEach((watcher) => {
2869
- try {
2870
- const [[watchMethodName, watcherFlags]] = Object.entries(watcher);
2871
- if (flags & HOST_FLAGS.isWatchReady || watcherFlags & WATCH_FLAGS.Immediate) {
2872
- const inst = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
2873
- if (inst) inst[watchMethodName](newVal, prevWatchVal, memberName);
2874
- }
2875
- } catch (e) {
2876
- consoleError(e, elm);
2877
- }
2878
- });
2879
- prevWatchVal = newVal;
2880
- }));
2881
- }
2882
- }
2883
- const effectMethods = instance?.["__stencilEffects"] ?? [];
2884
- for (const methodName of effectMethods) disposers.push(effect(() => {
2885
- try {
2886
- instance[methodName]();
2887
- } catch (e) {
2888
- consoleError(e, elm);
2889
- }
2890
- }));
2891
- const publicSignals = new Map([...hostRef.$signalValues$].filter(([k]) => (cmpMeta.$members$?.[k]?.[0] ?? 0) & MEMBER_FLAGS.Prop));
2892
- elm[STENCIL_SIGNALS_SYMBOL] = publicSignals;
2893
- hostRef.$signalCleanup$ = () => {
2894
- disposers.forEach((d) => d());
2895
- elm[STENCIL_SIGNALS_SYMBOL] = void 0;
2896
- };
2897
- };
2898
- /**
2899
- * Sets up `@Effect()` method subscriptions without full signal-backing.
2900
- * Called when `vdomSignals` is active but `signalBacking` is not - allows
2901
- * reactive effects that track external signals with no @Prop/@State overhead.
2902
- * @param elm the host element
2903
- * @param hostRef the component's host reference
2904
- */
2905
- const initializeEffects = (elm, hostRef) => {
2906
- const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
2907
- const effectMethods = instance?.["__stencilEffects"] ?? [];
2908
- if (!effectMethods.length) return;
2909
- const disposers = [];
2910
- for (const methodName of effectMethods) disposers.push(effect(() => {
2911
- try {
2912
- instance[methodName]();
2913
- } catch (e) {
2914
- consoleError(e, elm);
2915
- }
2916
- }));
2917
- hostRef.$signalCleanup$ = () => disposers.forEach((d) => d());
2918
- };
2919
- //#endregion
2920
- //#region src/runtime/vdom/h.ts
2921
- /**
2922
- * Production h() function based on Preact by
2923
- * Jason Miller (@developit)
2924
- * Licensed under the MIT License
2925
- * https://github.com/developit/preact/blob/master/LICENSE
2926
- *
2927
- * Modified for Stencil's compiler and vdom
2928
- */
2929
- const h = (nodeName, vnodeData, ...children) => {
2930
- if (typeof nodeName === "string") nodeName = transformTag(nodeName);
2931
- let child = null;
2932
- let key = null;
2933
- let slotName = null;
2934
- let simple = false;
2935
- let lastSimple = false;
2936
- const vNodeChildren = [];
2937
- const walk = (c) => {
2938
- for (let i = 0; i < c.length; i++) {
2939
- child = c[i];
2940
- if (Array.isArray(child)) walk(child);
2941
- else if (child != null && typeof child !== "boolean") {
2942
- if (BUILD.vdomSignals && isSignalLike(child)) {
2943
- const sigVNode = newVNode(null, String(child.peek()));
2944
- sigVNode.$signal$ = child;
2945
- vNodeChildren.push(sigVNode);
2946
- lastSimple = false;
2947
- } else {
2948
- if (simple = typeof nodeName !== "function" && !isComplexType(child)) child = String(child);
2949
- else if (typeof nodeName !== "function" && child.$flags$ === void 0) {
2950
- if (BUILD.isDev) consoleDevError(`vNode passed as children has unexpected type.
2951
- Make sure it's using the correct h() function.
2952
- Empty objects can also be the cause, look for JSX comments that became objects.`);
2953
- else consoleError("Invalid vNode child");
2954
- continue;
2955
- }
2956
- if (simple && lastSimple) vNodeChildren[vNodeChildren.length - 1].$text$ += child;
2957
- else vNodeChildren.push(simple ? newVNode(null, child) : child);
2958
- lastSimple = simple;
2959
- }
2960
- }
2961
- }
2962
- };
2963
- walk(children);
2964
- if (vnodeData) {
2965
- if (BUILD.isDev && nodeName === "input") validateInputProperties(vnodeData);
2966
- if (BUILD.vdomKey && vnodeData.key) key = vnodeData.key;
2967
- if (BUILD.slotRelocation && vnodeData.name) slotName = vnodeData.name;
2968
- if (BUILD.vdomClass) {
2969
- const classData = vnodeData.class;
2970
- if (classData && !(BUILD.vdomSignals && isSignalLike(classData))) vnodeData.class = typeof classData !== "object" ? classData : Object.keys(classData).filter((k) => classData[k]).join(" ");
2971
- }
2972
- }
2973
- if (BUILD.isDev && vNodeChildren.some(isHost)) consoleDevError(`The <Host> must be the single root component. Make sure:
2974
- - You are NOT using hostData() and <Host> in the same component.
2975
- - <Host> is used once, and it's the single root component of the render() function.`);
2976
- if (BUILD.vdomFunctional && typeof nodeName === "function") return nodeName(vnodeData === null ? {} : vnodeData, vNodeChildren, vdomFnUtils);
2977
- const vnode = newVNode(nodeName, null);
2978
- vnode.$attrs$ = vnodeData;
2979
- if (vNodeChildren.length > 0) vnode.$children$ = vNodeChildren;
2980
- if (BUILD.vdomKey) vnode.$key$ = key;
2981
- if (BUILD.slotRelocation) vnode.$name$ = slotName;
2982
- return vnode;
2983
- };
2984
- /**
2985
- * A utility function for creating a virtual DOM node from a tag and some
2986
- * possible text content.
2987
- *
2988
- * @param tag the tag for this element
2989
- * @param text possible text content for the node
2990
- * @returns a newly-minted virtual DOM node
2991
- */
2992
- const newVNode = (tag, text) => {
2993
- const vnode = {
2994
- $flags$: 0,
2995
- $tag$: tag,
2996
- $text$: text ?? null,
2997
- $elm$: null,
2998
- $children$: null
2999
- };
3000
- if (BUILD.vdomAttribute) vnode.$attrs$ = null;
3001
- if (BUILD.vdomKey) vnode.$key$ = null;
3002
- if (BUILD.slotRelocation) vnode.$name$ = null;
3003
- return vnode;
3004
- };
3005
- const Host = {};
3006
- /**
3007
- * Check whether a given node is a Host node or not
3008
- *
3009
- * @param node the virtual DOM node to check
3010
- * @returns whether it's a Host node or not
3011
- */
3012
- const isHost = (node) => node && node.$tag$ === Host;
3013
- /**
3014
- * Implementation of {@link d.FunctionalUtilities} for Stencil's VDom.
3015
- *
3016
- * Note that these functions convert from {@link d.VNode} to
3017
- * {@link d.ChildNode} to give functional component developers a friendly
3018
- * interface.
3019
- */
3020
- const vdomFnUtils = {
3021
- forEach: (children, cb) => children.map(convertToPublic).forEach(cb),
3022
- map: (children, cb) => children.map(convertToPublic).map(cb).map(convertToPrivate)
3023
- };
3024
- /**
3025
- * Convert a {@link d.VNode} to a {@link d.ChildNode} in order to present a
3026
- * friendlier public interface (hence, 'convertToPublic').
3027
- *
3028
- * @param node the virtual DOM node to convert
3029
- * @returns a converted child node
3030
- */
3031
- const convertToPublic = (node) => ({
3032
- vattrs: node.$attrs$,
3033
- vchildren: node.$children$,
3034
- vkey: node.$key$,
3035
- vname: node.$name$,
3036
- vtag: node.$tag$,
3037
- vtext: node.$text$
3038
- });
3039
- /**
3040
- * Convert a {@link d.ChildNode} back to an equivalent {@link d.VNode} in
3041
- * order to use the resulting object in the virtual DOM. The initial object was
3042
- * likely created as part of presenting a public API, so converting it back
3043
- * involved making it 'private' again (hence, `convertToPrivate`).
3044
- *
3045
- * @param node the child node to convert
3046
- * @returns a converted virtual DOM node
3047
- */
3048
- const convertToPrivate = (node) => {
3049
- if (typeof node.vtag === "function") {
3050
- const vnodeData = { ...node.vattrs };
3051
- if (node.vkey) vnodeData.key = node.vkey;
3052
- if (node.vname) vnodeData.name = node.vname;
3053
- return h(node.vtag, vnodeData, ...node.vchildren || []);
3054
- }
3055
- const vnode = newVNode(node.vtag, node.vtext);
3056
- vnode.$attrs$ = node.vattrs;
3057
- vnode.$children$ = node.vchildren;
3058
- vnode.$key$ = node.vkey;
3059
- vnode.$name$ = node.vname;
3060
- return vnode;
3061
- };
3062
- /**
3063
- * Validates the ordering of attributes on an input element
3064
- *
3065
- * @param inputElm the element to validate
3066
- */
3067
- const validateInputProperties = (inputElm) => {
3068
- const props = Object.keys(inputElm);
3069
- const value = props.indexOf("value");
3070
- if (value === -1) return;
3071
- const typeIndex = props.indexOf("type");
3072
- const minIndex = props.indexOf("min");
3073
- const maxIndex = props.indexOf("max");
3074
- const stepIndex = props.indexOf("step");
3075
- if (value < typeIndex || value < minIndex || value < maxIndex || value < stepIndex) consoleDevWarn(`The "value" prop of <input> should be set after "min", "max", "type" and "step"`);
3076
- };
3077
- //#endregion
3078
- //#region src/runtime/client-hydrate.ts
3079
- /**
3080
- * Takes an SSR rendered document, as annotated by 'vdom-annotations.ts' and:
3081
- *
3082
- * 1) Recreate an accurate VDOM which is fed to 'vdom-render.ts'. A failure to do so can cause hydration errors; extra renders, duplicated nodes
3083
- * 2) Add shadowDOM trees to their respective #document-fragment
3084
- * 3) Move forwarded, slotted nodes out of shadowDOMs
3085
- * 4) Add meta nodes to non-shadow DOMs and their 'slotted' nodes
3086
- *
3087
- * @param hostElm The element to hydrate.
3088
- * @param tagName The element's tag name.
3089
- * @param hostId The host ID assigned to the element by the server. e.g. `s-id="1"`
3090
- * @param hostRef The host reference for the element.
3091
- */
3092
- const initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {
3093
- const endHydrate = createTime("hydrateClient", tagName);
3094
- const shadowRoot = getShadowRoot(hostElm);
3095
- const childRenderNodes = [];
3096
- const slotNodes = [];
3097
- const slottedNodes = [];
3098
- const shadowRootNodes = BUILD.shadowDom && shadowRoot ? [] : null;
3099
- const vnode = newVNode(tagName, null);
3100
- vnode.$elm$ = hostElm;
3101
- let scopeId;
3102
- if (BUILD.scoped) {
3103
- const cmpMeta = hostRef.$cmpMeta$;
3104
- if (cmpMeta && cmpMeta.$flags$ & CMP_FLAGS.needsScopedEncapsulation && hostElm["s-sc"]) {
3105
- scopeId = hostElm["s-sc"];
3106
- hostElm.classList.add(scopeId + "-h");
3107
- } else if (hostElm["s-sc"]) delete hostElm["s-sc"];
3108
- }
3109
- if (win.document && (!plt.$orgLocNodes$ || !plt.$orgLocNodes$.size)) initializeDocumentHydrate(win.document.body, plt.$orgLocNodes$ = /* @__PURE__ */ new Map());
3110
- hostElm[HYDRATE_ID] = hostId;
3111
- hostElm.removeAttribute(HYDRATE_ID);
3112
- hostRef.$vnode$ = clientHydrate(vnode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, hostElm, hostId, slottedNodes);
3113
- let crIndex = 0;
3114
- const crLength = childRenderNodes.length;
3115
- let childRenderNode;
3116
- for (; crIndex < crLength; crIndex++) {
3117
- childRenderNode = childRenderNodes[crIndex];
3118
- const orgLocationId = childRenderNode.$hostId$ + "." + childRenderNode.$nodeId$;
3119
- const orgLocationNode = plt.$orgLocNodes$.get(orgLocationId);
3120
- const node = childRenderNode.$elm$;
3121
- if (!shadowRoot) {
3122
- node["s-hn"] = transformTag(tagName).toUpperCase();
3123
- if (childRenderNode.$tag$ === "slot") node["s-cr"] = hostElm["s-cr"];
3124
- } else if (childRenderNode.$tag$?.toString().includes("-") && childRenderNode.$tag$ !== "slot-fb" && !childRenderNode.$elm$.shadowRoot) {
3125
- const cmpMeta = getHostRef(childRenderNode.$elm$);
3126
- if (cmpMeta) {
3127
- const childScopeId = getScopeId(cmpMeta.$cmpMeta$, BUILD.mode ? childRenderNode.$elm$.getAttribute("s-mode") : void 0);
3128
- const styleSheet = win.document.querySelector(`style[sty-id="${childScopeId}"]`);
3129
- if (styleSheet) shadowRootNodes.unshift(styleSheet.cloneNode(true));
3130
- }
3131
- }
3132
- if (childRenderNode.$tag$ === "slot") {
3133
- childRenderNode.$name$ = childRenderNode.$elm$["s-sn"] || childRenderNode.$elm$["name"] || null;
3134
- if (childRenderNode.$children$) {
3135
- childRenderNode.$flags$ |= VNODE_FLAGS.isSlotFallback;
3136
- if (!childRenderNode.$elm$.childNodes.length) childRenderNode.$children$.forEach((c) => {
3137
- childRenderNode.$elm$.appendChild(c.$elm$);
3138
- });
3139
- } else childRenderNode.$flags$ |= VNODE_FLAGS.isSlotReference;
3140
- }
3141
- if (orgLocationNode && orgLocationNode.isConnected) {
3142
- const orgParentNode = orgLocationNode.parentNode;
3143
- if (orgLocationNode.parentElement.shadowRoot && orgLocationNode["s-en"] === "") orgParentNode.insertBefore(node, orgLocationNode.nextSibling);
3144
- orgParentNode.removeChild(orgLocationNode);
3145
- if (!shadowRoot) node["s-oo"] = parseInt(childRenderNode.$nodeId$);
3146
- }
3147
- if (orgLocationNode && !orgLocationNode["s-id"]) plt.$orgLocNodes$.delete(orgLocationId);
3148
- }
3149
- const hosts = [];
3150
- const snLen = slottedNodes.length;
3151
- let snIndex = 0;
3152
- let slotGroup;
3153
- let snGroupIdx;
3154
- let snGroupLen;
3155
- let slottedItem;
3156
- let currentPos = 0;
3157
- for (; snIndex < snLen; snIndex++) {
3158
- slotGroup = slottedNodes[snIndex];
3159
- if (!slotGroup || !slotGroup.length) continue;
3160
- snGroupLen = slotGroup.length;
3161
- snGroupIdx = 0;
3162
- for (; snGroupIdx < snGroupLen; snGroupIdx++) {
3163
- slottedItem = slotGroup[snGroupIdx];
3164
- const hid = slottedItem.hostId;
3165
- if (!hosts[hid]) hosts[hid] = plt.$orgLocNodes$.get(slottedItem.hostId);
3166
- if (!hosts[hid]) continue;
3167
- const hostEle = hosts[hid];
3168
- const siNode = slottedItem.node;
3169
- const siSlot = slottedItem.slot;
3170
- if (hostEle.shadowRoot && siNode.parentElement !== hostEle) hostEle.insertBefore(siNode, slotGroup[snGroupIdx - 1]?.node?.nextSibling);
3171
- if (!hostEle.shadowRoot || !shadowRoot) {
3172
- if (!siSlot["s-cr"]) {
3173
- siSlot["s-cr"] = hostEle["s-cr"];
3174
- if (!siSlot["s-cr"] && hostEle.shadowRoot) siSlot["s-cr"] = hostEle;
3175
- else siSlot["s-cr"] = (hostEle.__childNodes || hostEle.childNodes)[0];
3176
- }
3177
- addSlotRelocateNode(siNode, siSlot, false, siNode["s-oo"] || currentPos);
3178
- if (siNode.parentElement?.shadowRoot && siNode["getAttribute"] && siNode.getAttribute("slot")) siNode.removeAttribute("slot");
3179
- if (BUILD.lightDomPatches || BUILD.slotChildNodes || BUILD.patchAll && hostRef.$cmpMeta$.$flags$ & CMP_FLAGS.patchAll) patchSlottedNode(siNode);
3180
- }
3181
- currentPos = (siNode["s-oo"] || currentPos) + 1;
3182
- }
3183
- }
3184
- if (BUILD.scoped && scopeId && slotNodes.length) slotNodes.forEach((slot) => {
3185
- slot.$elm$.parentElement.classList.add(scopeId + "-s");
3186
- });
3187
- if (BUILD.shadowDom && shadowRoot && !shadowRoot.childNodes.length) {
3188
- let rnIdex = 0;
3189
- const rnLen = shadowRootNodes.length;
3190
- if (rnLen) {
3191
- for (; rnIdex < rnLen; rnIdex++) {
3192
- const node = shadowRootNodes[rnIdex];
3193
- /**
3194
- * in apps with a lot of components the `shadowRootNodes` array can be modified while iterating over it
3195
- * so we need to check if the node is still in the array before appending it to avoid any errors like:
3196
- *
3197
- * TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
3198
- */
3199
- if (node) shadowRoot.appendChild(node);
3200
- }
3201
- Array.from(hostElm.childNodes).forEach((node) => {
3202
- if (typeof node["s-en"] !== "string" && typeof node["s-sn"] !== "string") {
3203
- if (node.nodeType === NODE_TYPE.ElementNode && node.slot && node.hidden) node.removeAttribute("hidden");
3204
- else if (node.nodeType === NODE_TYPE.CommentNode && !node.nodeValue) node.parentNode.removeChild(node);
3205
- }
3206
- });
3207
- }
3208
- }
3209
- hostRef.$hostElement$ = hostElm;
3210
- endHydrate();
3211
- };
3212
- /**
3213
- * Recursively constructs the virtual node tree for a host element and its children.
3214
- * The tree is constructed by parsing the annotations set on the nodes by the server (`vdom-annotations.ts`).
3215
- *
3216
- * In addition to constructing the VNode tree, we also track information about the node's descendants:
3217
- * - which are slots
3218
- * - which should exist in the shadow root
3219
- * - which are nodes that should be rendered as children of the parent node
3220
- *
3221
- * @param parentVNode The vNode representing the parent node.
3222
- * @param childRenderNodes An array of all child nodes in the parent's node tree.
3223
- * @param slotNodes An array of all slot nodes in the parent's node tree.
3224
- * @param shadowRootNodes An array of nodes that should be rendered in the shadowDOM of the parent.
3225
- * @param hostElm The parent element.
3226
- * @param node The node to construct the vNode tree for.
3227
- * @param hostId The host ID assigned to the element by the server.
3228
- * @param slottedNodes - nodes that have been slotted
3229
- * @returns - the constructed VNode
3230
- */
3231
- const clientHydrate = (parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node, hostId, slottedNodes = []) => {
3232
- let childNodeType;
3233
- let childIdSplt;
3234
- let childVNode;
3235
- let i;
3236
- const scopeId = hostElm["s-sc"];
3237
- if (node.nodeType === NODE_TYPE.ElementNode) {
3238
- childNodeType = node.getAttribute(HYDRATE_CHILD_ID);
3239
- if (childNodeType) {
3240
- childIdSplt = childNodeType.split(".");
3241
- if (childIdSplt[0] === hostId || childIdSplt[0] === "0") {
3242
- childVNode = createSimpleVNode({
3243
- $hostId$: childIdSplt[0],
3244
- $nodeId$: childIdSplt[1],
3245
- $depth$: childIdSplt[2],
3246
- $index$: childIdSplt[3],
3247
- $tag$: node.tagName.toLowerCase(),
3248
- $elm$: node,
3249
- $attrs$: { class: node.className || "" }
3250
- });
3251
- childRenderNodes.push(childVNode);
3252
- node.removeAttribute(HYDRATE_CHILD_ID);
3253
- if (!parentVNode.$children$) parentVNode.$children$ = [];
3254
- if (BUILD.scoped && scopeId && childIdSplt[0] === hostId) {
3255
- node["s-si"] = scopeId;
3256
- childVNode.$attrs$.class += " " + scopeId;
3257
- }
3258
- const slotName = childVNode.$elm$.getAttribute("s-sn");
3259
- if (typeof slotName === "string") {
3260
- if (childVNode.$tag$ === "slot-fb") {
3261
- addSlot(slotName, childIdSplt[2], childVNode, node, parentVNode, childRenderNodes, slotNodes, shadowRootNodes, slottedNodes);
3262
- if (BUILD.scoped && scopeId) node.classList.add(scopeId);
3263
- }
3264
- childVNode.$elm$["s-sn"] = slotName;
3265
- childVNode.$elm$.removeAttribute("s-sn");
3266
- }
3267
- if (childVNode.$index$ !== void 0) parentVNode.$children$[childVNode.$index$] = childVNode;
3268
- parentVNode = childVNode;
3269
- if (shadowRootNodes && childVNode.$depth$ === "0") shadowRootNodes[childVNode.$index$] = childVNode.$elm$;
3270
- }
3271
- }
3272
- if (node.shadowRoot) for (i = node.shadowRoot.childNodes.length - 1; i >= 0; i--) clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.shadowRoot.childNodes[i], hostId, slottedNodes);
3273
- const nonShadowNodes = node.__childNodes || node.childNodes;
3274
- for (i = nonShadowNodes.length - 1; i >= 0; i--) clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, nonShadowNodes[i], hostId, slottedNodes);
3275
- } else if (node.nodeType === NODE_TYPE.CommentNode) {
3276
- childIdSplt = node.nodeValue.split(".");
3277
- if (childIdSplt[1] === hostId || childIdSplt[1] === "0") {
3278
- childNodeType = childIdSplt[0];
3279
- childVNode = createSimpleVNode({
3280
- $hostId$: childIdSplt[1],
3281
- $nodeId$: childIdSplt[2],
3282
- $depth$: childIdSplt[3],
3283
- $index$: childIdSplt[4] || "0",
3284
- $elm$: node
3285
- });
3286
- if (childNodeType === "t") {
3287
- childVNode.$elm$ = findCorrespondingNode(node, NODE_TYPE.TextNode);
3288
- if (childVNode.$elm$ && childVNode.$elm$.nodeType === NODE_TYPE.TextNode) {
3289
- childVNode.$text$ = childVNode.$elm$.textContent;
3290
- childRenderNodes.push(childVNode);
3291
- node.remove();
3292
- if (hostId === childVNode.$hostId$) {
3293
- if (!parentVNode.$children$) parentVNode.$children$ = [];
3294
- parentVNode.$children$[childVNode.$index$] = childVNode;
3295
- }
3296
- if (shadowRootNodes && childVNode.$depth$ === "0") shadowRootNodes[childVNode.$index$] = childVNode.$elm$;
3297
- }
3298
- } else if (childNodeType === "c") {
3299
- childVNode.$elm$ = findCorrespondingNode(node, NODE_TYPE.CommentNode);
3300
- if (childVNode.$elm$ && childVNode.$elm$.nodeType === NODE_TYPE.CommentNode) {
3301
- childRenderNodes.push(childVNode);
3302
- node.remove();
3303
- }
3304
- } else if (childVNode.$hostId$ === hostId) {
3305
- if (childNodeType === "s") addSlot(node["s-sn"] = childIdSplt[5] || "", childIdSplt[2], childVNode, node, parentVNode, childRenderNodes, slotNodes, shadowRootNodes, slottedNodes);
3306
- else if (childNodeType === "r") {
3307
- if (BUILD.shadowDom && shadowRootNodes) node.remove();
3308
- else if (BUILD.slotRelocation) {
3309
- hostElm["s-cr"] = node;
3310
- node["s-cn"] = true;
3311
- }
3312
- }
3313
- }
3314
- }
3315
- } else if (parentVNode && parentVNode.$tag$ === "style") {
3316
- const vnode = newVNode(null, node.textContent);
3317
- vnode.$elm$ = node;
3318
- vnode.$index$ = "0";
3319
- parentVNode.$children$ = [vnode];
3320
- }
3321
- return parentVNode;
3322
- };
3323
- /**
3324
- * Recursively locate any comments representing an 'original location' for a node; in a node's children or shadowRoot children.
3325
- * Creates a map of component IDs and 'original location' ID's which are derived from comment nodes placed by 'vdom-annotations.ts'.
3326
- * Each 'original location' relates to a lightDOM node that was moved deeper into the SSR markup. e.g. `<!--o.1-->` maps to `<div c-id="0.1">`
3327
- *
3328
- * @param node The node to search.
3329
- * @param orgLocNodes A map of the original location annotations and the current node being searched.
3330
- */
3331
- const initializeDocumentHydrate = (node, orgLocNodes) => {
3332
- if (node.nodeType === NODE_TYPE.ElementNode) {
3333
- const componentId = node["s-id"] || node.getAttribute("s-id");
3334
- if (componentId) orgLocNodes.set(componentId, node);
3335
- let i = 0;
3336
- if (node.shadowRoot) for (; i < node.shadowRoot.childNodes.length; i++) initializeDocumentHydrate(node.shadowRoot.childNodes[i], orgLocNodes);
3337
- const nonShadowNodes = node.__childNodes || node.childNodes;
3338
- for (i = 0; i < nonShadowNodes.length; i++) initializeDocumentHydrate(nonShadowNodes[i], orgLocNodes);
3339
- } else if (node.nodeType === NODE_TYPE.CommentNode) {
3340
- const childIdSplt = node.nodeValue.split(".");
3341
- if (childIdSplt[0] === "o") {
3342
- orgLocNodes.set(childIdSplt[1] + "." + childIdSplt[2], node);
3343
- node.nodeValue = "";
3344
- node["s-en"] = childIdSplt[3];
3345
- }
3346
- }
3347
- };
3348
- /**
3349
- * Creates a VNode to add to a hydrated component VDOM
3350
- *
3351
- * @param vnode - a vnode partial which will be augmented
3352
- * @returns an complete vnode
3353
- */
3354
- const createSimpleVNode = (vnode) => ({
3355
- $flags$: 0,
3356
- $index$: "0",
3357
- ...vnode
3358
- });
3359
- function addSlot(slotName, slotId, childVNode, node, parentVNode, childRenderNodes, slotNodes, shadowRootNodes, slottedNodes) {
3360
- node["s-sr"] = true;
3361
- childVNode.$name$ = slotName || null;
3362
- childVNode.$tag$ = "slot";
3363
- const parentNodeId = parentVNode?.$elm$ ? parentVNode.$elm$["s-id"] || parentVNode.$elm$.getAttribute("s-id") : "";
3364
- if (BUILD.shadowDom && shadowRootNodes && win.document) {
3365
- const slot = childVNode.$elm$ = win.document.createElement(childVNode.$tag$);
3366
- if (childVNode.$name$) childVNode.$elm$.setAttribute("name", slotName);
3367
- if (parentVNode.$elm$.shadowRoot && parentNodeId && parentNodeId !== childVNode.$hostId$) internalCall(parentVNode.$elm$, "insertBefore")(slot, internalCall(parentVNode.$elm$, "children")[0]);
3368
- else internalCall(internalCall(node, "parentNode"), "insertBefore")(slot, node);
3369
- addSlottedNodes(slottedNodes, slotId, slotName, node, childVNode.$hostId$);
3370
- node.remove();
3371
- if (childVNode.$depth$ === "0") shadowRootNodes[childVNode.$index$] = childVNode.$elm$;
3372
- } else {
3373
- const slot = childVNode.$elm$;
3374
- const shouldMove = parentNodeId && parentNodeId !== childVNode.$hostId$ && parentVNode.$elm$.shadowRoot;
3375
- addSlottedNodes(slottedNodes, slotId, slotName, node, shouldMove ? parentNodeId : childVNode.$hostId$);
3376
- patchSlotNode(node);
3377
- if (shouldMove) parentVNode.$elm$.insertBefore(slot, parentVNode.$elm$.children[0]);
3378
- }
3379
- childRenderNodes.push(childVNode);
3380
- slotNodes.push(childVNode);
3381
- if (!parentVNode.$children$) parentVNode.$children$ = [];
3382
- parentVNode.$children$[childVNode.$index$] = childVNode;
3383
- }
3384
- /**
3385
- * Adds groups of slotted nodes (grouped by slot ID) to this host element's 'master' array.
3386
- * We'll use this after the host element's VDOM is completely constructed to finally position and add meta required by non-shadow slotted nodes
3387
- *
3388
- * @param slottedNodes - the main host element 'master' array to add to
3389
- * @param slotNodeId - the slot node unique ID
3390
- * @param slotName - the slot node name (can be '')
3391
- * @param slotNode - the slot node
3392
- * @param hostId - the host element id where this node should be slotted
3393
- */
3394
- const addSlottedNodes = (slottedNodes, slotNodeId, slotName, slotNode, hostId) => {
3395
- let slottedNode = slotNode.nextSibling;
3396
- const group = slottedNodes[slotNodeId] ||= [];
3397
- if (!slottedNode || slottedNode.nodeValue?.startsWith("s.")) return;
3398
- do {
3399
- const sa = slottedNode["getAttribute"] && slottedNode.getAttribute("slot");
3400
- if ((sa || slottedNode["s-sn"]) === slotName || slotName === "" && !slottedNode["s-sn"] && !sa && (slottedNode.nodeType === NODE_TYPE.CommentNode || slottedNode.nodeType === NODE_TYPE.TextNode)) {
3401
- slottedNode["s-sn"] = slotName;
3402
- group.push({
3403
- slot: slotNode,
3404
- node: slottedNode,
3405
- hostId
3406
- });
3407
- }
3408
- slottedNode = slottedNode.nextSibling;
3409
- } while (slottedNode && !slottedNode.nodeValue?.startsWith("s."));
3410
- };
3411
- /**
3412
- * Steps through the node's siblings to find the next node of a specific type, with a value.
3413
- * e.g. when we find a position comment `<!--t.1-->`, we need to find the next text node with a value.
3414
- * (it's a guard against whitespace which is never accounted for in the SSR output)
3415
- * @param node - the starting node
3416
- * @param type - the type of node to find
3417
- * @returns the first corresponding node of the type
3418
- */
3419
- const findCorrespondingNode = (node, type) => {
3420
- let sibling = node;
3421
- do
3422
- sibling = sibling.nextSibling;
3423
- while (sibling && (sibling.nodeType !== type || !sibling.nodeValue));
3424
- return sibling;
3425
- };
3426
- //#endregion
3427
- //#region src/utils/shadow-css.ts
3428
- /**
3429
- * @license
3430
- * Copyright Google Inc. All Rights Reserved.
3431
- *
3432
- * Use of this source code is governed by an MIT-style license that can be
3433
- * found in the LICENSE file at https://angular.io/license
3434
- *
3435
- * This file is a port of shadowCSS from `webcomponents.js` to TypeScript.
3436
- * https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
3437
- * https://github.com/angular/angular/blob/master/packages/compiler/src/shadow_css.ts
3438
- */
3439
- const safeSelector = (selector) => {
3440
- const placeholders = [];
3441
- let index = 0;
3442
- selector = selector.replace(/(\[\s*part~=\s*("[^"]*"|'[^']*')\s*\])/g, (_, keep) => {
3443
- const replaceBy = `__part-${index}__`;
3444
- placeholders.push(keep);
3445
- index++;
3446
- return replaceBy;
3447
- });
3448
- selector = selector.replace(/(\[[^\]]*\])/g, (_, keep) => {
3449
- const replaceBy = `__ph-${index}__`;
3450
- placeholders.push(keep);
3451
- index++;
3452
- return replaceBy;
3453
- });
3454
- return {
3455
- content: selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
3456
- const replaceBy = `__ph-${index}__`;
3457
- placeholders.push(exp);
3458
- index++;
3459
- return pseudo + replaceBy;
3460
- }),
3461
- placeholders
3462
- };
3463
- };
3464
- const restoreSafeSelector = (placeholders, content) => {
3465
- content = content.replace(/__part-(\d+)__/g, (_, index) => placeholders[+index]);
3466
- return content.replace(/__ph-(\d+)__/g, (_, index) => placeholders[+index]);
3467
- };
3468
- const _polyfillHost = "-shadowcsshost";
3469
- const _polyfillSlotted = "-shadowcssslotted";
3470
- const _polyfillHostContext = "-shadowcsscontext";
3471
- let _cssColonHostRe;
3472
- let _cssColonHostContextRe;
3473
- let _cssColonSlottedRe;
3474
- const getCssColonHostRe = () => _cssColonHostRe ??= /* @__PURE__ */ new RegExp("(-shadowcsshost)(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)", "gim");
3475
- const getCssColonHostContextRe = () => _cssColonHostContextRe ??= /* @__PURE__ */ new RegExp("(-shadowcsscontext)(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)", "gim");
3476
- const getCssColonSlottedRe = () => _cssColonSlottedRe ??= /* @__PURE__ */ new RegExp("(-shadowcssslotted)(?:\\(((?:\\([^)(]*\\)|[^)(]*)+?)\\))?([^,{]*)", "gim");
3477
- const _polyfillHostNoCombinator = "-shadowcsshost-no-combinator";
3478
- const _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
3479
- const _shadowDOMSelectorsRe = [/::shadow/g, /::content/g];
3480
- const _safePartRe = /__part-(\d+)__/g;
3481
- const _polyfillHostRe = /-shadowcsshost/gim;
3482
- /**
3483
- * Little helper for generating a regex that will match a specified
3484
- * CSS selector when that selector is _not_ a part of a `@supports` rule.
3485
- *
3486
- * The pattern will match the provided `selector` (i.e. ':host', ':host-context', etc.)
3487
- * when that selector is not a part of a `@supports` selector rule _or_ if the selector
3488
- * is a part of the rule's declaration.
3489
- *
3490
- * For instance, if we create the regex with the selector ':host-context':
3491
- * - '@supports selector(:host-context())' will return no matches (starts with '@supports')
3492
- * - '@supports selector(:host-context()) { :host-context() { ... }}' will match the second ':host-context' (part of declaration)
3493
- * - ':host-context() { ... }' will match ':host-context' (selector is not a '@supports' rule)
3494
- * - ':host() { ... }' will return no matches (selector doesn't match selector used to create regex)
3495
- *
3496
- * @param selector The CSS selector we want to match for replacement
3497
- * @returns A look-behind regex containing the selector
3498
- */
3499
- const createSupportsRuleRe = (selector) => {
3500
- const escapedSelector = escapeRegExpSpecialCharacters(selector);
3501
- return new RegExp(`(^|[^@]|@(?!supports\\s+selector\\s*\\([^{]*?${escapedSelector}))(${escapedSelector}\\b)`, "g");
3502
- };
3503
- const _commentRe = /\/\*\s*[\s\S]*?\*\//g;
3504
- const stripComments = (input) => {
3505
- return input.replace(_commentRe, "");
3506
- };
3507
- const _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
3508
- const extractCommentsWithHash = (input) => {
3509
- return input.match(_commentWithHashRe) || [];
3510
- };
3511
- const _ruleRe = /(\s*)([^;{}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
3512
- const _curlyRe = /([{}])/g;
3513
- const _selectorPartsRe = /(^.*?[^\\])??((:+)(.*)|$)/;
3514
- const OPEN_CURLY = "{";
3515
- const CLOSE_CURLY = "}";
3516
- const BLOCK_PLACEHOLDER = "%BLOCK%";
3517
- const processRules = (input, ruleCallback) => {
3518
- const inputWithEscapedBlocks = escapeBlocks(input);
3519
- let nextBlockIndex = 0;
3520
- return inputWithEscapedBlocks.escapedString.replace(_ruleRe, (...m) => {
3521
- const selector = m[2];
3522
- let content = "";
3523
- let suffix = m[4];
3524
- let contentPrefix = "";
3525
- if (suffix && suffix.startsWith("{%BLOCK%")) {
3526
- content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
3527
- suffix = suffix.substring(8);
3528
- contentPrefix = "{";
3529
- }
3530
- const rule = ruleCallback({
3531
- selector,
3532
- content
3533
- });
3534
- return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
3535
- });
3536
- };
3537
- const escapeBlocks = (input) => {
3538
- const inputParts = input.split(_curlyRe);
3539
- const resultParts = [];
3540
- const escapedBlocks = [];
3541
- let bracketCount = 0;
3542
- let currentBlockParts = [];
3543
- for (let partIndex = 0; partIndex < inputParts.length; partIndex++) {
3544
- const part = inputParts[partIndex];
3545
- if (part === CLOSE_CURLY) bracketCount--;
3546
- if (bracketCount > 0) currentBlockParts.push(part);
3547
- else {
3548
- if (currentBlockParts.length > 0) {
3549
- escapedBlocks.push(currentBlockParts.join(""));
3550
- resultParts.push(BLOCK_PLACEHOLDER);
3551
- currentBlockParts = [];
3552
- }
3553
- resultParts.push(part);
3554
- }
3555
- if (part === OPEN_CURLY) bracketCount++;
3556
- }
3557
- if (currentBlockParts.length > 0) {
3558
- escapedBlocks.push(currentBlockParts.join(""));
3559
- resultParts.push(BLOCK_PLACEHOLDER);
3560
- }
3561
- return {
3562
- escapedString: resultParts.join(""),
3563
- blocks: escapedBlocks
3564
- };
3565
- };
3566
- /**
3567
- * Replaces certain strings within the CSS with placeholders
3568
- * that will later be replaced with class selectors appropriate
3569
- * for the level of encapsulation (shadow or scoped).
3570
- *
3571
- * When performing these replacements, we want to ignore selectors that are a
3572
- * part of an `@supports` rule. Replacing these selectors will result in invalid
3573
- * CSS that gets passed to autoprefixer/postcss once the placeholders are replaced.
3574
- * For example, a rule like:
3575
- *
3576
- * ```css
3577
- * @supports selector(:host()) {
3578
- * :host {
3579
- * color: red;
3580
- * }
3581
- * }
3582
- * ```
3583
- *
3584
- * Should be converted to:
3585
- *
3586
- * ```css
3587
- * @supports selector(:host()) {
3588
- * -shadowcsshost {
3589
- * color: red;
3590
- * }
3591
- * }
3592
- * ```
3593
- *
3594
- * The order the regex replacements happen in matters since we match
3595
- * against a whole selector word so we need to match all of `:host-context`
3596
- * before we try to replace `:host`. Otherwise the pattern for `:host` would match
3597
- * `:host-context` resulting in something like `:-shadowcsshost-context`.
3598
- *
3599
- * @param cssText A CSS string for a component
3600
- * @returns The modified CSS string
3601
- */
3602
- const insertPolyfillHostInCssText = (cssText) => {
3603
- const supportsBlocks = [];
3604
- cssText = cssText.replace(/@supports\s+selector\s*\(\s*([^)]*)\s*\)/g, (_, selectorContent) => {
3605
- const placeholder = `__supports_${supportsBlocks.length}__`;
3606
- supportsBlocks.push(selectorContent);
3607
- return `@supports selector(${placeholder})`;
3608
- });
3609
- const _colonSlottedRe = createSupportsRuleRe("::slotted");
3610
- const _colonHostRe = createSupportsRuleRe(":host");
3611
- const _colonHostContextRe = createSupportsRuleRe(":host-context");
3612
- cssText = cssText.replace(_colonHostContextRe, `$1${_polyfillHostContext}`).replace(_colonHostRe, `$1${_polyfillHost}`).replace(_colonSlottedRe, `$1${_polyfillSlotted}`);
3613
- supportsBlocks.forEach((originalSelector, index) => {
3614
- cssText = cssText.replace(`__supports_${index}__`, originalSelector);
3615
- });
3616
- return cssText;
3617
- };
3618
- const convertColonRule = (cssText, regExp, partReplacer) => {
3619
- return cssText.replace(regExp, (...m) => {
3620
- if (m[2]) {
3621
- const parts = m[2].split(",");
3622
- const r = [];
3623
- for (let i = 0; i < parts.length; i++) {
3624
- const p = parts[i].trim();
3625
- if (!p) break;
3626
- r.push(partReplacer(_polyfillHostNoCombinator, p, m[3]));
3627
- }
3628
- return r.join(",");
3629
- } else return _polyfillHostNoCombinator + m[3];
3630
- });
3631
- };
3632
- const colonHostPartReplacer = (host, part, suffix) => {
3633
- return host + part.replace(_polyfillHost, "") + suffix;
3634
- };
3635
- const convertColonHost = (cssText) => {
3636
- return convertColonRule(cssText, getCssColonHostRe(), colonHostPartReplacer);
3637
- };
3638
- const colonHostContextPartReplacer = (host, part, suffix) => {
3639
- if (part.indexOf(_polyfillHost) > -1) return colonHostPartReplacer(host, part, suffix);
3640
- else return host + part + suffix + ", " + part + " " + host + suffix;
3641
- };
3642
- const convertColonSlotted = (cssText, slotScopeId) => {
3643
- const slotClass = "." + slotScopeId + " > ";
3644
- const selectors = [];
3645
- cssText = cssText.replace(getCssColonSlottedRe(), (...m) => {
3646
- if (m[2]) {
3647
- const compound = m[2].trim();
3648
- const suffix = m[3];
3649
- const slottedSelector = slotClass + compound + suffix;
3650
- let prefixSelector = "";
3651
- for (let i = m[4] - 1; i >= 0; i--) {
3652
- const char = m[5][i];
3653
- if (char === "}" || char === ",") break;
3654
- prefixSelector = char + prefixSelector;
3655
- }
3656
- const orgSelector = (prefixSelector + slottedSelector).trim();
3657
- const addedSelector = `${prefixSelector.trimEnd()}${slottedSelector.trim()}`.trim();
3658
- if (orgSelector !== addedSelector) {
3659
- const updatedSelector = `${addedSelector}, ${orgSelector}`;
3660
- selectors.push({
3661
- orgSelector,
3662
- updatedSelector
3663
- });
3664
- }
3665
- return slottedSelector;
3666
- } else return _polyfillHostNoCombinator + m[3];
3667
- });
3668
- return {
3669
- selectors,
3670
- cssText
3671
- };
3672
- };
3673
- const convertColonHostContext = (cssText) => {
3674
- return convertColonRule(cssText, getCssColonHostContextRe(), colonHostContextPartReplacer);
3675
- };
3676
- const convertShadowDOMSelectors = (cssText) => {
3677
- return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, " "), cssText);
3678
- };
3679
- const makeScopeMatcher = (scopeSelector) => {
3680
- scopeSelector = scopeSelector.replace(/\[/g, "\\[").replace(/\]/g, "\\]");
3681
- return new RegExp("^(" + scopeSelector + ")([>\\s~+[.,{:][\\s\\S]*)?$", "m");
3682
- };
3683
- const selectorNeedsScoping = (selector, scopeSelector) => {
3684
- return !makeScopeMatcher(scopeSelector).test(selector);
3685
- };
3686
- const injectScopingSelector = (selector, scopingSelector) => {
3687
- return selector.replace(_selectorPartsRe, (_, before = "", _colonGroup, colon = "", after = "") => {
3688
- return before + scopingSelector + colon + after;
3689
- });
3690
- };
3691
- const applySimpleSelectorScope = (selector, scopeSelector, hostSelector) => {
3692
- _polyfillHostRe.lastIndex = 0;
3693
- if (_polyfillHostRe.test(selector)) {
3694
- const replaceBy = `.${hostSelector}`;
3695
- return selector.replace(_polyfillHostNoCombinatorRe, (_, sel) => injectScopingSelector(sel, replaceBy)).replace(_polyfillHostRe, replaceBy + " ");
3696
- }
3697
- return scopeSelector + " " + selector;
3698
- };
3699
- const applyStrictSelectorScope = (selector, scopeSelector, hostSelector) => {
3700
- scopeSelector = scopeSelector.replace(/\[is=([^\]]*)\]/g, (_, ...parts) => parts[0]);
3701
- const className = "." + scopeSelector;
3702
- const _scopeSelectorPart = (p) => {
3703
- let scopedP = p.trim();
3704
- if (!scopedP) return "";
3705
- if (p.indexOf(_polyfillHostNoCombinator) > -1) scopedP = applySimpleSelectorScope(p, scopeSelector, hostSelector);
3706
- else {
3707
- const t = p.replace(_polyfillHostRe, "");
3708
- if (t.length > 0) scopedP = injectScopingSelector(t, className);
3709
- }
3710
- return scopedP;
3711
- };
3712
- const safeContent = safeSelector(selector);
3713
- selector = safeContent.content;
3714
- let scopedSelector = "";
3715
- let startIndex = 0;
3716
- let res;
3717
- const sep = /( |>|\+|~(?!=))(?=(?:[^()]*\([^()]*\))*[^()]*$)\s*/g;
3718
- let shouldScope = !(selector.indexOf(_polyfillHostNoCombinator) > -1);
3719
- while ((res = sep.exec(selector)) !== null) {
3720
- const separator = res[1];
3721
- const part = selector.slice(startIndex, res.index).trim();
3722
- shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
3723
- const scopedPart = shouldScope ? _scopeSelectorPart(part) : part;
3724
- scopedSelector += `${scopedPart} ${separator} `;
3725
- startIndex = sep.lastIndex;
3726
- }
3727
- const part = selector.substring(startIndex);
3728
- shouldScope = !part.match(_safePartRe) && (shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1);
3729
- scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
3730
- return restoreSafeSelector(safeContent.placeholders, scopedSelector);
3731
- };
3732
- const scopeSelector = (selector, scopeSelectorText, hostSelector, slotSelector) => {
3733
- return selector.split(",").map((shallowPart) => {
3734
- if (slotSelector && shallowPart.indexOf("." + slotSelector) > -1) return shallowPart.trim();
3735
- if (selectorNeedsScoping(shallowPart, scopeSelectorText)) return applyStrictSelectorScope(shallowPart, scopeSelectorText, hostSelector).trim();
3736
- else return shallowPart.trim();
3737
- }).join(", ");
3738
- };
3739
- const scopeSelectors = (cssText, scopeSelectorText, hostSelector, slotSelector, commentOriginalSelector) => {
3740
- return processRules(cssText, (rule) => {
3741
- let selector = rule.selector;
3742
- let content = rule.content;
3743
- if (rule.selector[0] !== "@") selector = scopeSelector(rule.selector, scopeSelectorText, hostSelector, slotSelector);
3744
- else if (rule.selector.startsWith("@media") || rule.selector.startsWith("@supports") || rule.selector.startsWith("@page") || rule.selector.startsWith("@document")) content = scopeSelectors(rule.content, scopeSelectorText, hostSelector, slotSelector, commentOriginalSelector);
3745
- return {
3746
- selector: selector.replace(/\s{2,}/g, " ").trim(),
3747
- content
3748
- };
3749
- });
3750
- };
3751
- const scopeCssText = (cssText, scopeId, hostScopeId, slotScopeId, commentOriginalSelector) => {
3752
- cssText = insertPolyfillHostInCssText(cssText);
3753
- cssText = convertColonHost(cssText);
3754
- cssText = convertColonHostContext(cssText);
3755
- const slotted = convertColonSlotted(cssText, slotScopeId);
3756
- cssText = slotted.cssText;
3757
- cssText = convertShadowDOMSelectors(cssText);
3758
- if (scopeId) cssText = scopeSelectors(cssText, scopeId, hostScopeId, slotScopeId, commentOriginalSelector);
3759
- cssText = replaceShadowCssHost(cssText, hostScopeId);
3760
- cssText = cssText.replace(/>\s*\*\s+([^{, ]+)/gm, " $1 ");
3761
- return {
3762
- cssText: cssText.trim(),
3763
- slottedSelectors: slotted.selectors.map((ref) => ({
3764
- orgSelector: replaceShadowCssHost(ref.orgSelector, hostScopeId),
3765
- updatedSelector: replaceShadowCssHost(ref.updatedSelector, hostScopeId)
3766
- }))
3767
- };
3768
- };
3769
- /**
3770
- * Helper function that replaces the interim string representing a `:host` selector with
3771
- * the host scope selector class for the element.
3772
- *
3773
- * @param cssText The CSS string to make the replacement in
3774
- * @param hostScopeId The scope ID that will be used as the class representing the host element
3775
- * @returns CSS with the selector replaced
3776
- */
3777
- const replaceShadowCssHost = (cssText, hostScopeId) => {
3778
- return cssText.replace(/-shadowcsshost-no-combinator/g, `.${hostScopeId}`);
3779
- };
3780
- /**
3781
- * Expands selectors with ::part(...) to also include [part~="..."] selectors.
3782
- * For example:
3783
- * ```css
3784
- * selectors-like-this::part(demo) { ... }
3785
- * .something .selectors::part(demo demo2):hover { ... }
3786
- * ```
3787
- * Becomes:
3788
- * ```
3789
- * selectors-like-this::part(demo), selectors-like-this [part~="demo"] { ... }
3790
- * .something .selectors::part(demo demo2):hover, .something .selectors [part~="demo"][part~="demo2"]:hover { ... }
3791
- * ```
3792
- *
3793
- * @param cssText The CSS text to process
3794
- * @returns The CSS text with expanded ::part(...) selectors
3795
- */
3796
- const expandPartSelectors = (cssText) => {
3797
- const partSelectorRe = /([^\s,{][^,{]*?)::part\(\s*([^)]+?)\s*\)((?:[:.][^,{]*)*)/g;
3798
- return processRules(cssText, (rule) => {
3799
- if (rule.selector[0] === "@") return rule;
3800
- rule.selector = rule.selector.split(",").map((sel) => {
3801
- const out = [sel.trim()];
3802
- let m;
3803
- while ((m = partSelectorRe.exec(sel)) !== null) {
3804
- const before = m[1].trimEnd();
3805
- const partNames = m[2].trim().split(/\s+/);
3806
- const after = m[3] || "";
3807
- const partAttr = partNames.flatMap((p) => {
3808
- if (!rule.selector.includes(`[part~="${p}"]`)) return [`[part~="${p}"]`];
3809
- return [];
3810
- }).join("");
3811
- const expanded = `${before} ${partAttr}${after}`;
3812
- if (!!partAttr && expanded !== sel.trim()) out.push(expanded);
3813
- }
3814
- return out.join(", ");
3815
- }).join(", ");
3816
- return rule;
3817
- });
3818
- };
3819
- const scopeCss = (cssText, scopeId, commentOriginalSelector) => {
3820
- const hostScopeId = scopeId + "-h";
3821
- const slotScopeId = scopeId + "-s";
3822
- const commentsWithHash = extractCommentsWithHash(cssText);
3823
- cssText = stripComments(cssText);
3824
- const orgSelectors = [];
3825
- if (commentOriginalSelector) {
3826
- const processCommentedSelector = (rule) => {
3827
- const placeholder = `/*!@___${orgSelectors.length}___*/`;
3828
- const comment = `/*!@${rule.selector}*/`;
3829
- orgSelectors.push({
3830
- placeholder,
3831
- comment
3832
- });
3833
- rule.selector = placeholder + rule.selector;
3834
- return rule;
3835
- };
3836
- cssText = processRules(cssText, (rule) => {
3837
- if (rule.selector[0] !== "@") return processCommentedSelector(rule);
3838
- else if (rule.selector.startsWith("@media") || rule.selector.startsWith("@supports") || rule.selector.startsWith("@page") || rule.selector.startsWith("@document")) {
3839
- rule.content = processRules(rule.content, processCommentedSelector);
3840
- return rule;
3841
- }
3842
- return rule;
3843
- });
3844
- }
3845
- const scoped = scopeCssText(cssText, scopeId, hostScopeId, slotScopeId, commentOriginalSelector);
3846
- cssText = [scoped.cssText, ...commentsWithHash].join("\n");
3847
- if (commentOriginalSelector) orgSelectors.forEach(({ placeholder, comment }) => {
3848
- cssText = cssText.replace(placeholder, comment);
3849
- });
3850
- scoped.slottedSelectors.forEach((slottedSelector) => {
3851
- const regex = new RegExp(escapeRegExpSpecialCharacters(slottedSelector.orgSelector) + "(?=\\s*[,{]|$)", "g");
3852
- cssText = cssText.replace(regex, slottedSelector.updatedSelector);
3853
- });
3854
- cssText = expandPartSelectors(cssText);
3855
- return cssText;
3856
- };
3857
- //#endregion
3858
- //#region src/runtime/mode.ts
3859
- const computeMode = (elm) => modeResolutionChain.map((h) => h(elm)).find((m) => !!m);
3860
- const setMode = (handler) => modeResolutionChain.push(handler);
3861
- const getMode = (ref) => getHostRef(ref)?.$modeName$;
3862
- //#endregion
3863
- //#region src/runtime/normalize-watchers.ts
3864
- /**
3865
- * Normalizes watcher metadata to the current `{ [methodName]: flags }[]` format.
3866
- *
3867
- * Prior to Stencil 4.39.x (PR #6484), the `@Watch()` compiler emitted watcher
3868
- * handlers as a plain string array: `{ "min": ["minChanged"] }`. The new format
3869
- * wraps each entry in an object that carries option flags (e.g. `immediate`):
3870
- * `{ "min": [{ "minChanged": 0 }] }`.
3871
- *
3872
- * When a library (e.g. Ionic Framework) was compiled with an older Stencil compiler
3873
- * but consumed by an app using a newer Stencil runtime, the runtime's
3874
- * `Object.entries(watcher)` call receives a string and misinterprets its character
3875
- * indices as method names, causing:
3876
- * `TypeError: instance[watchMethodName] is not a function`
3877
- *
3878
- * This helper should be used at `$watchers$` assignment sites that need to
3879
- * accept both legacy and current compiler metadata so downstream code on those
3880
- * paths can safely assume the new object format.
3881
- *
3882
- * @param raw The raw watcher map from compiled metadata (new or legacy format).
3883
- * @returns A normalized watcher map in the `{ [methodName]: flags }[]` format, or `undefined` if `raw` is `undefined` or empty.
3884
- */
3885
- const normalizeWatchers = (raw) => {
3886
- if (!raw) return void 0;
3887
- const keys = Object.keys(raw);
3888
- if (keys.length === 0) return void 0;
3889
- let hasLegacy = false;
3890
- for (const propName of keys) {
3891
- if (hasLegacy) break;
3892
- for (const h of raw[propName]) if (typeof h === "string") {
3893
- hasLegacy = true;
3894
- break;
3895
- }
3896
- }
3897
- if (!hasLegacy) return raw;
3898
- const out = {};
3899
- for (const propName of keys) out[propName] = raw[propName].map((h) => typeof h === "string" ? { [h]: 0 } : h);
3900
- return out;
3901
- };
3902
- //#endregion
3903
- //#region src/runtime/parse-property-value.ts
3904
- /**
3905
- * Parse a new property value for a given property type.
3906
- *
3907
- * While the prop value can reasonably be expected to be of `any` type as far as TypeScript's type checker is concerned,
3908
- * it is not safe to assume that the string returned by evaluating `typeof propValue` matches:
3909
- * 1. `any`, the type given to `propValue` in the function signature
3910
- * 2. the type stored from `propType`.
3911
- *
3912
- * This function provides the capability to parse/coerce a property's value to potentially any other JavaScript type.
3913
- *
3914
- * Property values represented in TSX preserve their type information. In the example below, the number 0 is passed to
3915
- * a component. This `propValue` will preserve its type information (`typeof propValue === 'number'`). Note that is
3916
- * based on the type of the value being passed in, not the type declared of the class member decorated with `@Prop`.
3917
- * ```tsx
3918
- * <my-cmp prop-val={0}></my-cmp>
3919
- * ```
3920
- *
3921
- * HTML prop values on the other hand, will always a string
3922
- *
3923
- * @param propValue the new value to coerce to some type
3924
- * @param propType the type of the prop, expressed as a binary number
3925
- * @param isFormAssociated whether the component is form-associated (optional)
3926
- * @returns the parsed/coerced value
3927
- */
3928
- const parsePropertyValue = (propValue, propType, isFormAssociated) => {
3929
- if (propValue != null && !isComplexType(propValue)) {
3930
- /**
3931
- * ensure this value is of the correct prop type
3932
- */
3933
- if (BUILD.propBoolean && propType & MEMBER_FLAGS.Boolean) {
3934
- /**
3935
- * For form-associated components, according to HTML spec, the presence of any boolean attribute
3936
- * (regardless of its value, even "false") should make the property true.
3937
- * For non-form-associated components, we maintain the legacy behavior where "false" becomes false.
3938
- */
3939
- if (BUILD.formAssociated && isFormAssociated && typeof propValue === "string") return propValue === "" || !!propValue;
3940
- else return propValue === "false" ? false : propValue === "" || !!propValue;
3941
- }
3942
- /**
3943
- * force it to be a number
3944
- */
3945
- if (BUILD.propNumber && propType & MEMBER_FLAGS.Number) return typeof propValue === "string" ? parseFloat(propValue) : typeof propValue === "number" ? propValue : NaN;
3946
- /**
3947
- * could have been passed as a number or boolean but we still want it as a string
3948
- */
3949
- if (BUILD.propString && propType & MEMBER_FLAGS.String) return String(propValue);
3950
- return propValue;
3951
- }
3952
- /**
3953
- * not sure exactly what type we want so no need to change to a different type
3954
- */
3955
- return propValue;
3956
- };
3957
- //#endregion
3958
- //#region src/runtime/set-value.ts
3959
- const applySerializers = (hostRef, cmpMeta, propName, val, instance) => {
3960
- const run = (inst) => {
3961
- let attrVal = val;
3962
- for (const serializer of cmpMeta.$serializers$[propName]) {
3963
- const [[methodName]] = Object.entries(serializer);
3964
- attrVal = inst[methodName](attrVal, propName);
3965
- }
3966
- hostRef.$serializerValues$.set(propName, attrVal);
3967
- };
3968
- if (instance) run(instance);
3969
- else hostRef.$fetchedCbList$.push(() => run(hostRef.$lazyInstance$));
3970
- };
3971
- const getValue = (ref, propName) => {
3972
- if (BUILD.signalBacking) {
3973
- const sig = getHostRef(ref)?.$signalValues$?.get(propName);
3974
- if (sig !== void 0) return sig.value;
3975
- }
3976
- return getHostRef(ref).$instanceValues$.get(propName);
3977
- };
3978
- const setValue = (ref, propName, newVal, cmpMeta) => {
3979
- const hostRef = getHostRef(ref);
3980
- if (BUILD.signalBacking) {
3981
- const sig = hostRef?.$signalValues$?.get(propName);
3982
- if (sig !== void 0) {
3983
- const parsed = parsePropertyValue(newVal, cmpMeta.$members$[propName][0], BUILD.formAssociated && !!(cmpMeta.$flags$ & CMP_FLAGS.formAssociated));
3984
- if (BUILD.serializer && BUILD.reflect && cmpMeta.$attrsToReflect$ && cmpMeta.$serializers$?.[propName]) {
3985
- const elm = BUILD.lazyLoad ? hostRef.$hostElement$ : ref;
3986
- applySerializers(hostRef, cmpMeta, propName, parsed, BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm);
3987
- }
3988
- if (!(Number.isNaN(sig.peek()) && Number.isNaN(parsed))) sig.value = parsed;
3989
- return;
3990
- }
3991
- }
3992
- if (!hostRef) {
3993
- if (BUILD.lazyLoad) throw new Error(BUILD.isDev ? `Couldn't find host element for "${cmpMeta.$tagName$}". This usually happens when integrating a 3rd party Stencil component with another Stencil runtime. See https://github.com/stenciljs/core/issues/5457` : `Host element not found for "${cmpMeta.$tagName$}"`);
3994
- return;
3995
- }
3996
- if (BUILD.serializer && hostRef.$serializerValues$.has(propName) && hostRef.$serializerValues$.get(propName) === newVal) return;
3997
- const elm = BUILD.lazyLoad ? hostRef.$hostElement$ : ref;
3998
- const oldVal = hostRef.$instanceValues$.get(propName);
3999
- const flags = hostRef.$flags$;
4000
- const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
4001
- newVal = parsePropertyValue(newVal, cmpMeta.$members$[propName][0], BUILD.formAssociated && !!(cmpMeta.$flags$ & CMP_FLAGS.formAssociated));
4002
- const didValueChange = newVal !== oldVal && !(Number.isNaN(oldVal) && Number.isNaN(newVal));
4003
- if ((!BUILD.lazyLoad || !(flags & HOST_FLAGS.isConstructingInstance) || oldVal === void 0) && didValueChange) {
4004
- hostRef.$instanceValues$.set(propName, newVal);
4005
- if (BUILD.serializer && BUILD.reflect && cmpMeta.$attrsToReflect$ && cmpMeta.$serializers$?.[propName]) applySerializers(hostRef, cmpMeta, propName, newVal, instance);
4006
- if (BUILD.isDev) {
4007
- if (hostRef.$flags$ & HOST_FLAGS.devOnRender) consoleDevWarn(`The state/prop "${propName}" changed during rendering. This can potentially lead to infinite-loops and other bugs.`, "\nElement", elm, "\nNew value", newVal, "\nOld value", oldVal);
4008
- else if (hostRef.$flags$ & HOST_FLAGS.devOnDidLoad) consoleDevWarn(`The state/prop "${propName}" changed during "componentDidLoad()", this triggers extra re-renders, try to setup on "componentWillLoad()"`, "\nElement", elm, "\nNew value", newVal, "\nOld value", oldVal);
4009
- }
4010
- if (BUILD.propChangeCallback && cmpMeta.$watchers$) {
4011
- const watchMethods = cmpMeta.$watchers$[propName];
4012
- if (watchMethods) watchMethods.map((watcher) => {
4013
- try {
4014
- const [[watchMethodName, watcherFlags]] = Object.entries(watcher);
4015
- if (flags & HOST_FLAGS.isWatchReady || watcherFlags & WATCH_FLAGS.Immediate) {
4016
- if (BUILD.signalBacking && !hostRef.$signalValues$) return;
4017
- if (!instance) hostRef.$fetchedCbList$.push(() => {
4018
- hostRef.$lazyInstance$[watchMethodName](newVal, oldVal, propName);
4019
- });
4020
- else instance[watchMethodName](newVal, oldVal, propName);
4021
- }
4022
- } catch (e) {
4023
- consoleError(e, elm);
4024
- }
4025
- });
4026
- }
4027
- if (BUILD.updatable && flags & HOST_FLAGS.hasRendered) {
4028
- if (instance.componentShouldUpdate) {
4029
- const changes = hostRef.$queuedPropChanges$ ||= {};
4030
- changes[propName] = {
4031
- newVal,
4032
- oldVal: changes[propName]?.oldVal ?? oldVal
4033
- };
4034
- }
4035
- if (!(flags & HOST_FLAGS.isQueuedForUpdate)) scheduleUpdate(hostRef, false);
4036
- }
4037
- }
4038
- };
4039
- //#endregion
4040
- //#region src/runtime/proxy-component.ts
4041
- /**
4042
- * Attach a series of runtime constructs to a compiled Stencil component
4043
- * constructor, including getters and setters for the `@Prop` and `@State`
4044
- * decorators, callbacks for when attributes change, and so on.
4045
- *
4046
- * On a lazy loaded component, this is wired up to both the class instance
4047
- * and the element separately. A `hostRef` keeps the 2 in sync.
4048
- *
4049
- * On a traditional component, this is wired up to the element only.
4050
- *
4051
- * @param Cstr - the constructor for a component that we need to process
4052
- * @param cmpMeta - metadata collected previously about the component
4053
- * @param flags - a number used to store a series of bit flags
4054
- * @returns a reference to the same constructor passed in (but now mutated)
4055
- */
4056
- const proxyComponent = (Cstr, cmpMeta, flags) => {
4057
- const prototype = Cstr.prototype;
4058
- if (BUILD.isTesting) {
4059
- if (prototype.__stencilAugmented) return;
4060
- prototype.__stencilAugmented = true;
4061
- }
4062
- /**
4063
- * proxy form associated custom element lifecycle callbacks
4064
- * @see https://web.dev/articles/more-capable-form-controls#lifecycle_callbacks
4065
- */
4066
- if (BUILD.formAssociated && cmpMeta.$flags$ & CMP_FLAGS.formAssociated && flags & PROXY_FLAGS.isElementConstructor) FORM_ASSOCIATED_CUSTOM_ELEMENT_CALLBACKS.forEach((cbName) => {
4067
- const originalFormAssociatedCallback = prototype[cbName];
4068
- Object.defineProperty(prototype, cbName, { value(...args) {
4069
- const hostRef = getHostRef(this);
4070
- const instance = BUILD.lazyLoad ? hostRef?.$lazyInstance$ : this;
4071
- if (!instance) hostRef?.$onReadyPromise$?.then((asyncInstance) => {
4072
- const cb = asyncInstance[cbName];
4073
- if (typeof cb === "function") cb.call(asyncInstance, ...args);
4074
- });
4075
- else {
4076
- const cb = BUILD.lazyLoad ? instance[cbName] : originalFormAssociatedCallback;
4077
- if (typeof cb === "function") cb.call(instance, ...args);
4078
- }
4079
- } });
4080
- });
4081
- if (BUILD.member && cmpMeta.$members$ || BUILD.propChangeCallback) {
4082
- if (BUILD.propChangeCallback) {
4083
- if (Cstr.watchers && !cmpMeta.$watchers$) cmpMeta.$watchers$ = normalizeWatchers(Cstr.watchers);
4084
- if (Cstr.deserializers && !cmpMeta.$deserializers$) cmpMeta.$deserializers$ = Cstr.deserializers;
4085
- if (Cstr.serializers && !cmpMeta.$serializers$) cmpMeta.$serializers$ = Cstr.serializers;
4086
- }
4087
- const members = Object.entries(cmpMeta.$members$ ?? {});
4088
- members.map(([memberName, [memberFlags]]) => {
4089
- if ((BUILD.prop || BUILD.state) && (memberFlags & MEMBER_FLAGS.Prop || (!BUILD.lazyLoad || flags & PROXY_FLAGS.proxyState) && memberFlags & MEMBER_FLAGS.State)) {
4090
- const { get: origGetter, set: origSetter } = getPropertyDescriptor(prototype, memberName) || {};
4091
- if (origGetter) cmpMeta.$members$[memberName][0] |= MEMBER_FLAGS.Getter;
4092
- if (origSetter) cmpMeta.$members$[memberName][0] |= MEMBER_FLAGS.Setter;
4093
- if (flags & PROXY_FLAGS.isElementConstructor || !origGetter) Object.defineProperty(prototype, memberName, {
4094
- get() {
4095
- if (BUILD.lazyLoad) {
4096
- if ((cmpMeta.$members$[memberName][0] & MEMBER_FLAGS.Getter) === 0) return getValue(this, memberName);
4097
- const ref = getHostRef(this);
4098
- const instance = ref ? ref.$lazyInstance$ : prototype;
4099
- if (!instance) return;
4100
- return instance[memberName];
4101
- }
4102
- if (!BUILD.lazyLoad) return origGetter ? origGetter.apply(this) : getValue(this, memberName);
4103
- },
4104
- configurable: true,
4105
- enumerable: true
4106
- });
4107
- Object.defineProperty(prototype, memberName, { set(newValue) {
4108
- const ref = getHostRef(this);
4109
- if (!ref) return;
4110
- if (BUILD.isDev) {
4111
- if ((flags & PROXY_FLAGS.isElementConstructor) === 0 && (cmpMeta.$members$[memberName][0] & MEMBER_FLAGS.Setter) === 0 && (ref && ref.$flags$ & HOST_FLAGS.isConstructingInstance) === 0 && (memberFlags & MEMBER_FLAGS.Prop) !== 0 && (memberFlags & MEMBER_FLAGS.Mutable) === 0) consoleDevWarn(`@Prop() "${memberName}" on <${cmpMeta.$tagName$}> is immutable but was modified from within the component.\nMore information: https://stenciljs.com/docs/properties#prop-mutability`);
4112
- }
4113
- if (origSetter) {
4114
- if (typeof (memberFlags & MEMBER_FLAGS.State ? this[memberName] : ref.$hostElement$[memberName]) === "undefined" && ref.$instanceValues$.get(memberName)) newValue = ref.$instanceValues$.get(memberName);
4115
- origSetter.apply(this, [parsePropertyValue(newValue, memberFlags, BUILD.formAssociated && !!(cmpMeta.$flags$ & CMP_FLAGS.formAssociated))]);
4116
- newValue = memberFlags & MEMBER_FLAGS.State ? this[memberName] : ref.$hostElement$[memberName];
4117
- setValue(this, memberName, newValue, cmpMeta);
4118
- return;
4119
- }
4120
- if (!BUILD.lazyLoad) {
4121
- setValue(this, memberName, newValue, cmpMeta);
4122
- return;
4123
- }
4124
- if (BUILD.lazyLoad) {
4125
- if ((flags & PROXY_FLAGS.isElementConstructor) === 0 || (cmpMeta.$members$[memberName][0] & MEMBER_FLAGS.Setter) === 0) {
4126
- setValue(this, memberName, newValue, cmpMeta);
4127
- if (flags & PROXY_FLAGS.isElementConstructor && !ref.$lazyInstance$) ref.$fetchedCbList$.push(() => {
4128
- if (cmpMeta.$members$[memberName][0] & MEMBER_FLAGS.Setter && ref.$lazyInstance$[memberName] !== ref.$instanceValues$.get(memberName)) ref.$lazyInstance$[memberName] = newValue;
4129
- });
4130
- return;
4131
- }
4132
- const setterSetVal = () => {
4133
- const currentValue = ref.$lazyInstance$[memberName];
4134
- if (!ref.$instanceValues$.get(memberName) && currentValue) ref.$instanceValues$.set(memberName, currentValue);
4135
- ref.$lazyInstance$[memberName] = parsePropertyValue(newValue, memberFlags, BUILD.formAssociated && !!(cmpMeta.$flags$ & CMP_FLAGS.formAssociated));
4136
- setValue(this, memberName, ref.$lazyInstance$[memberName], cmpMeta);
4137
- };
4138
- if (ref.$lazyInstance$) setterSetVal();
4139
- else ref.$fetchedCbList$.push(() => {
4140
- setterSetVal();
4141
- });
4142
- }
4143
- } });
4144
- } else if (BUILD.lazyLoad && BUILD.method && flags & PROXY_FLAGS.isElementConstructor && memberFlags & MEMBER_FLAGS.Method) Object.defineProperty(prototype, memberName, { value(...args) {
4145
- const ref = getHostRef(this);
4146
- return ref?.$onInstancePromise$?.then(() => ref.$lazyInstance$?.[memberName](...args));
4147
- } });
4148
- });
4149
- if (BUILD.observeAttribute && (!BUILD.lazyLoad || flags & PROXY_FLAGS.isElementConstructor)) {
4150
- const attrNameToPropName = /* @__PURE__ */ new Map();
4151
- prototype.attributeChangedCallback = function(attrName, oldValue, newValue) {
4152
- plt.jmp(() => {
4153
- const propName = attrNameToPropName.get(attrName);
4154
- const hostRef = getHostRef(this);
4155
- if (BUILD.serializer && hostRef.$serializerValues$.has(propName) && hostRef.$serializerValues$.get(propName) === newValue) return;
4156
- if (this.hasOwnProperty(propName) && BUILD.lazyLoad) {
4157
- newValue = this[propName];
4158
- delete this[propName];
4159
- }
4160
- if (BUILD.deserializer && cmpMeta.$deserializers$ && cmpMeta.$deserializers$[propName]) {
4161
- const setVal = (methodName, instance) => {
4162
- const deserializeVal = instance?.[methodName](newValue, propName);
4163
- if (deserializeVal !== this[propName]) this[propName] = deserializeVal;
4164
- };
4165
- for (const deserializer of cmpMeta.$deserializers$[propName]) {
4166
- const [[methodName]] = Object.entries(deserializer);
4167
- if (BUILD.lazyLoad) {
4168
- if (hostRef.$lazyInstance$) setVal(methodName, hostRef.$lazyInstance$);
4169
- else hostRef.$fetchedCbList$.push(() => {
4170
- setVal(methodName, hostRef.$lazyInstance$);
4171
- });
4172
- } else setVal(methodName, this);
4173
- }
4174
- return;
4175
- } else if (prototype.hasOwnProperty(propName) && typeof this[propName] === "number" && this[propName] == newValue) return;
4176
- else if (propName == null) {
4177
- const hostFlags = hostRef?.$flags$;
4178
- if (hostRef && hostFlags && !(hostFlags & HOST_FLAGS.isConstructingInstance) && newValue !== oldValue) {
4179
- const elm = BUILD.lazyLoad ? hostRef.$hostElement$ : this;
4180
- const instance = BUILD.lazyLoad ? hostRef.$lazyInstance$ : elm;
4181
- (cmpMeta.$watchers$?.[attrName])?.forEach((watcher) => {
4182
- const [[watchMethodName, watcherFlags]] = Object.entries(watcher);
4183
- if (instance[watchMethodName] != null && (hostFlags & HOST_FLAGS.isWatchReady || watcherFlags & WATCH_FLAGS.Immediate)) instance[watchMethodName](newValue, oldValue, attrName);
4184
- });
4185
- }
4186
- return;
4187
- }
4188
- const propFlags = members.find(([m]) => m === propName);
4189
- const isBooleanTarget = propFlags && propFlags[1][0] & MEMBER_FLAGS.Boolean;
4190
- const isSpuriousBooleanRemoval = isBooleanTarget && newValue === null && this[propName] === void 0;
4191
- if (isBooleanTarget) newValue = !(newValue === null || newValue === "false");
4192
- const propDesc = Object.getOwnPropertyDescriptor(prototype, propName);
4193
- if (!isSpuriousBooleanRemoval && newValue != this[propName] && (!propDesc.get || !!propDesc.set)) this[propName] = newValue;
4194
- });
4195
- };
4196
- Cstr.observedAttributes = Array.from(/* @__PURE__ */ new Set([...Object.keys(cmpMeta.$watchers$ ?? {}), ...members.filter(([_, m]) => m[0] & MEMBER_FLAGS.HasAttribute).map(([propName, m]) => {
4197
- const attrName = m[1] || propName;
4198
- attrNameToPropName.set(attrName, propName);
4199
- if (BUILD.reflect && m[0] & MEMBER_FLAGS.ReflectAttr) cmpMeta.$attrsToReflect$?.push([propName, attrName]);
4200
- return attrName;
4201
- })]));
4202
- }
4203
- }
4204
- return Cstr;
4205
- };
4206
- //#endregion
4207
- //#region src/runtime/initialize-component.ts
4208
- /**
4209
- * Initialize a Stencil component given a reference to its host element, its
4210
- * runtime bookkeeping data structure, runtime metadata about the component,
4211
- * and (optionally) an HMR version ID.
4212
- *
4213
- * @param elm a host element
4214
- * @param hostRef the element's runtime bookkeeping object
4215
- * @param cmpMeta runtime metadata for the Stencil component
4216
- * @param hmrVersionId an (optional) HMR version ID
4217
- */
4218
- const initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId) => {
4219
- let Cstr;
4220
- try {
4221
- if ((hostRef.$flags$ & HOST_FLAGS.hasInitializedComponent) === 0) {
4222
- hostRef.$flags$ |= HOST_FLAGS.hasInitializedComponent;
4223
- hostRef.$flags$ &= ~HOST_FLAGS.hasFailedLoad;
4224
- const bundleId = cmpMeta.$lazyBundleId$;
4225
- if (BUILD.lazyLoad && bundleId) {
4226
- const CstrImport = loadModule(cmpMeta, hostRef, hmrVersionId);
4227
- if (CstrImport && "then" in CstrImport) {
4228
- const endLoad = uniqueTime(`st:load:${cmpMeta.$tagName$}:${hostRef.$modeName$}`, `[Stencil] Load module for <${cmpMeta.$tagName$}>`);
4229
- Cstr = await CstrImport;
4230
- endLoad();
4231
- } else Cstr = CstrImport;
4232
- if (!Cstr) {
4233
- hostRef.$flags$ &= ~HOST_FLAGS.hasInitializedComponent;
4234
- hostRef.$loadRetryCount$ = (hostRef.$loadRetryCount$ ?? 0) + 1;
4235
- if (hostRef.$loadRetryCount$ < 3) hostRef.$flags$ |= HOST_FLAGS.hasFailedLoad;
4236
- throw new Error(`Constructor for "${cmpMeta.$tagName$}#${hostRef.$modeName$}" was not found`);
4237
- }
4238
- if (BUILD.member && !Cstr.isProxied) {
4239
- if (BUILD.propChangeCallback) {
4240
- cmpMeta.$watchers$ = normalizeWatchers(Cstr.watchers);
4241
- cmpMeta.$serializers$ = Cstr.serializers;
4242
- cmpMeta.$deserializers$ = Cstr.deserializers;
4243
- }
4244
- proxyComponent(Cstr, cmpMeta, PROXY_FLAGS.proxyState);
4245
- Cstr.isProxied = true;
4246
- }
4247
- const endNewInstance = createTime("createInstance", cmpMeta.$tagName$);
4248
- if (BUILD.member) hostRef.$flags$ |= HOST_FLAGS.isConstructingInstance;
4249
- try {
4250
- new Cstr(hostRef);
4251
- } catch (e) {
4252
- consoleError(e, elm);
4253
- }
4254
- if (BUILD.member) hostRef.$flags$ &= ~HOST_FLAGS.isConstructingInstance;
4255
- endNewInstance();
4256
- if (BUILD.asyncLoading && hostRef.$ancestorComponent$) await awaitAncestorConnected(hostRef.$ancestorComponent$);
4257
- if (!(BUILD.slotRelocation && cmpMeta.$flags$ & CMP_FLAGS.hasSlotRelocation)) {
4258
- fireConnectedCallback(hostRef.$lazyInstance$, elm);
4259
- if (BUILD.asyncLoading) markFirstConnected(hostRef);
4260
- } else queueMicrotask(() => {
4261
- fireConnectedCallback(hostRef.$lazyInstance$, elm);
4262
- if (BUILD.asyncLoading) markFirstConnected(hostRef);
4263
- });
4264
- } else Cstr = elm.constructor;
4265
- if (BUILD.style && Cstr && Cstr.style) {
4266
- /**
4267
- * this component has styles but we haven't registered them yet
4268
- */
4269
- let style;
4270
- if (typeof Cstr.style === "string")
4271
- /**
4272
- * in case the component has a `styleUrl` defined, e.g.
4273
- * ```ts
4274
- * @Component({
4275
- * tag: 'my-component',
4276
- * styleUrl: 'my-component.css'
4277
- * })
4278
- * ```
4279
- */
4280
- style = Cstr.style;
4281
- else if (BUILD.mode && typeof Cstr.style !== "string") {
4282
- /**
4283
- * in case the component has a `styleUrl` object defined, e.g.
4284
- * ```ts
4285
- * @Component({
4286
- * tag: 'my-component',
4287
- * styleUrl: {
4288
- * ios: 'my-component.ios.css',
4289
- * md: 'my-component.md.css'
4290
- * }
4291
- * })
4292
- * ```
4293
- */
4294
- hostRef.$modeName$ = computeMode(elm);
4295
- if (hostRef.$modeName$) style = Cstr.style[hostRef.$modeName$];
4296
- if (BUILD.hydrateServerSide && hostRef.$modeName$) elm.setAttribute("s-mode", hostRef.$modeName$);
4297
- }
4298
- const scopeId = getScopeId(cmpMeta, hostRef.$modeName$);
4299
- if (!styles.has(scopeId) || BUILD.hotModuleReplacement && hmrVersionId) {
4300
- const endRegisterStyles = createTime("registerStyles", cmpMeta.$tagName$);
4301
- if (BUILD.hydrateServerSide && BUILD.shadowDom) {
4302
- if (cmpMeta.$flags$ & CMP_FLAGS.shadowNeedsScopedCss) style = scopeCss(style, scopeId, true);
4303
- else if (needsScopedSSR()) style = expandPartSelectors(style);
4304
- }
4305
- registerStyle(scopeId, style, !!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation));
4306
- endRegisterStyles();
4307
- }
4308
- }
4309
- }
4310
- if (BUILD.signalBacking && cmpMeta.$members$) initializeSignals(elm, hostRef, cmpMeta);
4311
- else if (BUILD.vdomSignals) initializeEffects(elm, hostRef);
4312
- const ancestorComponent = hostRef.$ancestorComponent$;
4313
- const schedule = () => scheduleUpdate(hostRef, true);
4314
- if (BUILD.asyncLoading && ancestorComponent && ancestorComponent["s-rc"]) ancestorComponent["s-rc"].push(schedule);
4315
- else schedule();
4316
- } catch (e) {
4317
- consoleError(e, elm);
4318
- if (BUILD.asyncLoading && hostRef.$onRenderResolve$) {
4319
- hostRef.$onRenderResolve$();
4320
- hostRef.$onRenderResolve$ = void 0;
4321
- }
4322
- if (BUILD.asyncLoading) markFirstConnected(hostRef);
4323
- if (BUILD.asyncLoading && hostRef.$onReadyResolve$ && !(hostRef.$flags$ & HOST_FLAGS.hasFailedLoad)) hostRef.$onReadyResolve$(elm);
4324
- }
4325
- };
4326
- const fireConnectedCallback = (instance, elm) => {
4327
- if (BUILD.lazyLoad) safeCall(instance, "connectedCallback", void 0, elm);
4328
- };
4329
- //#endregion
4330
- //#region src/runtime/connected-callback.ts
4331
- const connectedCallback = (elm) => {
4332
- if ((plt.$flags$ & PLATFORM_FLAGS.isTmpDisconnected) === 0) {
4333
- const hostRef = getHostRef(elm);
4334
- if (!hostRef) return;
4335
- const cmpMeta = hostRef.$cmpMeta$;
4336
- const endConnected = createTime("connectedCallback", cmpMeta.$tagName$);
4337
- if (!(hostRef.$flags$ & HOST_FLAGS.hasConnected)) {
4338
- hostRef.$flags$ |= HOST_FLAGS.hasConnected;
4339
- let hostId;
4340
- if (BUILD.hydrateClientSide) {
4341
- hostId = elm.getAttribute(HYDRATE_ID);
4342
- if (hostId) {
4343
- if (BUILD.shadowDom && cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) {
4344
- const shadowRoot = getShadowRoot(elm);
4345
- const scopeId = BUILD.mode ? addStyle(shadowRoot, cmpMeta, elm.getAttribute("s-mode")) : addStyle(shadowRoot, cmpMeta);
4346
- elm.classList.remove(scopeId + "-h", scopeId + "-s");
4347
- } else if (BUILD.scoped && cmpMeta.$flags$ & CMP_FLAGS.scopedCssEncapsulation) elm["s-sc"] = getScopeId(cmpMeta, BUILD.mode ? elm.getAttribute("s-mode") : void 0);
4348
- initializeClientHydrate(elm, cmpMeta.$tagName$, hostId, hostRef);
4349
- }
4350
- }
4351
- if (BUILD.slotRelocation && !hostId) {
4352
- if (BUILD.hydrateServerSide || (BUILD.slot || BUILD.shadowDom) && cmpMeta.$flags$ & CMP_FLAGS.hasSlotRelocation) setContentReference(elm);
4353
- }
4354
- if (BUILD.asyncLoading) {
4355
- let ancestorComponent = elm;
4356
- while (ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host) if (BUILD.hydrateClientSide && ancestorComponent.nodeType === NODE_TYPE.ElementNode && ancestorComponent.hasAttribute("s-id") && ancestorComponent["s-p"] || ancestorComponent["s-p"]) {
4357
- attachToAncestor(hostRef, hostRef.$ancestorComponent$ = ancestorComponent);
4358
- break;
4359
- }
4360
- }
4361
- if (BUILD.prop && !BUILD.hydrateServerSide && cmpMeta.$members$) Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => {
4362
- if (memberFlags & MEMBER_FLAGS.Prop && Object.prototype.hasOwnProperty.call(elm, memberName)) {
4363
- if (cmpMeta.$flags$ & CMP_FLAGS.hasModernPropertyDecls) {
4364
- const desc = Object.getOwnPropertyDescriptor(elm, memberName);
4365
- if (desc && (desc.get || desc.set)) return;
4366
- }
4367
- const value = elm[memberName];
4368
- delete elm[memberName];
4369
- elm[memberName] = value;
4370
- }
4371
- });
4372
- if (!BUILD.lazyLoad && BUILD.prop && !BUILD.hydrateServerSide) {
4373
- const pendingProps = elm["s-pp"];
4374
- if (pendingProps) {
4375
- delete elm["s-pp"];
4376
- pendingProps.forEach((value, propName) => {
4377
- elm[propName] = value;
4378
- });
4379
- }
4380
- }
4381
- if (BUILD.initializeNextTick) nextTick(() => initializeComponent(elm, hostRef, cmpMeta));
4382
- else initializeComponent(elm, hostRef, cmpMeta);
4383
- } else {
4384
- addHostEventListeners(elm, hostRef, cmpMeta.$listeners$);
4385
- if (hostRef?.$lazyInstance$) fireConnectedCallback(hostRef.$lazyInstance$, elm);
4386
- else if (hostRef.$flags$ & HOST_FLAGS.hasFailedLoad) setTimeout(() => initializeComponent(elm, hostRef, cmpMeta), LAZY_LOAD_RETRY_INTERVAL_MS);
4387
- else if (hostRef?.$onReadyPromise$) hostRef.$onReadyPromise$.then(() => fireConnectedCallback(hostRef.$lazyInstance$, elm));
4388
- }
4389
- endConnected();
4390
- }
4391
- };
4392
- const setContentReference = (elm) => {
4393
- if (!win.document) return;
4394
- const contentRefElm = elm["s-cr"] = win.document.createComment(BUILD.isDebug ? `content-ref (host=${elm.localName})` : "");
4395
- contentRefElm["s-cn"] = true;
4396
- insertBefore(elm, contentRefElm, elm.firstChild);
4397
- };
4398
- //#endregion
4399
- //#region src/runtime/disconnected-callback.ts
4400
- const disconnectInstance = (instance, elm) => {
4401
- if (BUILD.lazyLoad) safeCall(instance, "disconnectedCallback", void 0, elm || instance);
4402
- };
4403
- const disconnectedCallback = async (elm) => {
4404
- if ((plt.$flags$ & PLATFORM_FLAGS.isTmpDisconnected) === 0) {
4405
- const hostRef = getHostRef(elm);
4406
- if (BUILD.hostListener) {
4407
- if (hostRef?.$rmListeners$) {
4408
- hostRef.$rmListeners$.map((rmListener) => rmListener());
4409
- hostRef.$rmListeners$ = void 0;
4410
- }
4411
- }
4412
- if (BUILD.vdomSignals && hostRef?.$signalCleanup$) {
4413
- hostRef.$signalCleanup$();
4414
- hostRef.$signalCleanup$ = void 0;
4415
- }
4416
- if (BUILD.asyncLoading && hostRef && !(hostRef.$flags$ & HOST_FLAGS.hasFiredConnected)) markFirstConnected(hostRef);
4417
- if (!BUILD.lazyLoad) disconnectInstance(elm);
4418
- else if (hostRef?.$lazyInstance$) disconnectInstance(hostRef.$lazyInstance$, elm);
4419
- else if (hostRef?.$onReadyPromise$) hostRef.$onReadyPromise$.then(() => disconnectInstance(hostRef.$lazyInstance$, elm));
4420
- }
4421
- /**
4422
- * Remove the element from the `rootAppliedStyles` WeakMap
4423
- */
4424
- if (rootAppliedStyles.has(elm)) rootAppliedStyles.delete(elm);
4425
- /**
4426
- * Remove the shadow root from the `rootAppliedStyles` WeakMap
4427
- */
4428
- if (elm.shadowRoot && rootAppliedStyles.has(elm.shadowRoot)) rootAppliedStyles.delete(elm.shadowRoot);
4429
- };
4430
- //#endregion
4431
- //#region src/runtime/hmr-component.ts
4432
- /**
4433
- * Kick off hot-module-replacement for a component. In order to replace the
4434
- * component in-place we:
4435
- *
4436
- * 1. get a reference to the {@link d.HostRef} for the element
4437
- * 2. reset the element's runtime flags
4438
- * 3. re-run the initialization logic for the element (via
4439
- * {@link initializeComponent})
4440
- *
4441
- * For standalone (non-lazy) builds, we instead re-import the component module
4442
- * and patch the prototype of the registered constructor in-place, then
4443
- * force a re-render of all existing instances in the DOM.
4444
- *
4445
- * @param hostElement the host element for the component which we want to start
4446
- * doing HMR
4447
- * @param cmpMeta runtime metadata for the component
4448
- * @param hmrVersionId the current HMR version ID
4449
- */
4450
- const hmrStart = (hostElement, cmpMeta, hmrVersionId) => {
4451
- if (BUILD.lazyLoad) {
4452
- const hostRef = getHostRef(hostElement);
4453
- if (!hostRef) return;
4454
- hostRef.$flags$ = HOST_FLAGS.hasConnected;
4455
- if (BUILD.hostListener && hostRef.$rmListeners$) {
4456
- hostRef.$rmListeners$.map((rmListener) => rmListener());
4457
- hostRef.$rmListeners$ = void 0;
4458
- }
4459
- initializeComponent(hostElement, hostRef, cmpMeta, hmrVersionId);
4460
- } else hmrStandalone(hostElement, cmpMeta, hmrVersionId);
4461
- };
4462
- const hmrStandalone = async (hostElement, cmpMeta, hmrVersionId) => {
4463
- const modulePath = hostElement.constructor.__stencil_module__;
4464
- if (!modulePath) {
4465
- console.warn(`[Stencil HMR] No __stencil_module__ on <${cmpMeta.$tagName$}> constructor - was this built with devMode?`);
4466
- return;
4467
- }
4468
- try {
4469
- const newModule = await import(
4470
- /* @vite-ignore */
4471
- `${modulePath}?s-hmr=${hmrVersionId}`
4472
- );
4473
- const NewClass = Object.values(newModule).find((v) => typeof v === "function" && v.is === cmpMeta.$tagName$) ?? newModule.default;
4474
- if (!NewClass) return;
4475
- const ctor = customElements.get(cmpMeta.$tagName$);
4476
- if (ctor) {
4477
- for (const key of Object.getOwnPropertyNames(NewClass.prototype)) {
4478
- if (key === "constructor") continue;
4479
- Object.defineProperty(ctor.prototype, key, Object.getOwnPropertyDescriptor(NewClass.prototype, key));
4480
- }
4481
- const styleDesc = Object.getOwnPropertyDescriptor(NewClass, "style");
4482
- if (styleDesc) {
4483
- Object.defineProperty(ctor, "style", styleDesc);
4484
- const newStyle = NewClass.style;
4485
- if (newStyle) {
4486
- const scopeId = getScopeId(cmpMeta);
4487
- const isShadow = !!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation);
4488
- console.log("[stencil-hmr] registerStyle", {
4489
- tag: cmpMeta.$tagName$,
4490
- scopeId,
4491
- isShadow,
4492
- cssLen: newStyle.length
4493
- });
4494
- registerStyle(scopeId, newStyle, isShadow);
4495
- }
4496
- }
4497
- }
4498
- const isShadow = !!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation);
4499
- document.querySelectorAll(cmpMeta.$tagName$).forEach((el) => {
4500
- const hostRef = getHostRef(el);
4501
- if (BUILD.hostListener && hostRef?.$rmListeners$) {
4502
- hostRef.$rmListeners$.map((rmListener) => rmListener());
4503
- hostRef.$rmListeners$ = void 0;
4504
- addHostEventListeners(el, hostRef, cmpMeta.$listeners$);
4505
- }
4506
- if (!isShadow && hostRef) {
4507
- console.log("[stencil-hmr] calling attachStyles for", cmpMeta.$tagName$);
4508
- attachStyles(hostRef);
4509
- }
4510
- forceUpdate(el);
4511
- });
4512
- } catch (e) {
4513
- console.error(`[Stencil HMR] Failed to reload <${cmpMeta.$tagName$}>`, e);
4514
- }
4515
- };
4516
- //#endregion
4517
- //#region src/runtime/bootstrap-loader.ts
4518
- const bootstrapLazy = (lazyBundles, options = {}) => {
4519
- if (BUILD.profile && performance.mark) performance.mark("st:app:start");
4520
- installDevTools();
4521
- if (!win.document) {
4522
- console.warn("Stencil: No document found. Skipping");
4523
- return;
4524
- }
4525
- const endBootstrap = createTime("bootstrapLazy");
4526
- const cmpTags = [];
4527
- const exclude = options.exclude || [];
4528
- const _reg = options.registry ?? getRegistry();
4529
- const head = win.document.head;
4530
- const metaCharset = /*@__PURE__*/ head.querySelector("meta[charset]");
4531
- const dataStyles = /*@__PURE__*/ win.document.createElement("style");
4532
- const deferredConnectedCallbacks = [];
4533
- let appLoadFallback;
4534
- let isBootstrapping = true;
4535
- Object.assign(plt, options);
4536
- if (BUILD.asyncQueue && options.syncQueue) plt.$flags$ |= PLATFORM_FLAGS.queueSync;
4537
- if (BUILD.hydrateClientSide) plt.$flags$ |= PLATFORM_FLAGS.appLoaded;
4538
- if (BUILD.hydrateClientSide && BUILD.shadowDom) hydrateScopedToShadow();
4539
- lazyBundles.map((lazyBundle) => {
4540
- lazyBundle[1].map((compactMeta) => {
4541
- const cmpMeta = {
4542
- $flags$: compactMeta[0],
4543
- $tagName$: compactMeta[1],
4544
- $members$: compactMeta[2],
4545
- $listeners$: compactMeta[3]
4546
- };
4547
- if (BUILD.member) cmpMeta.$members$ = compactMeta[2];
4548
- if (BUILD.hostListener) cmpMeta.$listeners$ = compactMeta[3];
4549
- if (BUILD.reflect) cmpMeta.$attrsToReflect$ = [];
4550
- if (BUILD.propChangeCallback) {
4551
- cmpMeta.$watchers$ = normalizeWatchers(compactMeta[4]);
4552
- cmpMeta.$serializers$ = compactMeta[5] ?? {};
4553
- cmpMeta.$deserializers$ = compactMeta[6] ?? {};
4554
- }
4555
- const tagName = transformTag(cmpMeta.$tagName$);
4556
- const HostElement = class extends HTMLElement {
4557
- ["s-p"];
4558
- ["s-rc"];
4559
- hreListeners = false;
4560
- constructor(self) {
4561
- super(self);
4562
- self = this;
4563
- registerHost(self, cmpMeta);
4564
- if (BUILD.shadowDom && cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation && !(cmpMeta.$flags$ & CMP_FLAGS.shadowNeedsScopedCss)) {
4565
- if (!self.shadowRoot) createShadowRoot.call(self, cmpMeta);
4566
- else if (BUILD.isDev && self.shadowRoot.mode !== "open") throw new Error(`Unable to re-use existing shadow root for ${cmpMeta.$tagName$}! Mode is set to ${self.shadowRoot.mode} but DSD shadow roots must use open mode.`);
4567
- }
4568
- }
4569
- connectedCallback() {
4570
- const hostRef = getHostRef(this);
4571
- if (!hostRef) return;
4572
- /**
4573
- * The `connectedCallback` lifecycle event can potentially be fired multiple times
4574
- * if the element is removed from the DOM and re-inserted. This is not a common use case,
4575
- * but it can happen in some scenarios. To prevent registering the same event listeners
4576
- * multiple times, we will only register them once.
4577
- */
4578
- if (!this.hreListeners) {
4579
- this.hreListeners = true;
4580
- addHostEventListeners(this, hostRef, cmpMeta.$listeners$);
4581
- }
4582
- if (appLoadFallback) {
4583
- clearTimeout(appLoadFallback);
4584
- appLoadFallback = null;
4585
- }
4586
- if (isBootstrapping) deferredConnectedCallbacks.push(this);
4587
- else plt.jmp(() => connectedCallback(this));
4588
- }
4589
- disconnectedCallback() {
4590
- plt.jmp(() => disconnectedCallback(this));
4591
- /**
4592
- * Clear up references within the `$vnode$` object to the DOM
4593
- * node that was removed. This is necessary to ensure that these
4594
- * references used as keys in the `hostRef` object can be properly
4595
- * garbage collected.
4596
- *
4597
- * Also remove the reference from `deferredConnectedCallbacks` array
4598
- * otherwise removed instances won't get garbage collected.
4599
- *
4600
- * Use `nextTick` (microtask) rather than `plt.raf` since
4601
- * `requestAnimationFrame` callbacks do not fire while `document.hidden`
4602
- */
4603
- nextTick(() => {
4604
- const hostRef = getHostRef(this);
4605
- if (!hostRef) return;
4606
- const i = deferredConnectedCallbacks.findIndex((host) => host === this);
4607
- if (i > -1) deferredConnectedCallbacks.splice(i, 1);
4608
- if (hostRef?.$vnode$?.$elm$ instanceof Node && !hostRef.$vnode$.$elm$.isConnected) delete hostRef.$vnode$.$elm$;
4609
- });
4610
- }
4611
- componentOnReady() {
4612
- return getHostRef(this)?.$onReadyPromise$;
4613
- }
4614
- };
4615
- if (!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) && (BUILD.slotCloneNode || BUILD.patchClone && cmpMeta.$flags$ & CMP_FLAGS.patchClone)) patchCloneNode(HostElement.prototype);
4616
- if (!(cmpMeta.$flags$ & CMP_FLAGS.shadowDomEncapsulation) && cmpMeta.$flags$ & CMP_FLAGS.hasSlot) {
4617
- if (BUILD.lightDomPatches || BUILD.patchAll && cmpMeta.$flags$ & CMP_FLAGS.patchAll) applyLightDomPatches(HostElement.prototype);
4618
- else {
4619
- if (BUILD.slotChildNodes || BUILD.patchChildren && cmpMeta.$flags$ & CMP_FLAGS.patchChildren) patchChildSlotNodes(HostElement.prototype);
4620
- if (BUILD.slotDomMutations || BUILD.patchInsert && cmpMeta.$flags$ & CMP_FLAGS.patchInsert) {
4621
- patchSlotAppendChild(HostElement.prototype);
4622
- patchSlotAppend(HostElement.prototype);
4623
- patchSlotPrepend(HostElement.prototype);
4624
- patchSlotInsertAdjacentHTML(HostElement.prototype);
4625
- patchInsertBefore(HostElement.prototype);
4626
- patchSlotRemoveChild(HostElement.prototype);
4627
- }
4628
- if (BUILD.slotTextContent) patchTextContent(HostElement.prototype);
4629
- }
4630
- }
4631
- if (BUILD.formAssociated && cmpMeta.$flags$ & CMP_FLAGS.formAssociated) HostElement.formAssociated = true;
4632
- if (BUILD.hotModuleReplacement) HostElement.prototype["s-hmr"] = function(hmrVersionId) {
4633
- hmrStart(this, cmpMeta, hmrVersionId);
4634
- };
4635
- cmpMeta.$lazyBundleId$ = lazyBundle[0];
4636
- if (!exclude.includes(tagName) && !_reg.get(tagName)) {
4637
- cmpTags.push(tagName);
4638
- const proxied = proxyComponent(HostElement, cmpMeta, PROXY_FLAGS.isElementConstructor);
4639
- proxied._registry = _reg;
4640
- _reg.define(tagName, proxied);
4641
- }
4642
- });
4643
- });
4644
- if (cmpTags.length > 0) {
4645
- if (BUILD.invisiblePrehydration && !BUILD.staticHydrationStyles && (BUILD.hydratedClass || BUILD.hydratedAttribute)) dataStyles.textContent += cmpTags.sort() + HYDRATED_CSS;
4646
- if (dataStyles.innerHTML.length) {
4647
- dataStyles.setAttribute("data-styles", "");
4648
- const nonce = plt.$nonce$ ?? queryNonceMetaTagContent(win.document);
4649
- if (nonce != null) dataStyles.setAttribute("nonce", nonce);
4650
- head.insertBefore(dataStyles, metaCharset ? metaCharset.nextSibling : head.firstChild);
4651
- }
4652
- }
4653
- isBootstrapping = false;
4654
- if (deferredConnectedCallbacks.length) deferredConnectedCallbacks.map((host) => host.connectedCallback());
4655
- else if (BUILD.profile) plt.jmp(() => appLoadFallback = setTimeout(appDidLoad, 30, "timeout"));
4656
- else plt.jmp(() => appLoadFallback = setTimeout(appDidLoad, 30));
4657
- endBootstrap();
4658
- };
4659
- //#endregion
4660
- //#region src/runtime/host-listener.ts
4661
- const addHostEventListeners = (elm, hostRef, listeners) => {
4662
- if (BUILD.hostListener && listeners && win.document) listeners.map(([flags, name, method]) => {
4663
- const target = BUILD.hostListenerTarget ? getHostListenerTarget(win.document, elm, flags) : elm;
4664
- const handler = hostListenerProxy(hostRef, method);
4665
- const opts = hostListenerOpts(flags);
4666
- plt.ael(target, name, handler, opts);
4667
- (hostRef.$rmListeners$ = hostRef.$rmListeners$ || []).push(() => plt.rel(target, name, handler, opts));
4668
- });
4669
- };
4670
- const hostListenerProxy = (hostRef, methodName) => (ev) => {
4671
- try {
4672
- if (BUILD.lazyLoad) {
4673
- if (hostRef.$flags$ & HOST_FLAGS.isListenReady) hostRef.$lazyInstance$?.[methodName](ev);
4674
- else (hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]);
4675
- } else hostRef.$hostElement$[methodName](ev);
4676
- } catch (e) {
4677
- consoleError(e, hostRef.$hostElement$);
4678
- }
4679
- };
4680
- const getHostListenerTarget = (doc, elm, flags) => {
4681
- if (BUILD.hostListenerTargetDocument && flags & LISTENER_FLAGS.TargetDocument) return doc;
4682
- if (BUILD.hostListenerTargetWindow && flags & LISTENER_FLAGS.TargetWindow) return win;
4683
- if (BUILD.hostListenerTargetBody && flags & LISTENER_FLAGS.TargetBody) return doc.body;
4684
- return elm;
4685
- };
4686
- const hostListenerOpts = (flags) => supportsListenerOptions ? {
4687
- passive: (flags & LISTENER_FLAGS.Passive) !== 0,
4688
- capture: (flags & LISTENER_FLAGS.Capture) !== 0
4689
- } : (flags & LISTENER_FLAGS.Capture) !== 0;
4690
- //#endregion
4691
- //#region src/runtime/mixin.ts
4692
- const baseClass = BUILD.lazyLoad ? class {} : globalThis.HTMLElement || class {};
4693
- function Mixin(...mixins) {
4694
- return mixins.reduceRight((acc, mixin) => mixin(acc), baseClass);
4695
- }
4696
- //#endregion
4697
- //#region src/runtime/reactive-controller.ts
4698
- const ReactiveControllerHost = (Base) => class ReactiveControllerHostMixin extends Base {
4699
- controllers = /* @__PURE__ */ new Set();
4700
- #connected = false;
4701
- #updateCompleteResolvers = [];
4702
- addController(controller) {
4703
- this.controllers.add(controller);
4704
- if (this.#connected) controller.hostConnected?.();
4705
- }
4706
- removeController(controller) {
4707
- this.controllers.delete(controller);
4708
- }
4709
- requestUpdate() {
4710
- forceUpdate(this);
4711
- }
4712
- get updateComplete() {
4713
- return new Promise((resolve) => this.#updateCompleteResolvers.push(resolve));
4714
- }
4715
- connectedCallback() {
4716
- super.connectedCallback?.();
4717
- this.#connected = true;
4718
- const el = getElement(this);
4719
- if (el && el !== this) {
4720
- el.addController = (controller) => this.addController(controller);
4721
- el.removeController = (controller) => this.removeController(controller);
4722
- el.requestUpdate = () => this.requestUpdate();
4723
- Object.defineProperty(el, "updateComplete", {
4724
- configurable: true,
4725
- get: () => this.updateComplete
4726
- });
4727
- }
4728
- this.controllers.forEach((c) => c.hostConnected?.());
4729
- }
4730
- disconnectedCallback() {
4731
- super.disconnectedCallback?.();
4732
- this.#connected = false;
4733
- this.controllers.forEach((c) => c.hostDisconnected?.());
4734
- }
4735
- async componentWillLoad() {
4736
- await super.componentWillLoad?.();
4737
- await Promise.all([...this.controllers].map((c) => c.hostWillLoad?.()));
4738
- }
4739
- componentDidLoad() {
4740
- super.componentDidLoad?.();
4741
- this.controllers.forEach((c) => c.hostDidLoad?.());
4742
- }
4743
- async componentWillRender() {
4744
- await super.componentWillRender?.();
4745
- await Promise.all([...this.controllers].map((c) => c.hostWillRender?.()));
4746
- }
4747
- componentDidRender() {
4748
- super.componentDidRender?.();
4749
- this.controllers.forEach((c) => c.hostDidRender?.());
4750
- const resolvers = this.#updateCompleteResolvers;
4751
- this.#updateCompleteResolvers = [];
4752
- resolvers.forEach((resolve) => resolve(true));
4753
- }
4754
- async componentWillUpdate() {
4755
- await super.componentWillUpdate?.();
4756
- await Promise.all([...this.controllers].map((c) => c.hostWillUpdate?.()));
4757
- }
4758
- componentDidUpdate() {
4759
- super.componentDidUpdate?.();
4760
- this.controllers.forEach((c) => c.hostDidUpdate?.());
4761
- }
4762
- };
4763
- //#endregion
4764
- //#region src/runtime/render.ts
4765
- /**
4766
- * A WeakMap to persist HostRef objects across multiple render() calls to the
4767
- * same container. This enables VNode diffing on re-renders - without it, each
4768
- * call creates a fresh HostRef with no previous VNode, causing renderVdom to
4769
- * replace the entire DOM subtree instead of patching only what changed.
4770
- */
4771
- const hostRefCache = /* @__PURE__ */ new WeakMap();
4772
- /**
4773
- * Method to render a virtual DOM tree to a container element.
4774
- *
4775
- * Supports efficient re-renders: calling `render()` again on the same container
4776
- * will diff the new VNode tree against the previous one and only update what changed,
4777
- * preserving existing DOM elements and their state.
4778
- *
4779
- * @example
4780
- * ```tsx
4781
- * import { render } from '@stencil/core';
4782
- *
4783
- * const vnode = (
4784
- * <div>
4785
- * <h1>Hello, world!</h1>
4786
- * </div>
4787
- * );
4788
- * render(vnode, document.body);
4789
- * ```
4790
- *
4791
- * @param vnode - The virtual DOM tree to render
4792
- * @param container - The container element to render the virtual DOM tree to
4793
- */
4794
- function render(vnode, container) {
4795
- let ref = hostRefCache.get(container);
4796
- if (!ref) {
4797
- ref = {
4798
- $flags$: 0,
4799
- $cmpMeta$: {
4800
- $flags$: 0,
4801
- $tagName$: container.tagName
4802
- },
4803
- $hostElement$: container
4804
- };
4805
- hostRefCache.set(container, ref);
4806
- }
4807
- renderVdom(ref, vnode);
4808
- }
4809
- //#endregion
4810
- //#region src/runtime/tag-transform.ts
4811
- let tagTransformer = void 0;
4812
- /**
4813
- * Transforms a tag name using the current tag transformer
4814
- * @param tag - the tag to transform e.g. `my-tag`
4815
- * @returns the transformed tag e.g. `new-my-tag`
4816
- */
4817
- function transformTag(tag) {
4818
- if (!tagTransformer) return tag;
4819
- return tagTransformer(tag);
4820
- }
4821
- /**
4822
- * Sets the tag transformer to be used when rendering custom elements
4823
- * @param transformer the transformer function to use. Must return a string
4824
- */
4825
- function setTagTransformer(transformer) {
4826
- tagTransformer = transformer;
4827
- }
4828
- //#endregion
4829
- //#region src/runtime/vdom/jsx-runtime.ts
4830
- function jsx(type, props, key) {
4831
- const { children, ...rest } = props ?? {};
4832
- if (key !== void 0 && !("key" in rest)) rest.key = key;
4833
- const attrs = hasKeys(rest) ? rest : null;
4834
- if (children !== void 0) return Array.isArray(children) ? h(type, attrs, ...children) : h(type, attrs, children);
4835
- return h(type, attrs);
4836
- }
4837
- /**
4838
- * @alias
4839
- */
4840
- const jsxs = jsx;
4841
- /**
4842
- * @alias
4843
- */
4844
- const jsxDEV = jsx;
4845
- function hasKeys(obj) {
4846
- for (const _ in obj) return true;
4847
- return false;
4848
- }
4849
- //#endregion
4850
- export { HYDRATE_ID as A, setAssetPath as C, DEFAULT_DOC_DATA as D, setPlatformHelpers as E, reWireGetterSetter as F, Build as I, BUILD as L, STENCIL_DOC_DATA as M, setErrorHandler as N, HYDRATED_CSS as O, getHostRef as P, Env as R, getAssetPath as S, writeTask as T, insertBefore as _, transformTag as a, getElement as b, Mixin as c, setMode as d, scopeCss as f, getRenderingRef as g, forceUpdate as h, setTagTransformer as i, NODE_TYPE as j, HYDRATE_CHILD_ID as k, bootstrapLazy as l, h as m, jsxDEV as n, render as o, Host as p, jsxs as r, ReactiveControllerHost as s, jsx as t, getMode as u, renderVdom as v, readTask as w, getShadowRoot as x, createEvent as y };