lightview 2.0.9 → 2.1.0

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 (77) hide show
  1. package/build-bundles.mjs +109 -0
  2. package/cdom/helpers/array.js +70 -0
  3. package/cdom/helpers/compare.js +26 -0
  4. package/cdom/helpers/conditional.js +34 -0
  5. package/cdom/helpers/datetime.js +54 -0
  6. package/cdom/helpers/format.js +20 -0
  7. package/cdom/helpers/logic.js +24 -0
  8. package/cdom/helpers/lookup.js +25 -0
  9. package/cdom/helpers/math.js +34 -0
  10. package/cdom/helpers/network.js +41 -0
  11. package/cdom/helpers/state.js +77 -0
  12. package/cdom/helpers/stats.js +39 -0
  13. package/cdom/helpers/string.js +49 -0
  14. package/cdom/parser.js +602 -0
  15. package/components/actions/button.js +16 -3
  16. package/components/actions/swap.js +26 -3
  17. package/components/daisyui.js +1 -1
  18. package/components/data-display/alert.js +13 -3
  19. package/components/data-display/badge.js +11 -3
  20. package/components/data-display/kbd.js +9 -3
  21. package/components/data-display/loading.js +11 -3
  22. package/components/data-display/progress.js +11 -3
  23. package/components/data-display/radial-progress.js +12 -3
  24. package/components/data-display/tooltip.js +17 -0
  25. package/components/layout/divider.js +21 -1
  26. package/components/layout/indicator.js +14 -0
  27. package/components/navigation/tabs.js +291 -16
  28. package/docs/api/elements.html +125 -49
  29. package/docs/api/hypermedia.html +29 -2
  30. package/docs/api/index.html +6 -2
  31. package/docs/api/nav.html +18 -4
  32. package/docs/cdom-nav.html +29 -0
  33. package/docs/cdom.html +362 -0
  34. package/docs/components/alert.html +8 -8
  35. package/docs/components/badge.html +55 -0
  36. package/docs/components/button.html +78 -92
  37. package/docs/components/component-nav.html +1 -1
  38. package/docs/components/divider.html +65 -21
  39. package/docs/components/indicator.html +85 -31
  40. package/docs/components/kbd.html +64 -25
  41. package/docs/components/loading.html +55 -39
  42. package/docs/components/progress.html +44 -3
  43. package/docs/components/radial-progress.html +32 -12
  44. package/docs/components/swap.html +183 -100
  45. package/docs/components/tabs.html +146 -278
  46. package/docs/components/tooltip.html +71 -31
  47. package/docs/getting-started/index.html +7 -5
  48. package/docs/index.html +1 -1
  49. package/docs/syntax-nav.html +10 -0
  50. package/docs/syntax.html +8 -6
  51. package/index.html +2 -2
  52. package/lightview-all.js +1 -0
  53. package/lightview-cdom.js +1 -0
  54. package/lightview-x.js +1 -1608
  55. package/lightview.js +1 -766
  56. package/lightview.js.bak +1 -0
  57. package/package.json +6 -2
  58. package/src/lightview-all.js +10 -0
  59. package/src/lightview-cdom.js +305 -0
  60. package/src/lightview-x.js +1581 -0
  61. package/src/lightview.js +694 -0
  62. package/src/reactivity/signal.js +133 -0
  63. package/src/reactivity/state.js +217 -0
  64. package/test-text-tag.js +6 -0
  65. package/tests/cdom/fixtures/helpers.cdomc +62 -0
  66. package/tests/cdom/fixtures/user.cdom +14 -0
  67. package/tests/cdom/fixtures/user.cdomc +12 -0
  68. package/tests/cdom/fixtures/user.odom +18 -0
  69. package/tests/cdom/fixtures/user.vdom +11 -0
  70. package/tests/cdom/helpers.test.js +121 -0
  71. package/tests/cdom/loader.test.js +125 -0
  72. package/tests/cdom/parser.test.js +108 -0
  73. package/tests/cdom/reactivity.test.js +186 -0
  74. package/tests/text-tag.test.js +77 -0
  75. package/vite.config.mjs +52 -0
  76. package/components/data-display/skeleton.js +0 -66
  77. package/docs/components/skeleton.html +0 -447
