thunderous 2.3.12 → 2.3.13

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.
package/dist/index.js CHANGED
@@ -1,1007 +1,5 @@
1
- // src/constants.ts
2
- var DEFAULT_RENDER_OPTIONS = {
3
- formAssociated: false,
4
- observedAttributes: [],
5
- attributesAsProperties: [],
6
- attachShadow: true,
7
- shadowRootOptions: {
8
- mode: "closed",
9
- delegatesFocus: false,
10
- clonable: false,
11
- serializable: false,
12
- slotAssignment: "named"
13
- }
14
- };
15
-
16
- // src/signals.ts
17
- var subscriber = null;
18
- var createSignal = (initVal, options) => {
19
- const subscribers = /* @__PURE__ */ new Set();
20
- let value = initVal;
21
- const getter = (getterOptions) => {
22
- if (subscriber !== null) {
23
- subscribers.add(subscriber);
24
- }
25
- if (options?.debugMode === true || getterOptions?.debugMode === true) {
26
- let label = "anonymous signal";
27
- if (options?.label !== void 0) {
28
- label = `(${options.label})`;
29
- if (getterOptions?.label !== void 0) {
30
- label += ` ${getterOptions.label}`;
31
- }
32
- } else if (getterOptions?.label !== void 0) {
33
- label = getterOptions.label;
34
- }
35
- console.log("Signal retrieved:", { value, subscribers, label });
36
- }
37
- return value;
38
- };
39
- getter.getter = true;
40
- let stackLength = 0;
41
- const setter = (newValue, setterOptions) => {
42
- stackLength++;
43
- queueMicrotask(() => stackLength--);
44
- if (stackLength > 1e3) {
45
- console.error(new Error("Signal setter stack overflow detected. Possible infinite loop. Bailing out."));
46
- stackLength = 0;
47
- return;
48
- }
49
- const isObject = typeof newValue === "object" && newValue !== null;
50
- if (!isObject && value === newValue) return;
51
- if (isObject && typeof value === "object" && value !== null) {
52
- if (JSON.stringify(value) === JSON.stringify(newValue)) return;
53
- }
54
- const oldValue = value;
55
- value = newValue;
56
- for (const fn of subscribers) {
57
- try {
58
- fn();
59
- } catch (error) {
60
- console.error("Error in subscriber:", { error, oldValue, newValue, fn });
61
- }
62
- }
63
- if (options?.debugMode === true || setterOptions?.debugMode === true) {
64
- let label = "anonymous signal";
65
- if (options?.label !== void 0) {
66
- label = `(${options.label})`;
67
- if (setterOptions?.label !== void 0) {
68
- label += ` ${setterOptions.label}`;
69
- }
70
- } else if (setterOptions?.label !== void 0) {
71
- label = setterOptions.label;
72
- }
73
- console.log("Signal set:", { oldValue, newValue, subscribers, label });
74
- }
75
- };
76
- return [getter, setter];
77
- };
78
- var derived = (fn, options) => {
79
- const [getter, setter] = createSignal(void 0, options);
80
- createEffect(() => {
81
- try {
82
- setter(fn());
83
- } catch (error) {
84
- console.error("Error in derived signal:", { error, fn });
85
- }
86
- });
87
- return getter;
88
- };
89
- var createEffect = (fn) => {
90
- subscriber = fn;
91
- try {
92
- fn();
93
- } catch (error) {
94
- console.error("Error in effect:", { error, fn });
95
- }
96
- subscriber = null;
97
- };
98
-
99
- // src/utilities.ts
100
- var NOOP = () => void 0;
101
- var queryComment = (node, comment) => {
102
- for (const child of node.childNodes) {
103
- if (child.nodeType === Node.COMMENT_NODE && child.nodeValue === comment) {
104
- return child;
105
- }
106
- }
107
- return null;
108
- };
109
-
110
- // src/server-side.ts
111
- var isServer = typeof window === "undefined";
112
- var serverDefineFns = /* @__PURE__ */ new Set();
113
- var onServerDefine = (fn) => {
114
- serverDefineFns.add(fn);
115
- };
116
- var serverDefine = ({
117
- tagName,
118
- serverRender,
119
- options,
120
- elementResult,
121
- scopedRegistry,
122
- parentRegistry
123
- }) => {
124
- if (parentRegistry !== void 0) {
125
- if (parentRegistry.getTagName(elementResult) !== tagName.toUpperCase()) {
126
- parentRegistry.define(tagName, elementResult);
127
- }
128
- parentRegistry.__serverRenderOpts.set(tagName, { serverRender, ...options });
129
- if (parentRegistry.scoped) return;
130
- }
131
- for (const fn of serverDefineFns) {
132
- let result = serverRender(getServerRenderArgs(tagName));
133
- result = wrapTemplate({
134
- tagName,
135
- serverRender,
136
- options
137
- });
138
- if (scopedRegistry !== void 0) {
139
- for (const [scopedTagName, scopedRenderOptions] of scopedRegistry.__serverRenderOpts) {
140
- const { serverRender: serverRender2, ...scopedOptions } = scopedRenderOptions;
141
- let template = serverRender2(getServerRenderArgs(scopedTagName, scopedRegistry));
142
- template = wrapTemplate({
143
- tagName: scopedTagName,
144
- serverRender: serverRender2,
145
- options: scopedOptions
146
- });
147
- result = insertTemplates(scopedTagName, template, result);
148
- }
149
- }
150
- fn(tagName, result);
151
- }
152
- };
153
- var serverCss = /* @__PURE__ */ new Map();
154
- var getServerRenderArgs = (tagName, registry) => ({
155
- get elementRef() {
156
- return new Proxy({}, {
157
- get: () => {
158
- const error = new Error("The `elementRef` property is not available on the server.");
159
- console.error(error);
160
- throw error;
161
- }
162
- });
163
- },
164
- get root() {
165
- return new Proxy({}, {
166
- get: () => {
167
- const error = new Error("The `root` property is not available on the server.");
168
- console.error(error);
169
- throw error;
170
- }
171
- });
172
- },
173
- get internals() {
174
- return new Proxy({}, {
175
- get: () => {
176
- const error = new Error("The `internals` property is not available on the server.");
177
- console.error(error);
178
- throw error;
179
- }
180
- });
181
- },
182
- attributeChangedCallback: NOOP,
183
- connectedCallback: NOOP,
184
- disconnectedCallback: NOOP,
185
- adoptedCallback: NOOP,
186
- formDisabledCallback: NOOP,
187
- formResetCallback: NOOP,
188
- formStateRestoreCallback: NOOP,
189
- formAssociatedCallback: NOOP,
190
- clientOnlyCallback: NOOP,
191
- customCallback: () => "",
192
- getter: (fn) => {
193
- const _fn = () => fn();
194
- _fn.getter = true;
195
- return _fn;
196
- },
197
- attrSignals: new Proxy({}, { get: (_, attr) => createSignal(`{{attr:${String(attr)}}}`) }),
198
- propSignals: new Proxy({}, { get: () => createSignal(null) }),
199
- refs: {},
200
- // @ts-expect-error // this will be a string for SSR, but this is true for internal cases only.
201
- // The end user will see the public type, which is either a CSSStyleSheet or HTMLStyleElement.
202
- adoptStyleSheet: (cssStr) => {
203
- const _serverCss = registry !== void 0 ? registry.__serverCss : serverCss;
204
- const cssArr = _serverCss.get(tagName) ?? [];
205
- cssArr.push(cssStr);
206
- _serverCss.set(tagName, cssArr);
207
- }
208
- });
209
- var wrapTemplate = ({ tagName, serverRender, options }) => {
210
- const { registry } = options.shadowRootOptions;
211
- const scopedRegistry = registry !== void 0 && "scoped" in registry ? registry : void 0;
212
- const initialRenderString = serverRender(getServerRenderArgs(tagName, scopedRegistry));
213
- const _serverCss = scopedRegistry?.__serverCss ?? serverCss;
214
- const cssRenderString = (_serverCss.get(tagName) ?? []).map((cssStr) => `<style>${cssStr}</style>`).join("");
215
- const finalScopedRenderString = options.attachShadow ? (
216
- /* html */
217
- `
218
- <template
219
- shadowrootmode="${options.shadowRootOptions.mode}"
220
- shadowrootdelegatesfocus="${options.shadowRootOptions.delegatesFocus}"
221
- shadowrootclonable="${options.shadowRootOptions.clonable}"
222
- shadowrootserializable="${options.shadowRootOptions.serializable}"
223
- >
224
- ${cssRenderString + initialRenderString}
225
- </template>
226
- `
227
- ) : cssRenderString + initialRenderString;
228
- return finalScopedRenderString;
229
- };
230
- var insertTemplates = (tagName, template, inputString) => {
231
- return inputString.replace(new RegExp(`(<s*${tagName}([^>]*)>)`, "gm"), ($1, _, $3) => {
232
- const attrs = $3.split(/(?<=")\s+/).filter((attr) => attr.trim() !== "").map((attr) => {
233
- const [_key, _value] = attr.split("=");
234
- const key = _key.trim();
235
- const value = _value?.replace(/"/g, "") ?? "";
236
- return [key, value];
237
- });
238
- let scopedResult = template;
239
- for (const [key, value] of attrs) {
240
- scopedResult = scopedResult.replace(new RegExp(`{{attr:${key}}}`, "gm"), value);
241
- }
242
- return $1 + scopedResult;
243
- });
244
- };
245
- var clientOnlyCallback = (fn) => {
246
- if (!isServer) return fn();
247
- };
248
-
249
- // src/render.ts
250
- var CALLBACK_BINDING_REGEX = /(\{\{callback:.+\}\})/;
251
- var LEGACY_CALLBACK_BINDING_REGEX = /(this.getRootNode\(\).host.__customCallbackFns.get\('.+'\)\(event\))/;
252
- var SIGNAL_BINDING_REGEX = /(\{\{signal:.+\}\})/;
253
- var FRAGMENT_ATTRIBUTE = "___thunderous-fragment";
254
- var renderState = {
255
- currentShadowRoot: null,
256
- signalMap: /* @__PURE__ */ new Map(),
257
- callbackMap: /* @__PURE__ */ new Map(),
258
- fragmentMap: /* @__PURE__ */ new Map(),
259
- registry: typeof customElements !== "undefined" ? customElements : {}
260
- };
261
- var logPropertyWarning = (propName, element) => {
262
- console.warn(
263
- `Property "${propName}" does not exist on element:`,
264
- element,
265
- "\n\nThunderous will attempt to set the property anyway, but this may result in unexpected behavior. Please make sure the property exists on the element prior to setting it."
266
- );
267
- };
268
- var arrayToDocumentFragment = (array, parent, uniqueKey) => {
269
- const documentFragment = new DocumentFragment();
270
- let count = 0;
271
- const keys = /* @__PURE__ */ new Set();
272
- for (const item of array) {
273
- const node = createNewNode(item, parent, uniqueKey);
274
- if (node instanceof DocumentFragment) {
275
- const child = node.firstElementChild;
276
- if (node.children.length > 1) {
277
- console.error(
278
- "When rendering arrays, fragments must contain only one top-level element at a time. Error occured in:",
279
- parent
280
- );
281
- }
282
- if (child === null) continue;
283
- let key = child.getAttribute("key");
284
- if (key === null) {
285
- console.warn(
286
- "When rendering arrays, a `key` attribute should be provided on each child element. An index was automatically applied, but this could result in unexpected behavior:",
287
- child
288
- );
289
- key = String(count);
290
- child.setAttribute("key", key);
291
- }
292
- if (keys.has(key)) {
293
- console.warn(
294
- `When rendering arrays, each child should have a unique \`key\` attribute. Duplicate key "${key}" found on:`,
295
- child
296
- );
297
- }
298
- keys.add(key);
299
- count++;
300
- }
301
- documentFragment.append(node);
302
- }
303
- const comment = document.createComment(uniqueKey);
304
- documentFragment.append(comment);
305
- return documentFragment;
306
- };
307
- var createNewNode = (value, parent, uniqueKey) => {
308
- if (typeof value === "string") return new Text(value);
309
- if (Array.isArray(value)) return arrayToDocumentFragment(value, parent, uniqueKey);
310
- if (value instanceof DocumentFragment) return value;
311
- return new Text("");
312
- };
313
- var processValue = (value) => {
314
- if (!isServer && value instanceof DocumentFragment) {
315
- const uniqueKey = crypto.randomUUID();
316
- renderState.fragmentMap.set(uniqueKey, value);
317
- return `<div ${FRAGMENT_ATTRIBUTE}="${uniqueKey}"></div>`;
318
- }
319
- if (typeof value === "function" && "getter" in value && value.getter === true) {
320
- const getter = value;
321
- const uniqueKey = crypto.randomUUID();
322
- renderState.signalMap.set(uniqueKey, getter);
323
- let result = getter();
324
- if (Array.isArray(result)) {
325
- result = result.map((item) => processValue(item)).join("");
326
- }
327
- return isServer ? String(result) : `{{signal:${uniqueKey}}}`;
328
- }
329
- if (typeof value === "function") {
330
- const uniqueKey = crypto.randomUUID();
331
- renderState.callbackMap.set(uniqueKey, value);
332
- return isServer ? String(value()) : `{{callback:${uniqueKey}}}`;
333
- }
334
- return String(value);
335
- };
336
- var evaluateBindings = (element, fragment) => {
337
- for (const child of element.childNodes) {
338
- if (child instanceof Text && SIGNAL_BINDING_REGEX.test(child.data)) {
339
- const textList = child.data.split(SIGNAL_BINDING_REGEX);
340
- const sibling = child.nextSibling;
341
- textList.forEach((text, i) => {
342
- const uniqueKey = text.replace(/\{\{signal:(.+)\}\}/, "$1");
343
- const signal = uniqueKey !== text ? renderState.signalMap.get(uniqueKey) : void 0;
344
- const newValue = signal !== void 0 ? signal() : text;
345
- const newNode = createNewNode(newValue, element, uniqueKey);
346
- if (i === 0) {
347
- child.replaceWith(newNode);
348
- } else {
349
- element.insertBefore(newNode, sibling);
350
- }
351
- if (signal !== void 0 && newNode instanceof Text) {
352
- createEffect(() => {
353
- newNode.data = signal();
354
- });
355
- } else if (signal !== void 0 && newNode instanceof DocumentFragment) {
356
- let init = false;
357
- createEffect(() => {
358
- const result = signal();
359
- const nextNode = createNewNode(result, element, uniqueKey);
360
- if (nextNode instanceof Text) {
361
- const error = new TypeError(
362
- "Signal mismatch: expected DocumentFragment or Array<DocumentFragment>, but got Text"
363
- );
364
- console.error(error);
365
- throw error;
366
- }
367
- for (const child2 of element.children) {
368
- const key = child2.getAttribute("key");
369
- if (key === null) continue;
370
- const matchingNode = nextNode.querySelector(`[key="${key}"]`);
371
- if (init && matchingNode === null) {
372
- child2.remove();
373
- }
374
- }
375
- let anchor = queryComment(element, uniqueKey);
376
- for (const child2 of nextNode.children) {
377
- const key = child2.getAttribute("key");
378
- const matchingNode = element.querySelector(`[key="${key}"]`);
379
- if (matchingNode === null) continue;
380
- matchingNode.__customCallbackFns = child2.__customCallbackFns;
381
- for (const attr of child2.attributes) {
382
- matchingNode.setAttribute(attr.name, attr.value);
383
- }
384
- matchingNode.replaceChildren(...child2.childNodes);
385
- anchor = matchingNode.nextSibling;
386
- child2.replaceWith(matchingNode);
387
- }
388
- const nextAnchor = queryComment(nextNode, uniqueKey);
389
- nextAnchor?.remove();
390
- element.insertBefore(nextNode, anchor);
391
- if (!init) init = true;
392
- });
393
- }
394
- });
395
- }
396
- if (child instanceof Element && child.hasAttribute(FRAGMENT_ATTRIBUTE)) {
397
- const uniqueKey = child.getAttribute(FRAGMENT_ATTRIBUTE);
398
- const childFragment = renderState.fragmentMap.get(uniqueKey);
399
- if (childFragment !== void 0) {
400
- child.replaceWith(childFragment);
401
- }
402
- } else if (child instanceof Element) {
403
- for (const attr of [...child.attributes]) {
404
- const attrName = attr.name;
405
- if (SIGNAL_BINDING_REGEX.test(attr.value)) {
406
- const textList = attr.value.split(SIGNAL_BINDING_REGEX);
407
- let prevText = attr.value;
408
- createEffect(() => {
409
- let newText = "";
410
- let hasNull = false;
411
- let signal;
412
- for (const text of textList) {
413
- const uniqueKey = text.replace(/\{\{signal:(.+)\}\}/, "$1");
414
- if (signal === void 0) {
415
- signal = uniqueKey !== text ? renderState.signalMap.get(uniqueKey) : void 0;
416
- const value = signal !== void 0 ? signal() : text;
417
- if (value === null) hasNull = true;
418
- newText += String(value);
419
- } else {
420
- newText += text;
421
- }
422
- }
423
- if (hasNull && newText === "null" || attrName.startsWith("prop:")) {
424
- if (child.hasAttribute(attrName)) child.removeAttribute(attrName);
425
- } else {
426
- if (newText !== prevText) child.setAttribute(attrName, newText);
427
- }
428
- if (attrName.startsWith("prop:")) {
429
- if (child.hasAttribute(attrName)) child.removeAttribute(attrName);
430
- const propName = attrName.replace("prop:", "");
431
- const newValue = hasNull && newText === "null" ? null : newText;
432
- if (!(propName in child)) logPropertyWarning(propName, child);
433
- child[propName] = signal !== void 0 ? signal() : newValue;
434
- }
435
- prevText = newText;
436
- });
437
- } else if (LEGACY_CALLBACK_BINDING_REGEX.test(attr.value)) {
438
- const getRootNode = child.getRootNode.bind(child);
439
- child.getRootNode = () => {
440
- const rootNode = getRootNode();
441
- return rootNode instanceof ShadowRoot ? rootNode : fragment;
442
- };
443
- } else if (CALLBACK_BINDING_REGEX.test(attr.value)) {
444
- const textList = attr.value.split(CALLBACK_BINDING_REGEX);
445
- createEffect(() => {
446
- child.__customCallbackFns = child.__customCallbackFns ?? /* @__PURE__ */ new Map();
447
- let uniqueKey = "";
448
- for (const text of textList) {
449
- const _uniqueKey = text.replace(/\{\{callback:(.+)\}\}/, "$1");
450
- if (_uniqueKey !== text) uniqueKey = _uniqueKey;
451
- const callback = uniqueKey !== text ? renderState.callbackMap.get(uniqueKey) : void 0;
452
- if (callback !== void 0) {
453
- child.__customCallbackFns.set(uniqueKey, callback);
454
- }
455
- }
456
- if (uniqueKey !== "" && !attrName.startsWith("prop:")) {
457
- child.setAttribute(attrName, `this.__customCallbackFns.get('${uniqueKey}')(event)`);
458
- } else if (attrName.startsWith("prop:")) {
459
- child.removeAttribute(attrName);
460
- const propName = attrName.replace("prop:", "");
461
- if (!(propName in child)) logPropertyWarning(propName, child);
462
- child[propName] = child.__customCallbackFns.get(uniqueKey);
463
- }
464
- });
465
- } else if (attrName.startsWith("prop:")) {
466
- child.removeAttribute(attrName);
467
- const propName = attrName.replace("prop:", "");
468
- if (!(propName in child)) logPropertyWarning(propName, child);
469
- child[propName] = attr.value;
470
- }
471
- }
472
- evaluateBindings(child, fragment);
473
- }
474
- }
475
- };
476
- var html = (strings, ...values) => {
477
- const innerHTML = strings.reduce((innerHTML2, str, i) => {
478
- let value = values[i] ?? "";
479
- if (Array.isArray(value)) {
480
- value = value.map((item) => processValue(item)).join("");
481
- } else {
482
- value = processValue(value);
483
- }
484
- innerHTML2 += str + String(value === null ? "" : value);
485
- return innerHTML2;
486
- }, "");
487
- if (isServer) return innerHTML;
488
- const template = document.createElement("template");
489
- template.innerHTML = innerHTML;
490
- const fragment = renderState.currentShadowRoot?.importNode?.(template.content, true) ?? document.importNode(template.content, true);
491
- renderState.registry.upgrade(fragment);
492
- evaluateBindings(fragment, fragment);
493
- return fragment;
494
- };
495
- var adoptedStylesSupported = typeof window !== "undefined" && window.ShadowRoot?.prototype.hasOwnProperty("adoptedStyleSheets") && window.CSSStyleSheet?.prototype.hasOwnProperty("replace");
496
- var isCSSStyleSheet = (stylesheet) => {
497
- return typeof CSSStyleSheet !== "undefined" && stylesheet instanceof CSSStyleSheet;
498
- };
499
- var css = (strings, ...values) => {
500
- let cssText = "";
501
- const signalMap = /* @__PURE__ */ new Map();
502
- const signalBindingRegex = /(\{\{signal:.+\}\})/;
503
- strings.forEach((string, i) => {
504
- let value = values[i] ?? "";
505
- if (typeof value === "function") {
506
- const uniqueKey = crypto.randomUUID();
507
- signalMap.set(uniqueKey, value);
508
- value = isServer ? value() : `{{signal:${uniqueKey}}}`;
509
- }
510
- if (typeof value === "object" && value !== null) {
511
- console.error("Objects are not valid in CSS values. Received:", value);
512
- value = "";
513
- }
514
- cssText += string + String(value);
515
- });
516
- if (isServer) {
517
- return cssText;
518
- }
519
- const stylesheet = adoptedStylesSupported ? new CSSStyleSheet() : document.createElement("style");
520
- const textList = cssText.split(signalBindingRegex);
521
- createEffect(() => {
522
- const newCSSTextList = [];
523
- for (const text of textList) {
524
- const uniqueKey = text.replace(/\{\{signal:(.+)\}\}/, "$1");
525
- const signal = uniqueKey !== text ? signalMap.get(uniqueKey) : null;
526
- const newValue = signal !== null ? signal() : text;
527
- const newText = String(newValue);
528
- newCSSTextList.push(newText);
529
- }
530
- const newCSSText = newCSSTextList.join("");
531
- if (isCSSStyleSheet(stylesheet)) {
532
- stylesheet.replace(newCSSText).catch(console.error);
533
- } else {
534
- stylesheet.textContent = newCSSText;
535
- }
536
- });
537
- return stylesheet;
538
- };
539
-
540
- // src/custom-element.ts
541
- var ANY_BINDING_REGEX = /(\{\{.+:.+\}\})/;
542
- var customElement = (render, options) => {
543
- const _options = { ...DEFAULT_RENDER_OPTIONS, ...options };
544
- const {
545
- formAssociated,
546
- observedAttributes: _observedAttributes,
547
- attributesAsProperties,
548
- attachShadow,
549
- shadowRootOptions: _shadowRootOptions
550
- } = _options;
551
- const shadowRootOptions = { ...DEFAULT_RENDER_OPTIONS.shadowRootOptions, ..._shadowRootOptions };
552
- const allOptions = { ..._options, shadowRootOptions };
553
- if (isServer) {
554
- const serverRender = render;
555
- let _tagName2;
556
- let _registry2;
557
- const scopedRegistry = (() => {
558
- if (shadowRootOptions.registry !== void 0 && "scoped" in shadowRootOptions.registry && shadowRootOptions.registry.scoped) {
559
- return shadowRootOptions.registry;
560
- }
561
- })();
562
- return {
563
- define(tagName) {
564
- _tagName2 = tagName;
565
- serverDefine({
566
- tagName,
567
- serverRender,
568
- options: allOptions,
569
- scopedRegistry,
570
- parentRegistry: _registry2,
571
- elementResult: this
572
- });
573
- return this;
574
- },
575
- register(registry) {
576
- if (_tagName2 !== void 0 && "eject" in registry && registry.scoped) {
577
- console.error("Must call `register()` before `define()` for scoped registries.");
578
- return this;
579
- }
580
- if ("eject" in registry) {
581
- _registry2 = registry;
582
- } else {
583
- console.error("Registry must be created with `createRegistry()` for SSR.");
584
- }
585
- return this;
586
- },
587
- eject() {
588
- const error = new Error("Cannot eject a custom element on the server.");
589
- console.error(error);
590
- throw error;
591
- }
592
- };
593
- }
594
- shadowRootOptions.registry = shadowRootOptions.customElements = shadowRootOptions.registry instanceof CustomElementRegistry ? shadowRootOptions.registry : shadowRootOptions.registry?.eject();
595
- const observedAttributesSet = new Set(_observedAttributes);
596
- const attributesAsPropertiesMap = /* @__PURE__ */ new Map();
597
- for (const [attrName, coerce] of attributesAsProperties) {
598
- observedAttributesSet.add(attrName);
599
- attributesAsPropertiesMap.set(attrName, {
600
- // convert kebab-case attribute names to camelCase property names
601
- prop: attrName.replace(/^([A-Z]+)/, (_, letter) => letter.toLowerCase()).replace(/(-|_| )([a-zA-Z])/g, (_, letter) => letter.toUpperCase()),
602
- coerce,
603
- value: null
604
- });
605
- }
606
- const observedAttributes = Array.from(observedAttributesSet);
607
- class CustomElement extends HTMLElement {
608
- #attributesAsPropertiesMap = new Map(attributesAsPropertiesMap);
609
- #attrSignals = {};
610
- #propSignals = {};
611
- #attributeChangedFns = /* @__PURE__ */ new Set();
612
- #connectedFns = /* @__PURE__ */ new Set();
613
- #disconnectedFns = /* @__PURE__ */ new Set();
614
- #adoptedCallbackFns = /* @__PURE__ */ new Set();
615
- #formAssociatedCallbackFns = /* @__PURE__ */ new Set();
616
- #formDisabledCallbackFns = /* @__PURE__ */ new Set();
617
- #formResetCallbackFns = /* @__PURE__ */ new Set();
618
- #formStateRestoreCallbackFns = /* @__PURE__ */ new Set();
619
- #clientOnlyCallbackFns = /* @__PURE__ */ new Set();
620
- #shadowRoot = attachShadow ? this.attachShadow(shadowRootOptions) : null;
621
- #internals = this.attachInternals();
622
- #observer = options?.observedAttributes !== void 0 ? null : new MutationObserver((mutations) => {
623
- for (const mutation of mutations) {
624
- const attrName = mutation.attributeName;
625
- if (mutation.type !== "attributes" || attrName === null) continue;
626
- if (!(attrName in this.#attrSignals)) this.#attrSignals[attrName] = createSignal(null);
627
- const [getter, setter] = this.#attrSignals[attrName];
628
- const oldValue = getter();
629
- const newValue = this.getAttribute(attrName);
630
- setter(newValue);
631
- for (const fn of this.#attributeChangedFns) {
632
- fn(attrName, oldValue, newValue);
633
- }
634
- }
635
- });
636
- #getPropSignal = ((prop, { allowUndefined = false } = {}) => {
637
- if (!(prop in this.#propSignals)) this.#propSignals[prop] = createSignal();
638
- const [_getter, __setter] = this.#propSignals[prop];
639
- let stackLength = 0;
640
- const _setter = (newValue, options2) => {
641
- stackLength++;
642
- queueMicrotask(() => stackLength--);
643
- if (stackLength > 999) {
644
- console.error(
645
- new Error(
646
- `Property signal setter stack overflow detected. Possible infinite loop. Bailing out.
647
-
648
- Property: ${prop}
649
-
650
- New value: ${JSON.stringify(newValue, null, 2)}
651
-
652
- Element: <${this.tagName.toLowerCase()}>
653
- `
654
- )
655
- );
656
- stackLength = 0;
657
- return;
658
- }
659
- __setter(newValue, options2);
660
- };
661
- const descriptor = Object.getOwnPropertyDescriptor(this, prop);
662
- if (descriptor === void 0) {
663
- Object.defineProperty(this, prop, {
664
- get: _getter,
665
- set: _setter,
666
- configurable: false,
667
- enumerable: true
668
- });
669
- }
670
- const setter = (newValue, options2) => {
671
- this[prop] = newValue;
672
- _setter(newValue, options2);
673
- };
674
- const getter = (options2) => {
675
- const value = _getter(options2);
676
- if (value === void 0 && !allowUndefined) {
677
- const error = new Error(
678
- `Error accessing property: "${prop}"
679
- You must set an initial value before calling a property signal's getter.
680
- `
681
- );
682
- console.error(error);
683
- throw error;
684
- }
685
- return value;
686
- };
687
- getter.getter = true;
688
- const publicSignal = [getter, setter];
689
- publicSignal.init = (value) => {
690
- _setter(value);
691
- return [getter, setter];
692
- };
693
- return publicSignal;
694
- }).bind(this);
695
- #render = (() => {
696
- const root = this.#shadowRoot ?? this;
697
- renderState.currentShadowRoot = this.#shadowRoot;
698
- renderState.registry = shadowRootOptions.customElements ?? customElements;
699
- const fragment = render({
700
- elementRef: this,
701
- root,
702
- internals: this.#internals,
703
- attributeChangedCallback: (fn) => this.#attributeChangedFns.add(fn),
704
- connectedCallback: (fn) => this.#connectedFns.add(fn),
705
- disconnectedCallback: (fn) => this.#disconnectedFns.add(fn),
706
- adoptedCallback: (fn) => this.#adoptedCallbackFns.add(fn),
707
- formAssociatedCallback: (fn) => this.#formAssociatedCallbackFns.add(fn),
708
- formDisabledCallback: (fn) => this.#formDisabledCallbackFns.add(fn),
709
- formResetCallback: (fn) => this.#formResetCallbackFns.add(fn),
710
- formStateRestoreCallback: (fn) => this.#formStateRestoreCallbackFns.add(fn),
711
- clientOnlyCallback: (fn) => this.#clientOnlyCallbackFns.add(fn),
712
- getter: (fn) => {
713
- const _fn = () => fn();
714
- _fn.getter = true;
715
- return _fn;
716
- },
717
- customCallback: (fn) => {
718
- const key = crypto.randomUUID();
719
- this.__customCallbackFns?.set(key, fn);
720
- return `this.getRootNode().host.__customCallbackFns.get('${key}')(event)`;
721
- },
722
- attrSignals: new Proxy(
723
- {},
724
- {
725
- get: (_, prop) => {
726
- if (!(prop in this.#attrSignals)) this.#attrSignals[prop] = createSignal(null);
727
- const [getter] = this.#attrSignals[prop];
728
- const setter = (newValue) => this.setAttribute(prop, newValue);
729
- return [getter, setter];
730
- },
731
- set: () => {
732
- console.error("Signals must be assigned via setters.");
733
- return false;
734
- }
735
- }
736
- ),
737
- propSignals: new Proxy({}, {
738
- get: (_, prop) => this.#getPropSignal(prop),
739
- set: () => {
740
- console.error("Signals must be assigned via setters.");
741
- return false;
742
- }
743
- }),
744
- refs: new Proxy(
745
- {},
746
- {
747
- get: (_, prop) => root.querySelector(`[ref=${prop}]`),
748
- set: () => {
749
- console.error("Refs are readonly and cannot be assigned.");
750
- return false;
751
- }
752
- }
753
- ),
754
- adoptStyleSheet: (stylesheet) => {
755
- if (!attachShadow) {
756
- console.warn(
757
- "Styles are only encapsulated when using shadow DOM. The stylesheet will be applied to the global document instead."
758
- );
759
- }
760
- if (isCSSStyleSheet(stylesheet)) {
761
- if (this.#shadowRoot === null) {
762
- for (const rule of stylesheet.cssRules) {
763
- if (rule instanceof CSSStyleRule && rule.selectorText.includes(":host")) {
764
- console.error("Styles with :host are not supported when not using shadow DOM.");
765
- }
766
- }
767
- document.adoptedStyleSheets.push(stylesheet);
768
- return;
769
- }
770
- this.#shadowRoot.adoptedStyleSheets.push(stylesheet);
771
- } else {
772
- requestAnimationFrame(() => {
773
- root.appendChild(stylesheet);
774
- });
775
- }
776
- }
777
- });
778
- fragment.host = this;
779
- for (const fn of this.#clientOnlyCallbackFns) {
780
- fn();
781
- }
782
- root.replaceChildren(fragment);
783
- renderState.currentShadowRoot = null;
784
- renderState.registry = customElements;
785
- }).bind(this);
786
- static get formAssociated() {
787
- return formAssociated;
788
- }
789
- static get observedAttributes() {
790
- return observedAttributes;
791
- }
792
- constructor() {
793
- try {
794
- super();
795
- if (!Object.prototype.hasOwnProperty.call(this, "__customCallbackFns")) {
796
- this.__customCallbackFns = /* @__PURE__ */ new Map();
797
- }
798
- for (const attr of this.attributes) {
799
- this.#attrSignals[attr.name] = createSignal(attr.value);
800
- }
801
- this.#render();
802
- } catch (error) {
803
- const _error = new Error(
804
- "Error instantiating element:\nThis usually occurs if you have errors in the function body of your component. Check prior logs for possible causes.\n",
805
- { cause: error }
806
- );
807
- console.error(_error);
808
- throw _error;
809
- }
810
- }
811
- connectedCallback() {
812
- for (const [attrName, attr] of this.#attributesAsPropertiesMap) {
813
- if (!(attrName in this.#attrSignals)) this.#attrSignals[attrName] = createSignal(null);
814
- const propName = attr.prop;
815
- const [getter] = this.#getPropSignal(propName, { allowUndefined: true });
816
- let busy = false;
817
- createEffect(() => {
818
- if (busy) return;
819
- busy = true;
820
- const value = getter();
821
- if (value === void 0) return;
822
- if (value !== null && value !== false) {
823
- this.setAttribute(attrName, String(value === true ? "" : value));
824
- } else {
825
- this.removeAttribute(attrName);
826
- }
827
- busy = false;
828
- });
829
- }
830
- if (this.#observer !== null) {
831
- this.#observer.observe(this, { attributes: true });
832
- }
833
- for (const fn of this.#connectedFns) {
834
- fn();
835
- }
836
- }
837
- disconnectedCallback() {
838
- if (this.#observer !== null) {
839
- this.#observer.disconnect();
840
- }
841
- for (const fn of this.#disconnectedFns) {
842
- fn();
843
- }
844
- }
845
- #attributesBusy = false;
846
- attributeChangedCallback(name, oldValue, newValue) {
847
- if (this.#attributesBusy || ANY_BINDING_REGEX.test(newValue ?? "")) return;
848
- const [, attrSetter] = this.#attrSignals[name] ?? [];
849
- attrSetter?.(newValue);
850
- const prop = this.#attributesAsPropertiesMap.get(name);
851
- if (prop !== void 0) {
852
- const propName = prop.prop;
853
- this.#attributesBusy = true;
854
- const [, propSetter] = this.#getPropSignal(propName);
855
- if (prop.coerce === Boolean) {
856
- const bool = newValue !== null && newValue !== "false";
857
- const propValue = newValue === null ? null : bool;
858
- propSetter(propValue);
859
- } else {
860
- const propValue = newValue === null ? null : prop.coerce(newValue);
861
- propSetter(propValue);
862
- }
863
- this.#attributesBusy = false;
864
- }
865
- for (const fn of this.#attributeChangedFns) {
866
- fn(name, oldValue, newValue);
867
- }
868
- }
869
- adoptedCallback() {
870
- for (const fn of this.#adoptedCallbackFns) {
871
- fn();
872
- }
873
- }
874
- formAssociatedCallback() {
875
- for (const fn of this.#formAssociatedCallbackFns) {
876
- fn();
877
- }
878
- }
879
- formDisabledCallback() {
880
- for (const fn of this.#formDisabledCallbackFns) {
881
- fn();
882
- }
883
- }
884
- formResetCallback() {
885
- for (const fn of this.#formResetCallbackFns) {
886
- fn();
887
- }
888
- }
889
- formStateRestoreCallback() {
890
- for (const fn of this.#formStateRestoreCallbackFns) {
891
- fn();
892
- }
893
- }
894
- }
895
- let _tagName;
896
- let _registry;
897
- const elementResult = {
898
- define(tagName, options2) {
899
- const registry = _registry ?? customElements;
900
- const nativeRegistry = "eject" in registry ? registry.eject() : registry;
901
- if (nativeRegistry.get(tagName) !== void 0) {
902
- console.warn(`Custom element "${tagName}" was already defined. Skipping...`);
903
- return this;
904
- }
905
- registry.define(tagName, CustomElement, options2);
906
- _tagName = tagName;
907
- return this;
908
- },
909
- register(registry) {
910
- if (_tagName !== void 0 && "eject" in registry && registry.scoped) {
911
- console.error("Must call `register()` before `define()` for scoped registries.");
912
- return this;
913
- }
914
- _registry = registry;
915
- return this;
916
- },
917
- eject: () => CustomElement
918
- };
919
- return elementResult;
920
- };
921
-
922
- // src/registry.ts
923
- var createRegistry = (args) => {
924
- const { scoped = false } = args ?? {};
925
- const customElementMap = /* @__PURE__ */ new Map();
926
- const elementResultMap = /* @__PURE__ */ new Map();
927
- const customElementTags = /* @__PURE__ */ new Set();
928
- const nativeRegistry = (() => {
929
- if (isServer) return;
930
- if (scoped) {
931
- try {
932
- return new CustomElementRegistry();
933
- } catch {
934
- console.error(
935
- "The scoped custom elements polyfill was not found. Falling back to global registry.\n\nCheck `RegistryResult.scoped` at https://thunderous.dev/docs/registries for more information."
936
- );
937
- }
938
- }
939
- return customElements;
940
- })();
941
- return {
942
- __serverCss: /* @__PURE__ */ new Map(),
943
- __serverRenderOpts: /* @__PURE__ */ new Map(),
944
- define(tagName, ElementResult, options) {
945
- const isResult = "eject" in ElementResult;
946
- const upperCaseTagName = tagName.toUpperCase();
947
- if (customElementTags.has(upperCaseTagName)) {
948
- console.warn(`Custom element tag name "${upperCaseTagName}" was already defined. Skipping...`);
949
- return this;
950
- }
951
- if (isResult) {
952
- if (elementResultMap.has(ElementResult)) {
953
- console.warn(`${upperCaseTagName} was already defined. Skipping...`);
954
- return this;
955
- }
956
- }
957
- if (!isServer) {
958
- const CustomElement2 = isResult ? ElementResult.eject() : ElementResult;
959
- if (customElementMap.has(CustomElement2)) {
960
- console.warn(`Custom element class "${CustomElement2.constructor.name}" was already defined. Skipping...`);
961
- return this;
962
- }
963
- customElementMap.set(CustomElement2, upperCaseTagName);
964
- }
965
- if (isResult) elementResultMap.set(ElementResult, upperCaseTagName);
966
- customElementTags.add(upperCaseTagName);
967
- if (isServer) {
968
- if (isResult) ElementResult.register(this).define(tagName, options);
969
- return this;
970
- }
971
- const CustomElement = isResult ? ElementResult.eject() : ElementResult;
972
- nativeRegistry?.define(tagName, CustomElement, options);
973
- return this;
974
- },
975
- getTagName: (ElementResult) => {
976
- const isResult = "eject" in ElementResult;
977
- if (isServer) {
978
- if (isResult) return elementResultMap.get(ElementResult);
979
- return;
980
- }
981
- const CustomElement = isResult ? ElementResult.eject() : ElementResult;
982
- return customElementMap.get(CustomElement);
983
- },
984
- getAllTagNames: () => Array.from(customElementTags),
985
- eject: () => {
986
- if (nativeRegistry === void 0) {
987
- const error = new Error("Cannot eject a registry on the server.");
988
- console.error(error);
989
- throw error;
990
- }
991
- return nativeRegistry;
992
- },
993
- scoped
994
- };
995
- };
996
- export {
997
- clientOnlyCallback,
998
- createEffect,
999
- createRegistry,
1000
- createSignal,
1001
- css,
1002
- customElement,
1003
- derived,
1004
- html,
1005
- insertTemplates,
1006
- onServerDefine
1007
- };
1
+ export { customElement } from './custom-element';
2
+ export { createRegistry } from './registry';
3
+ export { onServerDefine, insertTemplates, clientOnlyCallback } from './server-side';
4
+ export { createEffect, createSignal, derived } from './signals';
5
+ export { html, css } from './render';