-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathgiant.min.js
More file actions
666 lines (666 loc) · 34 KB
/
Copy pathgiant.min.js
File metadata and controls
666 lines (666 loc) · 34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
/**
* GIANT.JS
* Build Date: 2026-05-08T07:26:29.584Z
* Integrity: sha256-5f79380c6aba238f40b4eccf24342e1e6ccbb8fe68cdc6fbdf05927d5236425d
*/
/**
* # GIANT.JS BEST PRACTICES
*
* - IMPORTS: `import { component, html, signal, design } from './giant.js';`
* - HTML TAGS: Destructure from `html` object (e.g., `const { div, p } = html;`).
* - COMPONENTS: Wrap in `component.Name((props, ...children) => { ... })`. Async/Generators natively supported.
* - STATE: ALWAYS use signals (`const x = signal.x(init)`). Read/mutate via `x.value`. DO NOT use `this`.
* - EVENTS: Use lowercase inline handlers (e.g., `onclick`, `onpointerover`).
*
* ## COMPONENT EXAMPLE
* export const MyComponent = component.MyComponent(async (props, ...children) => {
* const { disabled = false, ...hostProps } = props;
* const count = signal.count(0); // Reactive state
* const onclick = (e) => count.value++;
* // RETURN PATTERNS:
* // 1. Standard: `return div({ class: 'wrapper' }, ...children);`
* // 2. Host Props: Return an array to bind props/events directly to the `<ui-mycomponent>` host element.
* return [
* { ...hostProps, onclick, 'data-active': count.value > 0 },
* div(
* button({ disabled, class: design.typography.weightBold }, `Count: ${count.value}`)
* )
* ];
* });
*/
globalThis.isServer = typeof process < 'u' && !!process.versions?.node && typeof window > 'u';
if (globalThis.isServer) {
const g = globalThis;
g.requestAnimationFrame ??= cb => setTimeout(() => cb(Date.now()), 16);
g.cancelAnimationFrame ??= clearTimeout;
g.CustomEvent ??= class CustomEvent extends Event {
constructor(type, opts = {}) {
super(type, opts);
this.detail = opts.detail ?? null;
}
};
const dom = new Proxy(() => {}, {
get: (_, p) =>
p === 'then' ? undefined :
['toString', Symbol.toPrimitive].includes(p) ? () => '' :
p === 'valueOf' ? () => 0 :
p === 'dispatchEvent' ? () => false :
dom,
apply: () => dom,
construct: () => dom,
set: () => true
});
for (const k of ['window', 'document', 'navigator', 'location']) g[k] ??= dom;
}
const tags = 'a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hr html i iframe img input ins kbd label legend li link main map mark meta meter nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup svg path polyline rect circle g line polygon use text table tbody td template textarea tfoot th thead time title tr track u ul video wbr'.split(' ');
const match = (p, s) => s ? p.closest(s) : (a1, a2) => !a2 ? p.closest(a1) : (a1?.closest ? a1.closest(a2) : p.closest(a2));
const escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
const escapeHTML = (str) => String(str).replace(/[&<>"']/g, m => escapeMap[m]);
const eventCache = {};
const delegatedEvents = new Set();
const svgTags = new Set(['svg', 'path', 'polyline', 'rect', 'circle', 'g', 'line', 'polygon', 'use', 'text']);
const isSvgTag = t => svgTags.has(t);
const safeAttr = /^[a-zA-Z_:-][\w:.-]*$/;
const dangerousCss = /javascript:|expression\(|url\(|@import|-moz-binding|\\0/i;
const urlAttrs = /^(href|src|xlink:href|formaction|action|poster|data)$/i;
const dangerousUrl = /^\s*javascript:/i;
const parseClass = (c) => Array.isArray(c) ? c.flat(Infinity).filter(Boolean).join(' ') : c;
let currentRenderingElement = null;
const voidElements = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
const ignoredAttrs = new Set(['state', 'on', 'emit']);
const createVNode = (_type, attributes = {}, children = [], node = null) => ({
_type,
attributes,
children,
node,
toString(lvl = 0) {
if (_type === '#text') return escapeHTML(this.attributes.text);
if (_type === '#dom') return this.node?.textContent ? escapeHTML(this.node.textContent) : '';
const ind = lvl === 0 ? '' : ' '.repeat(lvl);
const attrs = Object.entries(this.attributes)
.filter(([k, v]) => typeof v !== 'function' && !ignoredAttrs.has(k) && v !== false && v != null)
.map(([k, v]) => {
const kLower = k.toLowerCase();
if (!safeAttr.test(k) || kLower === 'srcdoc' || kLower.startsWith('on') || (urlAttrs.test(k) && dangerousUrl.test(String(v)))) return '';
if (k === 'style') {
if (typeof v === 'string' && dangerousCss.test(v)) return '';
if (typeof v === 'object') {
const styleStr = Object.entries(v)
.filter(([sk, sv]) => /^[a-zA-Z0-9-]+$/.test(sk) && !dangerousCss.test(String(sv)))
.map(([sk, sv]) => `${sk}:${escapeHTML(sv)}`).join(';');
return styleStr ? `style="${styleStr}"` : '';
}
}
return v === true ? k : `${k}="${escapeHTML(v)}"`;
})
.filter(Boolean)
.join(' ');
const tagStr = `<${_type}${attrs ? ' ' + attrs : ''}>`;
if (voidElements.has(_type)) return `${ind}${tagStr}`;
const validC = this.children.filter(c => c != null);
if (validC.some(c => c._type !== '#text')) {
return `${ind}${tagStr}\n${validC.map(c => c.toString ? c.toString(lvl + 1) : String(c)).join('\n')}\n${ind}</${_type}>`;
}
return `${ind}${tagStr}${validC.map(c => c.toString ? c.toString(lvl) : String(c)).join('')}</${_type}>`;
}
});
const createElement = (t, ...args) => {
const attributes = {};
const children = [];
const _type = (typeof t === 'string' ? t : t.tagName || 'div').toLowerCase();
const processArgs = (arr) => {
arr.forEach(c => {
if (c == null || c === '') return;
const type = typeof c;
if (type === 'string' || type === 'number' || type === 'boolean') {
children.push(createVNode('#text', { text: String(c) }));
} else if (Array.isArray(c)) {
processArgs(c);
} else if (c._type) {
children.push(c);
} else if (c.nodeType === 1 || c.nodeType === 3) {
const domAttrs = {};
if (c.nodeType === 1) {
const key = c._key ?? (typeof c.getAttribute === 'function' ? c.getAttribute('key') : null);
if (key != null) domAttrs.key = key;
if (c.id) domAttrs.id = c.id;
}
children.push(createVNode('#dom', domAttrs, [], c));
} else if (type === 'function' && c.name?.startsWith('on')) {
attributes[c.name] = c;
} else if (type === 'object') {
for (const k in c) attributes[k] = k === 'class' ? parseClass(c[k]) : c[k];
}
});
};
processArgs(args);
if (_type === 'svg') attributes.xmlns = 'http://www.w3.org/2000/svg';
return createVNode(_type, attributes, children);
};
const html = Object.fromEntries(tags.map(tag => [tag, (...args) => createElement(tag, ...args)]));
const patch = (el, vnode) => {
if (!el || vnode == null) return el;
if (typeof vnode.nodeType === 'number') {
if (el !== vnode) {
if (el && el.parentNode) el.replaceWith(vnode);
return vnode;
}
return el;
}
if (typeof vnode === 'string' || typeof vnode === 'number') {
if (el.textContent !== String(vnode)) el.textContent = String(vnode);
return el;
}
if (vnode._type === '#dom') {
if (el !== vnode.node) {
if (el && el.parentNode) el.replaceWith(vnode.node);
return vnode.node;
}
return el;
}
if (vnode._type === '#text') {
if (el.nodeType === 3) {
if (el.nodeValue !== vnode.attributes.text) el.nodeValue = vnode.attributes.text;
return el;
} else {
const textNode = document.createTextNode(vnode.attributes.text);
if (el.parentNode) el.replaceWith(textNode);
return textNode;
}
}
if (el.nodeType !== 1 || el.localName !== vnode._type) {
const newEl = isSvgTag(vnode._type)
? document.createElementNS('http://www.w3.org/2000/svg', vnode._type)
: document.createElement(vnode._type);
if (el._compId) {
newEl.state = el.state;
newEl.render = el.render;
newEl._compId = el._compId;
newEl._renderSeq = el._renderSeq;
}
if (el.parentNode) el.replaceWith(newEl);
el = newEl;
}
const oldProps = el._vprops || {};
if (!el._vprops && el.attributes) {
for (let i = 0; i < el.attributes.length; i++) oldProps[el.attributes[i].name] = true;
}
for (const k in oldProps) {
if (!(k in vnode.attributes)) {
if (k === 'class') {
el.className = '';
el.removeAttribute('class');
} else if (k === 'id') {
el.id = '';
el.removeAttribute('id');
} else if (k.startsWith('on')) {
const eventName = eventCache[k] || k.slice(2).toLowerCase();
if (el._handlers) delete el._handlers[eventName];
} else if (k === 'style') {
el.style.cssText = '';
} else {
el.removeAttribute(k);
}
}
}
el._vprops = { ...vnode.attributes };
for (const k in vnode.attributes) {
const v = vnode.attributes[k];
if (k === 'key') {
el._key = v;
if (el.getAttribute(k) !== String(v)) el.setAttribute(k, v);
} else if (typeof v === 'function') {
let eventName = eventCache[k];
if (!eventName) {
eventName = eventCache[k] = k.startsWith('on') ? k.slice(2).toLowerCase() : k.toLowerCase();
}
(el._handlers ??= {})[eventName] = v;
if (!delegatedEvents.has(eventName)) {
delegatedEvents.add(eventName);
const useCapture = ['focus', 'blur', 'scroll', 'load', 'error'].includes(eventName);
document.addEventListener(eventName, (e) => {
let node = e.target;
while (node && node !== document) {
if (node._handlers && node._handlers[eventName]) {
let compRoot = node;
while (compRoot && !compRoot.state && compRoot !== document) {
compRoot = compRoot.parentNode;
}
const contextNode = (compRoot && compRoot.state) ? compRoot : node;
node._handlers[eventName].call(contextNode, e, match(e.target));
if (e.cancelBubble) break;
}
node = node.parentNode;
}
}, useCapture);
}
} else if (k === 'class') {
const classStr = parseClass(v);
if (typeof el.className === 'string') {
if (el.className !== classStr) el.className = classStr;
} else {
if (el.getAttribute('class') !== classStr) el.setAttribute('class', classStr);
}
} else if (k === 'value') {
if (el.value !== String(v)) el.value = v;
} else if (k === 'checked') {
if (el.checked !== !!v) el.checked = !!v;
} else if (k === 'style' && typeof v === 'object') {
const oldStyle = oldProps.style || {};
for (const sk in oldStyle) {
if (!(sk in v)) {
if (sk.startsWith('--')) el.style.removeProperty(sk);
else el.style[sk] = '';
}
}
for (const sk in v) {
if (dangerousCss.test(String(v[sk]))) continue;
if (sk.startsWith('--')) {
if (el.style.getPropertyValue(sk) !== String(v[sk])) {
el.style.setProperty(sk, v[sk]);
}
} else {
if (el.style[sk] !== v[sk]) el.style[sk] = v[sk];
}
}
} else if (k !== 'state' && k !== 'on' && k !== 'emit') {
if (!safeAttr.test(k)) continue;
if (k.toLowerCase() === 'srcdoc') continue;
if (k.toLowerCase().startsWith('on') && typeof v === 'string') continue;
if (urlAttrs.test(k) && dangerousUrl.test(String(v))) continue;
if (k === 'style' && typeof v === 'string' && dangerousCss.test(v)) continue;
if (v === false || v == null) {
if (el.hasAttribute(k)) el.removeAttribute(k);
} else {
const strVal = v === true ? '' : String(v);
if (el.getAttribute(k) !== strVal) el.setAttribute(k, strVal);
}
}
}
const newC = vnode.children || [];
if (newC.length === 0) {
if (el.childNodes.length > 0) el.textContent = '';
return el;
}
if (el.childNodes.length === 0) {
for (let i = 0; i < newC.length; i++) {
const vchild = newC[i];
let targetNode = vchild._type === '#text'
? document.createTextNode(vchild.attributes.text)
: vchild._type === '#dom'
? vchild.node
: isSvgTag(vchild._type)
? document.createElementNS('http://www.w3.org/2000/svg', vchild._type)
: document.createElement(vchild._type);
if (vchild._type !== '#dom' && vchild._type !== '#text') {
targetNode = patch(targetNode, vchild);
}
el.appendChild(targetNode);
}
return el;
}
let oldNode = el.firstChild;
let newIdx = 0;
let lastPlacedNode = null;
while (oldNode && newIdx < newC.length) {
const vchild = newC[newIdx];
while (oldNode && oldNode.nodeType === 3 && oldNode.nodeValue.trim() === '' && vchild._type !== '#text') {
const next = oldNode.nextSibling;
el.removeChild(oldNode);
oldNode = next;
}
if (!oldNode) break;
const oldKey = oldNode.nodeType === 1 ? (oldNode._key ?? oldNode.getAttribute('key')) : null;
const newKey = vchild.attributes?.key;
if (oldKey == null && newKey == null) {
// Fast path: both elements are unkeyed, keep patching sequentially
} else if (String(oldKey) !== String(newKey)) {
break;
}
oldNode = patch(oldNode, vchild);
lastPlacedNode = oldNode;
oldNode = oldNode.nextSibling;
newIdx++;
}
if (newIdx === newC.length) {
while (oldNode) {
const next = oldNode.nextSibling;
el.removeChild(oldNode);
oldNode = next;
}
return el;
}
const keyed = new Map();
const unkeyed = [];
let curr = oldNode;
while (curr) {
const next = curr.nextSibling;
if (curr.nodeType === 1) {
const key = curr._key ?? curr.getAttribute('key');
if (key != null) keyed.set(String(key), curr);
else unkeyed.push(curr);
} else {
if (!(curr.nodeType === 3 && curr.nodeValue.trim() === '')) {
unkeyed.push(curr);
}
}
curr = next;
}
let unkeyedIdx = 0;
for (let i = newIdx; i < newC.length; i++) {
const vchild = newC[i];
const key = vchild.attributes?.key;
let targetNode = null;
if (key != null) {
targetNode = keyed.get(String(key));
if (targetNode) keyed.delete(String(key));
} else if (unkeyedIdx < unkeyed.length) {
targetNode = unkeyed[unkeyedIdx++];
}
if (targetNode) {
targetNode = patch(targetNode, vchild);
} else {
targetNode = vchild._type === '#text'
? document.createTextNode(vchild.attributes.text)
: vchild._type === '#dom'
? vchild.node
: isSvgTag(vchild._type)
? document.createElementNS('http://www.w3.org/2000/svg', vchild._type)
: document.createElement(vchild._type);
if (vchild._type !== '#dom' && vchild._type !== '#text') {
targetNode = patch(targetNode, vchild);
}
}
const expectedNext = lastPlacedNode ? lastPlacedNode.nextSibling : el.firstChild;
if (targetNode !== expectedNext) {
el.insertBefore(targetNode, expectedNext);
}
lastPlacedNode = targetNode;
}
keyed.forEach(node => {
if (node.parentNode === el) el.removeChild(node);
});
for (let i = unkeyedIdx; i < unkeyed.length; i++) {
if (unkeyed[i].parentNode === el) el.removeChild(unkeyed[i]);
}
return el;
};
const observables = new WeakSet();
const handleError = (err, compName, compId) => {
if (err instanceof Error && err.stack) {
const msg = `${err.name}: ${err.message}`;
const stackStr = err.stack.includes(err.message) ? err.stack : `${msg}\n${err.stack}`;
const [firstLine, ...rest] = stackStr.split('\n');
const userStack = rest.filter(l => !l.includes('giant.js') && !l.includes('node:'));
err.stack = [firstLine, ...userStack, ` at <${compName}> (GIANT Component Boundary)`].join('\n');
}
if (typeof coreComponent.onError === 'function') {
coreComponent.onError(err, { component: compName, id: compId });
} else {
console.error(`[GIANT] Error Boundary: Component <${compName}> crashed.\n`, err.stack || err);
if (!globalThis.isServer && globalThis.window) {
window.dispatchEvent(new CustomEvent('giant:error', { detail: { component: compName, id: compId, error: err } }));
}
}
};
function coreComponent(Fn, tagName = '') {
const defaultTag = ((Fn.name.match(/[A-Z][a-z0-9]*/g)?.join('-') ?? Fn.name) || 'anonymous-component').toLowerCase();
Fn.tagName = tagName || (tags.includes(defaultTag) ? `ui-${defaultTag}` : defaultTag);
Fn.rawFn = Fn;
const proxy = new Proxy(Fn, {
apply: (target, _, rawArgs) => {
const isProps = rawArgs[0] && typeof rawArgs[0] === 'object' && !Array.isArray(rawArgs[0]) && !rawArgs[0]._type && !rawArgs[0].nodeType;
const args = isProps ? rawArgs : [{}, ...rawArgs];
const explicitId = args[0]?.id;
const explicitKey = args[0]?.key;
const id = explicitId || `local-${Math.random().toString(36).slice(2, 9)}`;
let compState = explicitId ? (coreComponent.state[id] ??= {}) : {};
const safeRender = (contextToApply, argsToApply) => {
try {
return target.apply(contextToApply, argsToApply);
} catch (err) {
handleError(err, Fn.tagName, explicitId || id);
return createVNode('span', { style: 'display:none !important;', 'data-giant-error': Fn.tagName });
}
};
if (globalThis.isServer) {
const mockEl = { state: compState, _signals: {} };
const previousElement = currentRenderingElement;
currentRenderingElement = mockEl;
let innerVNode = safeRender(mockEl, args);
currentRenderingElement = previousElement;
let hostAttrs = { id: explicitId || id };
// Recursive SSR normalizer that matches client behavior
const normalizeSSR = (val) => {
if (val == null || typeof val === 'boolean') return createVNode('#text', { text: '' });
if (typeof val === 'string' || typeof val === 'number') return createVNode('#text', { text: String(val) });
if (Array.isArray(val)) {
const renderableChildren = [];
for (let i = 0; i < val.length; i++) {
const item = val[i];
if (typeof item === 'function') continue; // Strip event handlers
// Extract host props
if (item && typeof item === 'object' && !item._type && !item.nodeType && !Array.isArray(item)) {
for (const k in item) hostAttrs[k] = k === 'class' ? parseClass(item[k]) : item[k];
continue;
}
renderableChildren.push(normalizeSSR(item));
}
// Match client logic: unwrap if only 1 child remains, otherwise group in span
if (renderableChildren.length === 1) return renderableChildren[0];
return createVNode('span', { style: { display: 'contents' } }, renderableChildren);
}
return val;
};
return createVNode(Fn.tagName, hostAttrs, [normalizeSSR(innerVNode)]);
}
const safeId = (globalThis.CSS && CSS.escape) ? CSS.escape(explicitId) : explicitId;
let el = explicitId ? document.querySelector(`${Fn.tagName}#${safeId}`) : null;
if (!el) el = document.createElement(Fn.tagName);
el.id = el.id || explicitId || '';
if (explicitKey != null) el._key = explicitKey;
el._compId = explicitId || id;
el._renderSeq = el._renderSeq || 0;
el.state = el.state || compState;
if (!el.state._isProxy) {
el.state = new Proxy(el.state, {
get: (tgt, prop) => prop === '_isProxy' ? true : tgt[prop],
set: (tgt, prop, val) => {
if (tgt[prop] === val) return true;
tgt[prop] = val;
coreComponent._pendingRenders.add(el);
if (!coreComponent._isMicrotaskQueued) {
coreComponent._isMicrotaskQueued = true;
queueMicrotask(coreComponent._flushRenders);
}
return true;
}
});
}
el.render = (updates) => {
if (updates && typeof updates === 'object') Object.assign(args[0], updates);
const newArgs = [{ ...args[0] }, ...args.slice(1)];
const seq = ++el._renderSeq;
if (el._renderController) el._renderController.abort();
el._renderController = new AbortController();
el.signal = el._renderController.signal;
const previousElement = currentRenderingElement;
currentRenderingElement = el;
const innerVNode = safeRender(el, newArgs);
currentRenderingElement = previousElement;
const normalizeVNode = (val) => {
if (val == null || typeof val === 'boolean') return createVNode('#text', { text: '' });
if (typeof val === 'string' || typeof val === 'number') return createVNode('#text', { text: String(val) });
if (Array.isArray(val)) {
const renderableChildren = [];
for (let i = 0; i < val.length; i++) {
const item = val[i];
if (typeof item === 'function' && item.name) { el[item.name] = item; continue; }
if (item && typeof item === 'object' && !item._type && !item.nodeType && !Array.isArray(item)) {
for (const k in item) k === 'class' ? el.setAttribute('class', parseClass(item[k])) : (el[k] = item[k]);
continue;
}
renderableChildren.push(normalizeVNode(item));
}
if (renderableChildren.length === 1) return renderableChildren[0];
return createVNode('span', { style: { display: 'contents' } }, renderableChildren);
}
return val;
};
const applyPatch = (node) => {
if (seq !== el._renderSeq) return; // Prevent race conditions
el = patch(el, createVNode(Fn.tagName, { id: el.id || explicitId || id }, [node]));
if (seq > 1) queueMicrotask(() => el.dispatchEvent(new CustomEvent('updated', { bubbles: true, detail: { element: el } })));
};
if (innerVNode?.next) {
(async () => {
try {
let result = await innerVNode.next();
while (!result.done) {
applyPatch(normalizeVNode(result.value));
result = await innerVNode.next();
}
applyPatch(normalizeVNode(result.value));
} catch (err) {
handleError(err, Fn.tagName, explicitId || id);
applyPatch(createVNode('span', { style: 'display:none !important;', 'data-giant-error': Fn.tagName }));
}
})();
} else if (innerVNode?.then) {
innerVNode.then(res => applyPatch(normalizeVNode(res)))
.catch(err => {
handleError(err, Fn.tagName, explicitId || id);
applyPatch(createVNode('span', { style: 'display:none !important;', 'data-giant-error': Fn.tagName }));
});
} else {
applyPatch(normalizeVNode(innerVNode));
}
};
el.render();
observables.add(el);
return el;
}
});
if (coreComponent._globalsEnabled && Fn.name) {
if (!(Fn.name in globalThis)) globalThis[Fn.name] = proxy;
else if (globalThis[Fn.name] !== proxy) console.warn(`GIANT: Cannot expose component "${Fn.name}" globally because it conflicts with a native browser API or existing variable.`);
}
if (!tags.includes(Fn.tagName.toLowerCase())) coreComponent.registry[Fn.tagName] = proxy;
return proxy;
}
Object.assign(coreComponent, {
_globalsEnabled: false,
registry: {},
state: {},
onError: null,
_pendingRenders: new Set(),
_isMicrotaskQueued: false,
enableGlobals: () => {
coreComponent._globalsEnabled = true;
tags.forEach(tag => { if (!(tag in globalThis)) globalThis[tag] = html[tag]; });
console.log('GIANT: HTML tags and components exposed to global scope.');
},
_flushRenders: () => {
const queue = Array.from(coreComponent._pendingRenders);
coreComponent._pendingRenders.clear();
coreComponent._isMicrotaskQueued = false;
queue.forEach(el => el.isConnected !== false && el.render());
}
});
const component = new Proxy(coreComponent, {
apply(target, thisArg, argArray) {
return target.apply(thisArg, argArray);
},
get(target, prop) {
if (prop in target) return target[prop];
if (typeof prop === 'string') {
return (Fn, tagName = '') => {
Object.defineProperty(Fn, 'name', { value: prop, configurable: true });
return target(Fn, tagName);
};
}
},
set(target, prop, value) {
target[prop] = value;
return true;
}
});
function createRoot(Fn) {
const app = (Fn.tagName && coreComponent.registry[Fn.tagName] === Fn) ? Fn : component(Fn);
if (globalThis.isServer) return app;
return new Promise(resolve => {
const onready = async () => {
const el = document.querySelector(Fn.tagName)
let root
try {
const props = {};
if (el) {
if (!el.id) el.id = `root-${Math.random().toString(36).slice(2, 9)}`;
props.id = el.id;
}
root = await app(props)
} catch (err) {
return window.dispatchEvent(new ErrorEvent('error', { message: err.message, error: err }))
}
if (el && el !== root && el.parentNode) {
el.parentNode.replaceChild(root, el)
} else if (!document.body.contains(root)) {
document.body.appendChild(root)
}
resolve(root)
if (!globalThis.MutationObserver) return
const processNodes = (nodes, eventType) => {
const stack = Array.from(nodes)
while (stack.length > 0) {
const node = stack.pop()
if (observables.has(node)) {
node.dispatchEvent(new CustomEvent(eventType, { bubbles: true, detail: { element: node } }));
if (eventType === 'destroyed') {
if (node._renderController) node._renderController.abort();
queueMicrotask(() => {
if (document.body && !document.body.contains(node)) {
if (node._compId && coreComponent.state[node._compId]) delete coreComponent.state[node._compId];
observables.delete(node);
}
});
}
}
if (node.childNodes) {
for (let i = node.childNodes.length - 1; i >= 0; i--) stack.push(node.childNodes[i])
}
}
}
new globalThis.MutationObserver(list => list.forEach(mut => {
mut.removedNodes && processNodes(mut.removedNodes, 'destroyed')
mut.addedNodes && processNodes(mut.addedNodes, 'ready')
})).observe(root.parentNode || document.body, { childList: true, subtree: true })
}
document.readyState === 'loading'
? globalThis.window.addEventListener('DOMContentLoaded', onready)
: onready()
})
}
const signal = new Proxy({}, {
get: (_, key) => {
if (typeof key !== 'string') return;
return initial => {
const el = currentRenderingElement;
if (!el) throw Error('GIANT: state must be used inside a component.');
el.state ??= {};
el._signals ??= {};
if (!(key in el.state)) {
el.state[key] = typeof initial === 'function' ? initial() : initial;
}
return el._signals[key] ??= {
get value() {
return el.state[key];
},
set value(v) {
el.state[key] = typeof v === 'function' ? v(el.state[key]) : v;
}
};
};
}
});
const design = {"color":{"surface":"color-surface","surfaceMuted":"color-surface-muted","surfaceRaised":"color-surface-raised","surfaceOverlay":"color-surface-overlay","placeholder":"color-placeholder","highlight":"color-highlight","neutral":["var(--color-neutral-0)","var(--color-neutral-1)","var(--color-neutral-2)","var(--color-neutral-3)","var(--color-neutral-4)","var(--color-neutral-5)","var(--color-neutral-6)","var(--color-neutral-7)","var(--color-neutral-8)","var(--color-neutral-9)"],"primary":["var(--color-primary-0)","var(--color-primary-1)","var(--color-primary-2)","var(--color-primary-3)","var(--color-primary-4)","var(--color-primary-5)"],"accent":["var(--color-accent-0)","var(--color-accent-1)","var(--color-accent-2)","var(--color-accent-3)","var(--color-accent-4)","var(--color-accent-5)"],"success":["var(--color-success-0)","var(--color-success-1)","var(--color-success-2)","var(--color-success-3)","var(--color-success-4)"],"warning":["var(--color-warning-0)","var(--color-warning-1)","var(--color-warning-2)","var(--color-warning-3)","var(--color-warning-4)"],"danger":["var(--color-danger-0)","var(--color-danger-1)","var(--color-danger-2)","var(--color-danger-3)","var(--color-danger-4)"]},"bg":{"bg":"bg","bgMuted":"bg-muted","bgSubtle":"bg-subtle","bgSurface":"bg-surface","bgSurfaceMuted":"bg-surface-muted","bgSurfaceRaised":"bg-surface-raised","bgSurfaceOverlay":"bg-surface-overlay","actionBg":"color-action-bg","accentBg":"color-accent-bg","bgAction":"bg-action","successBg":"color-success-bg","warningBg":"color-warning-bg","dangerBg":"color-danger-bg","inputBg":"color-input-bg","inverseBg":"color-inverse-bg"},"fg":{"fg":"fg","fgMuted":"fg-muted","fgSubtle":"fg-subtle","actionFg":"color-action-fg","accentFg":"color-accent-fg","fgAction":"fg-action","successFg":"color-success-fg","warningFg":"color-warning-fg","dangerFg":"color-danger-fg","inputFg":"color-input-fg","inverseFg":"color-inverse-fg"},"border":{"border":"border-color","borderMuted":"border-muted","borderStrong":"border-strong","actionBorder":"color-action-border","accentBorder":"color-accent-border","borderAction":"border-action","successBorder":"color-success-border","warningBorder":"color-warning-border","dangerBorder":"color-danger-border","inputBorder":"color-input-border"},"layout":{"block":"layout-block","inline":"layout-inline","inlineBlock":"layout-inline-block","flex":"layout-flex","inlineFlex":"layout-inline-flex","inlineGrid":"layout-inline-grid","grid":"layout-grid","none":"layout-none","static":"layout-static","relative":"layout-relative","absolute":"layout-absolute","fixed":"layout-fixed","sticky":"layout-sticky","inset0":"layout-inset-0","insetAuto":"layout-inset-auto","insetInline0":"layout-inset-inline-0","insetBlock0":"layout-inset-block-0","insetStart0":"layout-inset-start-0","insetEnd0":"layout-inset-end-0","zBase":"layout-z-base","zRaised":"layout-z-raised","zOverlay":"layout-z-overlay","zModal":"layout-z-modal","overflowVisible":"layout-overflow-visible","overflowHidden":"layout-overflow-hidden","overflowAuto":"layout-overflow-auto","overflowScroll":"layout-overflow-scroll","overflowClip":"layout-overflow-clip","overflowInlineAuto":"layout-overflow-inline-auto","overflowBlockAuto":"layout-overflow-block-auto","itemsCenter":"layout-items-center","justifyCenter":"layout-justify-center","justifyBetween":"layout-justify-between","justifyAround":"layout-justify-around","container":"layout-container","stack":"layout-stack","cluster":"layout-cluster","frame":"layout-frame","sidebar":"layout-sidebar","switcher":"layout-switcher"},"spacing":{"layoutGap0":"layout-gap-0","gap0":"gap-0","layoutGap1":"layout-gap-1","gap1":"gap-1","layoutGap2":"layout-gap-2","gap2":"gap-2","layoutGap3":"layout-gap-3","gap3":"gap-3","layoutGap4":"layout-gap-4","gap4":"gap-4","layoutGap5":"layout-gap-5","gap5":"gap-5","layoutGap6":"layout-gap-6","gap6":"gap-6","layoutGap7":"layout-gap-7","gap7":"gap-7","layoutGap8":"layout-gap-8","gap8":"gap-8","layoutPadding0":"layout-padding-0","p0":"p-0","layoutPadding1":"layout-padding-1","p1":"p-1","layoutPadding2":"layout-padding-2","p2":"p-2","layoutPadding3":"layout-padding-3","p3":"p-3","layoutPadding4":"layout-padding-4","p4":"p-4","layoutPadding5":"layout-padding-5","p5":"p-5","layoutPadding6":"layout-padding-6","p6":"p-6","layoutPadding7":"layout-padding-7","p7":"p-7","layoutPadding8":"layout-padding-8","p8":"p-8","layoutPaddingInline4":"layout-padding-inline-4","layoutPaddingBlock4":"layout-padding-block-4","layoutMargin0":"layout-margin-0","m0":"m-0","layoutMarginAuto":"layout-margin-auto","mAuto":"m-auto","layoutMarginInlineAuto":"layout-margin-inline-auto"},"size":{"layoutWidthFull":"layout-width-full","wFull":"w-full","layoutWidthFit":"layout-width-fit","layoutWidthMin":"layout-width-min","layoutWidthMax":"layout-width-max","layoutHeightFull":"layout-height-full","hFull":"h-full","layoutHeightScreen":"layout-height-screen","minHScreen":"min-h-screen","layoutSizeFull":"layout-size-full","layoutRatioSquare":"layout-ratio-square","layoutRatioVideo":"layout-ratio-video"},"typography":{"fontSans":"typography-font-sans","fontSerif":"typography-font-serif","fontMono":"typography-font-mono","size0":"typography-size-0","size1":"typography-size-1","size2":"typography-size-2","size3":"typography-size-3","size4":"typography-size-4","size5":"typography-size-5","size6":"typography-size-6","size7":"typography-size-7","lineTight":"typography-line-tight","lineSnug":"typography-line-snug","lineNormal":"typography-line-normal","lineLoose":"typography-line-loose","weightRegular":"typography-weight-regular","weightMedium":"typography-weight-medium","weightSemibold":"typography-weight-semibold","weightBold":"typography-weight-bold","letterTight":"typography-letter-tight","letterNormal":"typography-letter-normal","letterWide":"typography-letter-wide","alignStart":"typography-align-start","alignCenter":"typography-align-center","alignEnd":"typography-align-end","transformUppercase":"typography-transform-uppercase","transformLowercase":"typography-transform-lowercase","transformCapitalize":"typography-transform-capitalize","decorationNone":"typography-decoration-none","decorationUnderline":"typography-decoration-underline","decorationLineThrough":"typography-decoration-line-through","overflowTruncate":"typography-overflow-truncate","overflowWrap":"typography-overflow-wrap","balance":"typography-balance","pretty":"typography-pretty"},"shape":{"radius0":"shape-radius-0","radius1":"shape-radius-1","radius2":"shape-radius-2","radius3":"shape-radius-3","radius4":"shape-radius-4","radiusRound":"shape-radius-round","border0":"shape-border-0","border1":"shape-border-1","border2":"shape-border-2"},"effect":{"shadow0":"effect-shadow-0","shadow1":"effect-shadow-1","shadow2":"effect-shadow-2","shadow3":"effect-shadow-3","opacity0":"effect-opacity-0","opacity50":"effect-opacity-50","opacity100":"effect-opacity-100","blur0":"effect-blur-0","blur1":"effect-blur-1","blur2":"effect-blur-2","ring":"effect-ring","outlineOffset2":"effect-outline-offset-2"},"animation":{"transitionColors":"animation-transition-colors","transitionTransform":"animation-transition-transform","transitionOpacity":"animation-transition-opacity","transitionShadow":"animation-transition-shadow","transitionAll":"animation-transition-all","durationFast":"animation-duration-fast","durationNormal":"animation-duration-normal","durationSlow":"animation-duration-slow","easeStandard":"animation-ease-standard","easeIn":"animation-ease-in","easeOut":"animation-ease-out","fadeIn":"animation-fade-in","enter":"animation-enter"},"interaction":{"cursorDefault":"interaction-cursor-default","cursorPointer":"interaction-cursor-pointer","cursorNotAllowed":"interaction-cursor-not-allowed","pointerNone":"interaction-pointer-none","pointerAuto":"interaction-pointer-auto","selectNone":"interaction-select-none","selectText":"interaction-select-text","selectAll":"interaction-select-all","scrollAuto":"interaction-scroll-auto","scrollSmooth":"interaction-scroll-smooth","hidden":"interaction-hidden","invisible":"interaction-invisible","visible":"interaction-visible","srOnly":"interaction-sr-only","notSrOnly":"interaction-not-sr-only"},"responsive":{"smLayoutGrid":"sm:layout-grid","smLayoutDisplayFlex":"sm:layout-display-flex","smLayoutDisplayNone":"sm:layout-display-none","mdLayoutGrid":"md:layout-grid","mdLayoutDisplayFlex":"md:layout-display-flex","mdLayoutDisplayNone":"md:layout-display-none","lgLayoutGrid":"lg:layout-grid","lgLayoutDisplayFlex":"lg:layout-display-flex","lgLayoutDisplayNone":"lg:layout-display-none"},"state":{"hoverColorBg":"hover:color-bg","activeColorBg":"active:color-bg","hoverColorBorder":"hover:color-border","focusColorBorder":"focus:color-border","hoverColorActionBg":"hover:color-action-bg","hoverColorAccentBg":"hover:color-accent-bg","activeColorActionBg":"active:color-action-bg","activeColorAccentBg":"active:color-accent-bg","disabledColorBg":"disabled:color-bg","disabledColorFg":"disabled:color-fg","disabledColorBorder":"disabled:color-border","focusEffectRing":"focus:effect-ring","focusVisibleEffectRing":"focus-visible:effect-ring","focusWithinEffectRing":"focus-within:effect-ring","hoverInteractionCursorPointer":"hover:interaction-cursor-pointer","focusInteractionPointerAuto":"focus:interaction-pointer-auto","activeInteractionCursorDefault":"active:interaction-cursor-default","disabledInteractionCursorNotAllowed":"disabled:interaction-cursor-not-allowed","cqSmLayoutGrid":"cq-sm:layout-grid","cqSmLayoutDisplayFlex":"cq-sm:layout-display-flex","cqSmLayoutDisplayNone":"cq-sm:layout-display-none","cqMdLayoutGrid":"cq-md:layout-grid","cqMdLayoutDisplayFlex":"cq-md:layout-display-flex","cqMdLayoutDisplayNone":"cq-md:layout-display-none","cqLgLayoutGrid":"cq-lg:layout-grid","cqLgLayoutDisplayFlex":"cq-lg:layout-display-flex","cqLgLayoutDisplayNone":"cq-lg:layout-display-none"},"misc":{"block":"block","inline":"inline","inlineBlock":"inline-block","flex":"flex","inlineFlex":"inline-flex","inlineGrid":"inline-grid","grid":"grid","hidden":"hidden","itemsCenter":"items-center","justifyCenter":"justify-center","justifyBetween":"justify-between","px4":"px-4","py4":"py-4","mxAuto":"mx-auto","cursorDefault":"cursor-default","cursorPointer":"cursor-pointer","cursorNotAllowed":"cursor-not-allowed","pointerEventsNone":"pointer-events-none","pointerEventsAuto":"pointer-events-auto","selectNone":"select-none","selectText":"select-text","selectAll":"select-all","responsiveContainer":"responsive-container","responsiveContainerNamed":"responsive-container-named","sliderThumbWrapper":"slider-thumb-wrapper","enterFade0":"enter-fade-0","enterZoom96":"enter-zoom-96","enterSlideX50":"enter-slide-x-50","enterSlideY48":"enter-slide-y-48"}};
export { createRoot, createElement, design, component, html, signal, match };