package/lightview.js CHANGED
@@ -1,766 +1 @@
1
- (() => {
2
- /**
3
- * LIGHTVIEW CORE
4
- * A minimalist library for signals-based reactivity and functional UI components.
5
- */
6
-
7
- // ============= SIGNALS =============
8
-
9
- let currentEffect = null;
10
-
11
-
12
- /**
13
- * Helper to get a value from a Map or create and set it if it doesn't exist.
14
- */
15
- const getOrSet = (map, key, factory) => {
16
- let v = map.get(key);
17
- if (!v) {
18
- v = factory();
19
- map.set(key, v);
20
- }
21
- return v;
22
- };
23
-
24
- const nodeState = new WeakMap();
25
- const nodeStateFactory = () => ({ effects: [], onmount: null, onunmount: null });
26
-
27
- const signalRegistry = new Map();
28
-
29
- /**
30
- * Creates a reactive signal.
31
- * @param {*} initialValue - The initial value of the signal.
32
- * @param {Object|string} [optionsOrName] - Optional name (for registry) or options object.
33
- */
34
- const signal = (initialValue, optionsOrName) => {
35
- let name = typeof optionsOrName === 'string' ? optionsOrName : optionsOrName?.name;
36
- const storage = optionsOrName?.storage;
37
-
38
- if (name && storage) {
39
- const stored = storage.getItem(name);
40
- if (stored !== null) {
41
- initialValue = stored;
42
- try {
43
- initialValue = JSON.parse(stored);
44
- } catch (e) {
45
- // Ignore storage errors
46
- }
47
- }
48
- }
49
-
50
- let value = initialValue;
51
- const subscribers = new Set();
52
-
53
- const f = (...args) => {
54
- if (args.length === 0) return f.value;
55
- f.value = args[0];
56
- };
57
-
58
- Object.defineProperty(f, 'value', {
59
- get() {
60
- if (currentEffect) {
61
- subscribers.add(currentEffect);
62
- currentEffect.dependencies.add(subscribers);
63
- }
64
- return value;
65
- },
66
- set(newValue) {
67
- if (value !== newValue) {
68
- value = newValue;
69
- if (name && storage) {
70
- try {
71
- storage.setItem(name, JSON.stringify(value));
72
- } catch (e) {
73
- // Ignore storage errors
74
- }
75
- }
76
- // Copy subscribers to avoid infinite loop when effect re-subscribes during iteration
77
- [...subscribers].forEach(effect => effect());
78
- }
79
- }
80
- });
81
-
82
- if (name) {
83
- signalRegistry.set(name, f);
84
- }
85
-
86
- return f;
87
- };
88
-
89
- signal.get = (name, defaultValue) => {
90
- if (!signalRegistry.has(name) && defaultValue !== undefined) {
91
- return signal(defaultValue, name);
92
- }
93
- return signalRegistry.get(name);
94
- };
95
-
96
- /**
97
- * Creates a side-effect that automatically tracks and re-runs when its signal dependencies change.
98
- * @param {Function} fn - The function to execute as an effect.
99
- */
100
- const effect = (fn) => {
101
- const execute = () => {
102
- if (!execute.active || execute.running) return;
103
- // Cleanup old dependencies
104
- execute.dependencies.forEach(dep => dep.delete(execute));
105
- execute.dependencies.clear();
106
-
107
- execute.running = true;
108
- currentEffect = execute;
109
- try {
110
- fn();
111
- } finally {
112
- currentEffect = null;
113
- execute.running = false;
114
- }
115
- };
116
-
117
- execute.active = true;
118
- execute.running = false;
119
- execute.dependencies = new Set();
120
- execute.stop = () => {
121
- execute.dependencies.forEach(dep => dep.delete(execute));
122
- execute.dependencies.clear();
123
- execute.active = false;
124
- };
125
- execute();
126
- return execute;
127
- };
128
-
129
- /**
130
- * Assocates an effect with a DOM node for automatic cleanup when the node is removed.
131
- */
132
- const trackEffect = (node, effectFn) => {
133
- const state = getOrSet(nodeState, node, nodeStateFactory);
134
- if (!state.effects) state.effects = [];
135
- state.effects.push(effectFn);
136
- };
137
-
138
- /**
139
- * Creates a read-only signal derived from other signals.
140
- */
141
- const computed = (fn) => {
142
- const sig = signal(undefined);
143
- effect(() => {
144
- sig.value = fn();
145
- });
146
- return sig;
147
- };
148
-
149
-
150
- // ============= SHADOW DOM SUPPORT =============
151
- // Marker symbol to identify shadowDOM directives
152
- const SHADOW_DOM_MARKER = Symbol('lightview.shadowDOM');
153
-
154
- /**
155
- * Create a shadowDOM directive marker
156
- * @param {Object} attributes - { mode: 'open'|'closed', styles?: string[], adoptedStyleSheets?: CSSStyleSheet[] }
157
- * @param {Array} children - Children to render inside the shadow root
158
- * @returns {Object} - Marker object for setupChildren to process
159
- */
160
- const createShadowDOMMarker = (attributes, children) => ({
161
- [SHADOW_DOM_MARKER]: true,
162
- mode: attributes.mode || 'open',
163
- styles: attributes.styles || [],
164
- adoptedStyleSheets: attributes.adoptedStyleSheets || [],
165
- children
166
- });
167
-
168
- /**
169
- * Check if an object is a shadowDOM marker
170
- */
171
- const isShadowDOMMarker = (obj) => obj && typeof obj === 'object' && obj[SHADOW_DOM_MARKER] === true;
172
-
173
- /**
174
- * Process a shadowDOM marker by attaching shadow root and rendering children
175
- * @param {Object} marker - The shadowDOM marker
176
- * @param {HTMLElement} parentNode - The DOM node to attach shadow to
177
- */
178
- const processShadowDOM = (marker, parentNode) => {
179
- // Don't attach if already has shadow root
180
- if (parentNode.shadowRoot) {
181
- console.warn('Lightview: Element already has a shadowRoot, skipping shadowDOM directive');
182
- return;
183
- }
184
-
185
- // Attach shadow root
186
- const shadowRoot = parentNode.attachShadow({ mode: marker.mode });
187
-
188
- // Split adoptedStyleSheets into sheets and urls
189
- const sheets = [];
190
- const linkUrls = [...(marker.styles || [])];
191
-
192
- if (marker.adoptedStyleSheets && marker.adoptedStyleSheets.length > 0) {
193
- marker.adoptedStyleSheets.forEach(item => {
194
- if (item instanceof CSSStyleSheet) {
195
- sheets.push(item);
196
- } else if (typeof item === 'string') {
197
- linkUrls.push(item);
198
- }
199
- });
200
- }
201
-
202
- // Handle adoptedStyleSheets (modern, efficient approach)
203
- if (sheets.length > 0) {
204
- try {
205
- shadowRoot.adoptedStyleSheets = sheets;
206
- } catch (e) {
207
- console.warn('Lightview: adoptedStyleSheets not supported');
208
- }
209
- }
210
-
211
- // Inject stylesheet links
212
- for (const styleUrl of linkUrls) {
213
- const link = document.createElement('link');
214
- link.rel = 'stylesheet';
215
- link.href = styleUrl;
216
- shadowRoot.appendChild(link);
217
- }
218
-
219
- // Setup children inside shadow root
220
- if (marker.children && marker.children.length > 0) {
221
- setupChildrenInTarget(marker.children, shadowRoot);
222
- }
223
- };
224
-
225
- // ============= REACTIVE UI =============
226
- let inSVG = false;
227
-
228
- const domToElement = new WeakMap();
229
-
230
- /**
231
- * Wraps a native DOM element in a Lightview reactive proxy.
232
- */
233
- const wrapDomElement = (domNode, tag, attributes = {}, children = []) => {
234
- const el = {
235
- tag,
236
- attributes,
237
- children,
238
- get domEl() { return domNode; }
239
- };
240
- const proxy = makeReactive(el);
241
- domToElement.set(domNode, proxy);
242
- return proxy;
243
- };
244
-
245
- /**
246
- * The core virtual-DOM-to-real-DOM factory.
247
- * Handles tag functions (components), shadow DOM directives, and SVG namespaces.
248
- */
249
- const element = (tag, attributes = {}, children = []) => {
250
- if (customTags[tag]) tag = customTags[tag];
251
- // If tag is a function (component), call it and process the result
252
- if (typeof tag === 'function') {
253
- const result = tag({ ...attributes }, children);
254
- return processComponentResult(result);
255
- }
256
-
257
- // Special handling for shadowDOM pseudo-element
258
- if (tag === 'shadowDOM') {
259
- return createShadowDOMMarker(attributes, children);
260
- }
261
-
262
- const isSVG = tag.toLowerCase() === 'svg';
263
- const wasInSVG = inSVG;
264
- if (isSVG) inSVG = true;
265
-
266
- const domNode = inSVG
267
- ? document.createElementNS('http://www.w3.org/2000/svg', tag)
268
- : document.createElement(tag);
269
-
270
- const proxy = wrapDomElement(domNode, tag, attributes, children);
271
- proxy.attributes = attributes;
272
- proxy.children = children;
273
-
274
- if (isSVG) inSVG = wasInSVG;
275
- return proxy;
276
- };
277
-
278
- // Process component function return value (HTML string, DOM node, vDOM, or Object DOM)
279
- const processComponentResult = (result) => {
280
- if (!result) return null;
281
-
282
- if (Lightview.hooks.processChild) {
283
- result = Lightview.hooks.processChild(result) ?? result;
284
- }
285
-
286
- // Already a Lightview element
287
- if (result.domEl) return result;
288
-
289
- // DOM node - wrap it
290
- if (result instanceof HTMLElement) {
291
- return wrapDomElement(result, result.tagName.toLowerCase(), {}, []);
292
- }
293
-
294
- // HTML string - parse and wrap
295
- if (typeof result === 'string') {
296
- const template = document.createElement('template');
297
- template.innerHTML = result.trim();
298
- const content = template.content;
299
- // If single element, return it; otherwise wrap in a fragment-like span
300
- if (content.childNodes.length === 1 && content.firstChild instanceof HTMLElement) {
301
- const el = content.firstChild;
302
- return wrapDomElement(el, el.tagName.toLowerCase(), {}, []);
303
- } else {
304
- const wrapper = document.createElement('span');
305
- wrapper.style.display = 'contents';
306
- wrapper.appendChild(content);
307
- return wrapDomElement(wrapper, 'span', {}, []);
308
- }
309
- }
310
-
311
- // vDOM object with tag property
312
- if (typeof result === 'object' && result.tag) {
313
- return element(result.tag, result.attributes || {}, result.children || []);
314
- }
315
-
316
- return null;
317
- };
318
-
319
- /**
320
- * Internal proxy to intercept 'attributes' and 'children' updates on an element.
321
- */
322
- const makeReactive = (el) => {
323
- const domNode = el.domEl;
324
-
325
- return new Proxy(el, {
326
- set(target, prop, value) {
327
- if (prop === 'attributes') {
328
- target[prop] = makeReactiveAttributes(value, domNode);
329
- } else if (prop === 'children') {
330
- target[prop] = setupChildren(value, domNode);
331
- } else {
332
- target[prop] = value;
333
- }
334
- return true;
335
- }
336
- });
337
- };
338
-
339
- // Properties that should be set directly on the DOM node object rather than as attributes
340
- const NODE_PROPERTIES = new Set(['value', 'checked', 'selected', 'selectedIndex', 'className', 'innerHTML', 'innerText']);
341
-
342
- // Set attribute with proper handling of boolean attributes and undefined/null values
343
- const setAttributeValue = (domNode, key, value) => {
344
- const isBool = typeof domNode[key] === 'boolean';
345
-
346
- // Sanitize href/src attributes to prevent javascript: and other dangerous protocols
347
- if ((key === 'href' || key === 'src') && typeof value === 'string' && /^(javascript|vbscript|data:text\/html|data:application\/javascript)/i.test(value)) {
348
- console.warn(`[Lightview] Blocked dangerous protocol in ${key}: ${value}`);
349
- value = 'javascript:void(0)'; // Safer fallback than # which might trigger scroll or router
350
- }
351
-
352
- if (NODE_PROPERTIES.has(key) || isBool) {
353
- domNode[key] = isBool ? (value !== null && value !== undefined && value !== false && value !== 'false') : value;
354
- } else if (value === null || value === undefined) {
355
- domNode.removeAttribute(key);
356
- } else {
357
- domNode.setAttribute(key, value);
358
- }
359
- };
360
-
361
- /**
362
- * Processes attributes, handling event listeners, reactive bindings, and special 'onmount' hooks.
363
- */
364
- const makeReactiveAttributes = (attributes, domNode) => {
365
- const reactiveAttrs = {};
366
-
367
- for (let [key, value] of Object.entries(attributes)) {
368
- if (key === 'onmount' || key === 'onunmount') {
369
- const state = getOrSet(nodeState, domNode, nodeStateFactory);
370
- state[key] = value;
371
-
372
- if (key === 'onmount' && domNode.isConnected) {
373
- value(domNode);
374
- }
375
- } else if (key.startsWith('on')) {
376
- // Event handler
377
- if (typeof value === 'function') {
378
- // Function handler - use addEventListener
379
- const eventName = key.slice(2).toLowerCase();
380
- domNode.addEventListener(eventName, value);
381
- } else if (typeof value === 'string') {
382
- // String handler (from parsed HTML) - use setAttribute
383
- // Browser will compile the string into a handler function
384
- domNode.setAttribute(key, value);
385
- }
386
- reactiveAttrs[key] = value;
387
- } else if (typeof value === 'function') {
388
- // Reactive binding
389
- const runner = effect(() => {
390
- const result = value();
391
- if (key === 'style' && typeof result === 'object') {
392
- Object.assign(domNode.style, result);
393
- } else {
394
- setAttributeValue(domNode, key, result);
395
- }
396
- });
397
- trackEffect(domNode, runner);
398
- reactiveAttrs[key] = value;
399
- } else if (key === 'style' && typeof value === 'object') {
400
- // Handle style object which may contain reactive values
401
- Object.entries(value).forEach(([styleKey, styleValue]) => {
402
- if (typeof styleValue === 'function') {
403
- const runner = effect(() => {
404
- domNode.style[styleKey] = styleValue();
405
- });
406
- trackEffect(domNode, runner);
407
- } else {
408
- domNode.style[styleKey] = styleValue;
409
- }
410
- });
411
- reactiveAttrs[key] = value;
412
- } else {
413
- // Static attribute - handle undefined/null/boolean properly
414
- setAttributeValue(domNode, key, value);
415
- reactiveAttrs[key] = value;
416
- }
417
- }
418
-
419
- return reactiveAttrs;
420
- };
421
-
422
- /**
423
- * Core child processing logic - shared between setupChildren and setupChildrenInTarget
424
- * @param {Array} children - Children to process
425
- * @param {HTMLElement|ShadowRoot} targetNode - Where to append children
426
- * @param {boolean} clearExisting - Whether to clear existing content
427
- * @returns {Array} - Processed child elements
428
- */
429
- /**
430
- * Core child processing logic. Recursively handles strings, arrays,
431
- * reactive functions, vDOM objects, and Shadow DOM markers.
432
- */
433
- const processChildren = (children, targetNode, clearExisting = true) => {
434
- if (clearExisting && targetNode.innerHTML !== undefined) {
435
- targetNode.innerHTML = ''; // Clear existing
436
- }
437
- const childElements = [];
438
-
439
- // Check if we're processing children of script or style elements
440
- // These need raw text content preserved, not reactive transformations
441
- const isSpecialElement = targetNode.tagName &&
442
- (targetNode.tagName.toLowerCase() === 'script' || targetNode.tagName.toLowerCase() === 'style');
443
-
444
- const flatChildren = children.flat(Infinity);
445
-
446
- for (let child of flatChildren) {
447
- // Allow extensions to transform children (e.g., template literals)
448
- // BUT skip for script/style elements which need raw content
449
- if (Lightview.hooks.processChild && !isSpecialElement) {
450
- child = Lightview.hooks.processChild(child) ?? child;
451
- }
452
-
453
- // Handle shadowDOM markers - attach shadow to parent and process shadow children
454
- if (isShadowDOMMarker(child)) {
455
- // targetNode is the parent element that should get the shadow root
456
- // For ShadowRoot targets, we can't attach another shadow, so warn
457
- if (targetNode instanceof ShadowRoot) {
458
- console.warn('Lightview: Cannot nest shadowDOM inside another shadowDOM');
459
- continue;
460
- }
461
- processShadowDOM(child, targetNode);
462
- continue;
463
- }
464
-
465
- const type = typeof child;
466
- if (type === 'function') {
467
- const startMarker = document.createComment('lv:s');
468
- const endMarker = document.createComment('lv:e');
469
- targetNode.appendChild(startMarker);
470
- targetNode.appendChild(endMarker);
471
-
472
- let runner;
473
- const update = () => {
474
- // 1. Cleanup: Remove everything between markers
475
- while (startMarker.nextSibling && startMarker.nextSibling !== endMarker) {
476
- startMarker.nextSibling.remove();
477
- // Note: MutationObserver handles cleanupNode(removedNode)
478
- }
479
-
480
- // 2. Execution: Get new value and process it
481
- const val = child();
482
- if (val === undefined || val === null) return;
483
-
484
- // 3. Render: Process children into a fragment and insert before endMarker
485
- const fragment = document.createDocumentFragment();
486
- const childrenToProcess = Array.isArray(val) ? val : [val];
487
-
488
- // Stop the runner if the markers are no longer in the DOM
489
- if (runner && !startMarker.isConnected) {
490
- runner.stop();
491
- return;
492
- }
493
-
494
- processChildren(childrenToProcess, fragment, false);
495
- endMarker.parentNode.insertBefore(fragment, endMarker);
496
- };
497
-
498
- runner = effect(update);
499
- trackEffect(startMarker, runner);
500
- childElements.push(child);
501
- } else if (['string', 'number', 'boolean', 'symbol'].includes(type)) {
502
- // Static text
503
- targetNode.appendChild(document.createTextNode(child));
504
- childElements.push(child);
505
- } else if (child && type === 'object' && child.tag) {
506
- // Child element (already wrapped or plain object) - tag can be string or function
507
- const childEl = child.domEl ? child : element(child.tag, child.attributes || {}, child.children || []);
508
- targetNode.appendChild(childEl.domEl);
509
- childElements.push(childEl);
510
- }
511
- }
512
-
513
- return childElements;
514
- };
515
-
516
- /**
517
- * Setup children in a target node (for shadow roots and other targets)
518
- * Does not clear existing content
519
- */
520
- const setupChildrenInTarget = (children, targetNode) => {
521
- return processChildren(children, targetNode, false);
522
- };
523
-
524
- /**
525
- * Setup children on a DOM node, clearing existing content
526
- */
527
- const setupChildren = (children, domNode) => {
528
- return processChildren(children, domNode, true);
529
- };
530
-
531
- // ============= EXPORTS =============
532
- /**
533
- * Enhances an existing DOM element with Lightview reactivity.
534
- */
535
- const enhance = (selectorOrNode, options = {}) => {
536
- const domNode = typeof selectorOrNode === 'string'
537
- ? document.querySelector(selectorOrNode)
538
- : selectorOrNode;
539
-
540
- // If it's already a Lightview element, use its domEl
541
- const node = domNode.domEl || domNode;
542
- if (!(node instanceof HTMLElement)) return null;
543
-
544
- const tagName = node.tagName.toLowerCase();
545
- let el = domToElement.get(node);
546
-
547
- if (!el) {
548
- el = wrapDomElement(node, tagName);
549
- }
550
-
551
- const { innerText, innerHTML, ...attrs } = options;
552
-
553
- if (innerText !== undefined) {
554
- if (typeof innerText === 'function') {
555
- effect(() => { node.innerText = innerText(); });
556
- } else {
557
- node.innerText = innerText;
558
- }
559
- }
560
-
561
- if (innerHTML !== undefined) {
562
- if (typeof innerHTML === 'function') {
563
- effect(() => { node.innerHTML = innerHTML(); });
564
- } else {
565
- node.innerHTML = innerHTML;
566
- }
567
- }
568
-
569
- if (Object.keys(attrs).length > 0) {
570
- // Merge with existing attributes or simply set them triggers the proxy
571
- el.attributes = attrs;
572
- }
573
-
574
- return el;
575
- };
576
-
577
- /**
578
- * Query selector helper that adds a .content() method for easy DOM manipulation.
579
- */
580
- const $ = (cssSelectorOrElement, startingDomEl = document.body) => {
581
- const el = typeof cssSelectorOrElement === 'string' ? startingDomEl.querySelector(cssSelectorOrElement) : cssSelectorOrElement;
582
- if (!el) return null;
583
- Object.defineProperty(el, 'content', {
584
- value(child, location = 'inner') {
585
- location = location.toLowerCase();
586
- const tags = Lightview.tags;
587
-
588
- // Check if target element is script or style
589
- const isSpecialElement = el.tagName &&
590
- (el.tagName.toLowerCase() === 'script' || el.tagName.toLowerCase() === 'style');
591
-
592
- const array = (Array.isArray(child) ? child : [child]).map(item => {
593
- // Allow extensions to transform children (e.g., Object DOM syntax)
594
- // BUT skip for script/style elements which need raw content
595
- if (Lightview.hooks.processChild && !isSpecialElement) {
596
- item = Lightview.hooks.processChild(item) ?? item;
597
- }
598
- if (item.tag && !item.domEl) {
599
- return element(item.tag, item.attributes || {}, item.children || []).domEl;
600
- } else {
601
- return item.domEl || item;
602
- }
603
- });
604
-
605
- const target = location === 'shadow' ? (el.shadowRoot || el.attachShadow({ mode: 'open' })) : el;
606
-
607
- if (location === 'inner' || location === 'shadow') {
608
- target.replaceChildren(...array);
609
- } else if (location === 'outer') {
610
- target.replaceWith(...array);
611
- } else if (location === 'afterbegin') {
612
- target.prepend(...array);
613
- } else if (location === 'beforeend') {
614
- target.append(...array);
615
- } else {
616
- array.forEach(item => el.insertAdjacentElement(location, item));
617
- }
618
- return el;
619
- },
620
- configurable: true,
621
- writable: true
622
- });
623
- return el;
624
- };
625
-
626
- const customTags = {}
627
- /**
628
- * Proxy for accessing or registering tags/components.
629
- * e.g., Lightview.tags.div(...) or Lightview.tags.MyComponent = ...
630
- */
631
- const tags = new Proxy({}, {
632
- get(_, tag) {
633
- if (tag === "_customTags") return { ...customTags };
634
-
635
- const wrapper = (...args) => {
636
- let attributes = {};
637
- let children = args;
638
- const arg0 = args[0];
639
- if (args.length > 0 && arg0 && typeof arg0 === 'object' && !arg0.tag && !arg0.domEl && !Array.isArray(arg0)) {
640
- attributes = arg0;
641
- children = args.slice(1);
642
- }
643
- return element(customTags[tag] || tag, attributes, children);
644
- };
645
-
646
- // Lift static methods/properties from the component onto the wrapper
647
- // This allows patterns like Card.Figure to work when Card is retrieved from tags
648
- if (customTags[tag]) {
649
- Object.assign(wrapper, customTags[tag]);
650
- }
651
-
652
- return wrapper;
653
- },
654
- set(_, tag, value) {
655
- customTags[tag] = value;
656
- return true;
657
- }
658
- });
659
-
660
- const Lightview = {
661
- signal,
662
- computed,
663
- effect,
664
- element, // do not document this
665
- enhance,
666
- tags,
667
- $,
668
- // Extension hooks
669
- hooks: {
670
- onNonStandardHref: null,
671
- processChild: null,
672
- validateUrl: null
673
- },
674
- // Internals exposed for extensions
675
- internals: {
676
- domToElement,
677
- wrapDomElement,
678
- setupChildren
679
- }
680
- };
681
-
682
- // Export for use
683
- if (typeof module !== 'undefined' && module.exports) {
684
- module.exports = Lightview;
685
- }
686
- if (typeof window !== 'undefined') {
687
- globalThis.Lightview = Lightview;
688
-
689
- // Global click handler delegates to hook if registered
690
- globalThis.addEventListener('click', (e) => {
691
- // Support fragment navigation piercing Shadow DOM
692
- // Use composedPath() to find the actual clicked element, even inside shadow roots
693
- const path = e.composedPath();
694
- const link = path.find(el => el.tagName === 'A' && el.getAttribute?.('href')?.startsWith('#'));
695
-
696
- if (link && !e.defaultPrevented) {
697
- const href = link.getAttribute('href');
698
- if (href.length > 1) {
699
- const id = href.slice(1);
700
- const root = link.getRootNode();
701
- const target = (root.getElementById ? root.getElementById(id) : null) ||
702
- (root.querySelector ? root.querySelector(`#${id}`) : null);
703
-
704
- if (target) {
705
- e.preventDefault();
706
- requestAnimationFrame(() => {
707
- requestAnimationFrame(() => {
708
- target.style.scrollMarginTop = 'calc(var(--site-nav-height, 0px) + 2rem)';
709
- target.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
710
- });
711
- });
712
- }
713
- }
714
- }
715
-
716
- if (Lightview.hooks.onNonStandardHref) {
717
- Lightview.hooks.onNonStandardHref(e);
718
- }
719
- });
720
-
721
- // Automatic Cleanup & Lifecycle Hooks
722
- if (typeof MutationObserver !== 'undefined') {
723
- const walkNodes = (node, fn) => {
724
- fn(node);
725
- node.childNodes?.forEach(n => walkNodes(n, fn));
726
- if (node.shadowRoot) walkNodes(node.shadowRoot, fn);
727
- };
728
-
729
- const cleanupNode = (node) => walkNodes(node, n => {
730
- const s = nodeState.get(n);
731
- if (s) {
732
- s.effects?.forEach(e => e.stop());
733
- s.onunmount?.(n);
734
- nodeState.delete(n);
735
- }
736
- });
737
-
738
- const mountNode = (node) => walkNodes(node, n => {
739
- nodeState.get(n)?.onmount?.(n);
740
- });
741
-
742
- const observer = new MutationObserver((mutations) => {
743
- mutations.forEach((mutation) => {
744
- mutation.removedNodes.forEach(cleanupNode);
745
- mutation.addedNodes.forEach(mountNode);
746
- });
747
- });
748
-
749
- // Wait for DOM to be ready before observing
750
- const startObserving = () => {
751
- if (document.body) {
752
- observer.observe(document.body, {
753
- childList: true,
754
- subtree: true
755
- });
756
- }
757
- };
758
-
759
- if (document.readyState === 'loading') {
760
- document.addEventListener('DOMContentLoaded', startObserving);
761
- } else {
762
- startObserving();
763
- }
764
- }
765
- }
766
- })();
1
+ !function(){"use strict";const e=globalThis.__LIGHTVIEW_INTERNALS__||(globalThis.__LIGHTVIEW_INTERNALS__={currentEffect:null,registry:new Map,dependencyMap:new WeakMap}),t=(t,n)=>{let o="string"==typeof n?n:null==n?void 0:n.name;const r=null==n?void 0:n.storage;if(o&&r)try{const e=r.getItem(o);null!==e&&(t=JSON.parse(e))}catch(l){}let s=t;const i=new Set,a=(...e)=>{if(0===e.length)return a.value;a.value=e[0]};if(Object.defineProperty(a,"value",{get:()=>(e.currentEffect&&(i.add(e.currentEffect),e.currentEffect.dependencies.add(i)),s),set(e){if(s!==e){if(s=e,o&&r)try{r.setItem(o,JSON.stringify(s))}catch(l){}[...i].forEach(e=>e())}}}),o)if(e.registry.has(o)){if(e.registry.get(o)!==a)throw new Error(`Lightview: A signal or state with the name "${o}" is already registered.`)}else e.registry.set(o,a);return a};t.get=(n,o)=>e.registry.has(n)||void 0===o?e.registry.get(n):t(o,n);const n=t=>{const n=()=>{if(n.active&&!n.running){n.dependencies.forEach(e=>e.delete(n)),n.dependencies.clear(),n.running=!0,e.currentEffect=n;try{t()}finally{e.currentEffect=null,n.running=!1}}};return n.active=!0,n.running=!1,n.dependencies=new Set,n.stop=()=>{n.dependencies.forEach(e=>e.delete(n)),n.dependencies.clear(),n.active=!1},n(),n},o=(e,t)=>Object.getOwnPropertyNames(e).filter(n=>"function"==typeof e[n]&&t(n));o(Date.prototype,e=>/^(to|get|valueOf)/.test(e)),o(Date.prototype,e=>/^set/.test(e));const r=(e,t,n)=>{let o=e.get(t);return o||(o=n(),e.set(t,o)),o},s={get currentEffect(){return(globalThis.__LIGHTVIEW_INTERNALS__||(globalThis.__LIGHTVIEW_INTERNALS__={})).currentEffect}},i=new WeakMap,a=()=>({effects:[],onmount:null,onunmount:null}),l=e.registry,c=(e,t)=>{const n=r(i,e,a);n.effects||(n.effects=[]),n.effects.push(t)},d=Symbol("lightview.shadowDOM"),u=e=>e&&"object"==typeof e&&!0===e[d],f=(e,t)=>{if(t.shadowRoot)return void console.warn("Lightview: Element already has a shadowRoot, skipping shadowDOM directive");const n=t.attachShadow({mode:e.mode}),o=[],r=[...e.styles||[]];if(e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&e.adoptedStyleSheets.forEach(e=>{e instanceof CSSStyleSheet?o.push(e):"string"==typeof e&&r.push(e)}),o.length>0)try{n.adoptedStyleSheets=o}catch(s){console.warn("Lightview: adoptedStyleSheets not supported")}for(const i of r){const e=document.createElement("link");e.rel="stylesheet",e.href=i,n.appendChild(e)}e.children&&e.children.length>0&&L(e.children,n)};let h=!1;const p=new WeakMap,g=(e,t,n={},o=[])=>{const r=b({tag:t,attributes:n,children:o,get domEl(){return e}});return p.set(e,r),r},m=(e,t={},o=[])=>{if(N[e]&&(e=N[e]),"function"==typeof e){const n=e({...t},o);return y(n)}if("shadowDOM"===e)return((e,t)=>({[d]:!0,mode:e.mode||"open",styles:e.styles||[],adoptedStyleSheets:e.adoptedStyleSheets||[],children:t}))(t,o);if("text"===e&&!h){const r=document.createTextNode(""),s={tag:e,attributes:t,children:o,get domEl(){return r}},i=()=>{const e=(Array.isArray(s.children)?s.children:[s.children]).flat(1/0).map(e=>{const t="function"==typeof e?e():e;return t&&"object"==typeof t&&t.domEl?t.domEl.textContent:null==t?"":String(t)});r.textContent=e.join(" ")},a=new Proxy(s,{set:(e,t,n)=>(e[t]=n,"children"===t&&i(),!0)});if(o.flat(1/0).some(e=>"function"==typeof e)){const e=n(i);c(r,e)}return i(),a}const r="svg"===e.toLowerCase(),s=h;r&&(h=!0);const i=h?document.createElementNS("http://www.w3.org/2000/svg",e):document.createElement(e),a=g(i,e,t,o);return a.attributes=t,a.children=o,r&&(h=s),a},y=e=>{if(!e)return null;if(j.hooks.processChild&&(e=j.hooks.processChild(e)??e),e.domEl)return e;const t=typeof e;if("object"===t&&e instanceof HTMLElement)return g(e,e.tagName.toLowerCase(),{},[]);if("object"===t&&e instanceof String){const t=document.createElement("span");return t.textContent=e.toString(),g(t,"span",{},[])}if("string"===t){const t=document.createElement("template");t.innerHTML=e.trim();const n=t.content;if(1===n.childNodes.length&&n.firstChild instanceof HTMLElement){const e=n.firstChild;return g(e,e.tagName.toLowerCase(),{},[])}{const e=document.createElement("span");return e.style.display="contents",e.appendChild(n),g(e,"span",{},[])}}return"object"==typeof e&&e.tag?m(e.tag,e.attributes||{},e.children||[]):null},b=e=>{const t=e.domEl;return new Proxy(e,{set:(e,n,o)=>(e[n]="attributes"===n?v(o,t):"children"===n?C(o,t):o,!0)})},w=new Set(["value","checked","selected","selectedIndex","className","innerHTML","innerText"]),E=(e,t,n)=>{const o="boolean"==typeof e[t];"href"!==t&&"src"!==t||"string"!=typeof n||!/^(javascript|vbscript|data:text\/html|data:application\/javascript)/i.test(n)||(console.warn(`[Lightview] Blocked dangerous protocol in ${t}: ${n}`),n="javascript:void(0)"),w.has(t)||o?e[t]=o?null!=n&&!1!==n&&"false"!==n:n:null==n?e.removeAttribute(t):e.setAttribute(t,n)},v=(e,t)=>{const o={};for(let[s,l]of Object.entries(e))if("onmount"===s||"onunmount"===s){r(i,t,a)[s]=l,"onmount"===s&&t.isConnected&&l(t)}else if(s.startsWith("on")){if("function"==typeof l){const e=s.slice(2).toLowerCase();t.addEventListener(e,l)}else"string"==typeof l&&t.setAttribute(s,l);o[s]=l}else if("function"==typeof l){const e=n(()=>{const e=l();"style"===s&&"object"==typeof e?Object.assign(t.style,e):E(t,s,e)});c(t,e),o[s]=l}else"style"===s&&"object"==typeof l?(Object.entries(l).forEach(([e,o])=>{if("function"==typeof o){const r=n(()=>{t.style[e]=o()});c(t,r)}else t.style[e]=o}),o[s]=l):(E(t,s,l),o[s]=l);return o},S=(e,t,o=!0)=>{o&&void 0!==t.innerHTML&&(t.innerHTML="");const r=[],s=t.tagName&&("script"===t.tagName.toLowerCase()||"style"===t.tagName.toLowerCase()),i=e.flat(1/0);for(let a of i){if(j.hooks.processChild&&!s&&(a=j.hooks.processChild(a)??a),u(a)){if(t instanceof ShadowRoot){console.warn("Lightview: Cannot nest shadowDOM inside another shadowDOM");continue}f(a,t);continue}const e=typeof a;if("function"===e){const e=document.createComment("lv:s"),o=document.createComment("lv:e");let s;t.appendChild(e),t.appendChild(o);const i=()=>{for(;e.nextSibling&&e.nextSibling!==o;)e.nextSibling.remove();const t=a();if(null!=t)if(!s||e.isConnected)if("object"==typeof t&&t instanceof String){const e=document.createTextNode(t);o.parentNode.insertBefore(e,o)}else{const e=document.createDocumentFragment(),n=Array.isArray(t)?t:[t];S(n,e,!1),o.parentNode.insertBefore(e,o)}else s.stop()};s=n(i),c(e,s),r.push(a)}else if(["string","number","boolean","symbol"].includes(e)||a&&"object"===e&&a instanceof String)t.appendChild(document.createTextNode(a)),r.push(a);else if(a&&"object"===e&&a.tag){const e=a.domEl?a:m(a.tag,a.attributes||{},a.children||[]);t.appendChild(e.domEl),r.push(e)}}return r},L=(e,t)=>S(e,t,!1),C=(e,t)=>S(e,t,!0),N={},T=new Proxy({},{get(e,t){if("_customTags"===t)return{...N};const n=(...e)=>{let n={},o=e;const r=e[0];return e.length>0&&r&&"object"==typeof r&&!r.tag&&!r.domEl&&!Array.isArray(r)&&(n=r,o=e.slice(1)),m(N[t]||t,n,o)};return N[t]&&Object.assign(n,N[t]),n},set:(e,t,n)=>(N[t]=n,!0)}),j={signal:t,get:t.get,computed:e=>{const o=t(void 0);return n(()=>{o.value=e()}),o},effect:n,registry:l,element:m,enhance:(e,t={})=>{const o="string"==typeof e?document.querySelector(e):e,r=o.domEl||o;if(!(r instanceof HTMLElement))return null;const s=r.tagName.toLowerCase();let i=p.get(r);i||(i=g(r,s));const{innerText:a,innerHTML:l,...c}=t;return void 0!==a&&("function"==typeof a?n(()=>{r.innerText=a()}):r.innerText=a),void 0!==l&&("function"==typeof l?n(()=>{r.innerHTML=l()}):r.innerHTML=l),Object.keys(c).length>0&&(i.attributes=c),i},tags:T,$:(e,t=document.body)=>{const n="string"==typeof e?t.querySelector(e):e;return n?(Object.defineProperty(n,"content",{value(e,t="inner"){t=t.toLowerCase(),j.tags;const o=n.tagName&&("script"===n.tagName.toLowerCase()||"style"===n.tagName.toLowerCase()),r=(Array.isArray(e)?e:[e]).map(e=>(j.hooks.processChild&&!o&&(e=j.hooks.processChild(e)??e),e.tag&&!e.domEl?m(e.tag,e.attributes||{},e.children||[]).domEl:e.domEl||e)),s="shadow"===t?n.shadowRoot||n.attachShadow({mode:"open"}):n;return"inner"===t||"shadow"===t?s.replaceChildren(...r):"outer"===t?s.replaceWith(...r):"afterbegin"===t?s.prepend(...r):"beforeend"===t?s.append(...r):r.forEach(e=>n.insertAdjacentElement(t,e)),n},configurable:!0,writable:!0}),n):null},hooks:{onNonStandardHref:null,processChild:null,validateUrl:null},internals:{core:s,domToElement:p,wrapDomElement:g,setupChildren:C}};if("undefined"!=typeof module&&module.exports&&(module.exports=j),"undefined"!=typeof window&&(globalThis.Lightview=j,globalThis.addEventListener("click",e=>{const t=e.composedPath().find(e=>{var t,n;return"A"===e.tagName&&(null==(n=null==(t=e.getAttribute)?void 0:t.call(e,"href"))?void 0:n.startsWith("#"))});if(t&&!e.defaultPrevented){const n=t.getAttribute("href");if(n.length>1){const o=n.slice(1),r=t.getRootNode(),s=(r.getElementById?r.getElementById(o):null)||(r.querySelector?r.querySelector(`#${o}`):null);s&&(e.preventDefault(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{s.style.scrollMarginTop="calc(var(--site-nav-height, 0px) + 2rem)",s.scrollIntoView({behavior:"smooth",block:"start",inline:"start"})})}))}}j.hooks.onNonStandardHref&&j.hooks.onNonStandardHref(e)}),"undefined"!=typeof MutationObserver)){const e=(t,n)=>{var o;n(t),null==(o=t.childNodes)||o.forEach(t=>e(t,n)),t.shadowRoot&&e(t.shadowRoot,n)},t=t=>e(t,e=>{var t,n;const o=i.get(e);o&&(null==(t=o.effects)||t.forEach(e=>e.stop()),null==(n=o.onunmount)||n.call(o,e),i.delete(e))}),n=t=>e(t,e=>{var t,n;null==(n=null==(t=i.get(e))?void 0:t.onmount)||n.call(t,e)}),o=new MutationObserver(e=>{e.forEach(e=>{e.removedNodes.forEach(t),e.addedNodes.forEach(n)})}),r=()=>{document.body&&o.observe(document.body,{childList:!0,subtree:!0})};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",r):r()}}();