lego-dom 0.0.9 → 1.0.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 (166) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -0
  3. package/{go.html → cdn.html} +33 -26
  4. package/docs/.vitepress/config.js +39 -1
  5. package/docs/api/directives.md +3 -3
  6. package/docs/api/index.md +1 -1
  7. package/docs/contributing/01-welcome.md +36 -0
  8. package/docs/contributing/02-registry.md +99 -0
  9. package/docs/contributing/03-batcher.md +110 -0
  10. package/docs/contributing/04-reactivity.md +87 -0
  11. package/docs/contributing/05-caching.md +59 -0
  12. package/docs/contributing/06-init.md +125 -0
  13. package/docs/contributing/07-observer.md +69 -0
  14. package/docs/contributing/08-snap.md +126 -0
  15. package/docs/contributing/09-diffing.md +69 -0
  16. package/docs/contributing/10-studs.md +76 -0
  17. package/docs/contributing/11-scanner.md +104 -0
  18. package/docs/contributing/12-render.md +116 -0
  19. package/docs/contributing/13-directives.md +225 -0
  20. package/docs/contributing/14-events.md +57 -0
  21. package/docs/contributing/15-router.md +9 -0
  22. package/docs/contributing/16-state.md +48 -0
  23. package/docs/contributing/17-legodom.md +55 -0
  24. package/docs/contributing/index.md +5 -0
  25. package/docs/examples/form.md +1 -1
  26. package/docs/examples/index.md +1 -1
  27. package/docs/examples/routing.md +4 -4
  28. package/docs/examples/todo-app.md +1 -1
  29. package/docs/guide/cdn-usage.md +8 -0
  30. package/docs/guide/components.md +33 -15
  31. package/docs/guide/directives.md +22 -22
  32. package/docs/guide/getting-started.md +35 -10
  33. package/docs/guide/index.md +3 -3
  34. package/docs/guide/quick-start.md +4 -1
  35. package/docs/guide/reactivity.md +22 -1
  36. package/docs/guide/routing.md +189 -289
  37. package/docs/guide/sfc.md +1 -1
  38. package/docs/guide/templating.md +2 -2
  39. package/docs/index.md +41 -7
  40. package/docs/router/basic-routing.md +103 -0
  41. package/docs/router/cold-entry.md +91 -0
  42. package/docs/router/history.md +69 -0
  43. package/docs/router/index.md +73 -0
  44. package/docs/router/resolver.md +74 -0
  45. package/docs/router/surgical-swaps.md +134 -0
  46. package/examples/vite-app/index.html +4 -12
  47. package/examples/vite-app/package.json +4 -2
  48. package/examples/vite-app/src/app.css +3 -0
  49. package/examples/vite-app/src/app.js +29 -0
  50. package/examples/vite-app/src/components/app-navbar.lego +34 -0
  51. package/examples/vite-app/src/components/customers/customer-details.lego +24 -0
  52. package/examples/vite-app/src/components/customers/customer-orders.lego +21 -0
  53. package/examples/vite-app/src/components/customers/order-list.lego +55 -0
  54. package/examples/vite-app/src/components/greeting-card.lego +1 -1
  55. package/examples/vite-app/src/components/sample-component.lego +15 -15
  56. package/examples/vite-app/src/components/shells/customers-shell.lego +21 -0
  57. package/examples/vite-app/src/components/todo-list.lego +12 -15
  58. package/examples/vite-app/src/components/widgets/user-card.lego +27 -0
  59. package/examples/vite-app/vite.config.js +5 -1
  60. package/main.js +247 -56
  61. package/package.json +1 -1
  62. package/parse-lego.js +17 -8
  63. package/{main.test.js → tests/main.test.js} +34 -17
  64. package/tests/parse-lego.test.js +65 -0
  65. package/vite-plugin.js +60 -22
  66. package/docs/.vitepress/dist/404.html +0 -22
  67. package/docs/.vitepress/dist/api/define.html +0 -35
  68. package/docs/.vitepress/dist/api/directives.html +0 -32
  69. package/docs/.vitepress/dist/api/globals.html +0 -27
  70. package/docs/.vitepress/dist/api/index.html +0 -25
  71. package/docs/.vitepress/dist/api/lifecycle.html +0 -38
  72. package/docs/.vitepress/dist/api/route.html +0 -34
  73. package/docs/.vitepress/dist/api/vite-plugin.html +0 -37
  74. package/docs/.vitepress/dist/assets/api_define.md.UA-ygUnQ.js +0 -11
  75. package/docs/.vitepress/dist/assets/api_define.md.UA-ygUnQ.lean.js +0 -1
  76. package/docs/.vitepress/dist/assets/api_directives.md.BV-D251p.js +0 -8
  77. package/docs/.vitepress/dist/assets/api_directives.md.BV-D251p.lean.js +0 -1
  78. package/docs/.vitepress/dist/assets/api_globals.md.CEznyRAY.js +0 -3
  79. package/docs/.vitepress/dist/assets/api_globals.md.CEznyRAY.lean.js +0 -1
  80. package/docs/.vitepress/dist/assets/api_index.md.IEYUxUIr.js +0 -1
  81. package/docs/.vitepress/dist/assets/api_index.md.IEYUxUIr.lean.js +0 -1
  82. package/docs/.vitepress/dist/assets/api_lifecycle.md.Ccm5xw6-.js +0 -14
  83. package/docs/.vitepress/dist/assets/api_lifecycle.md.Ccm5xw6-.lean.js +0 -1
  84. package/docs/.vitepress/dist/assets/api_route.md.CAHf_KNp.js +0 -10
  85. package/docs/.vitepress/dist/assets/api_route.md.CAHf_KNp.lean.js +0 -1
  86. package/docs/.vitepress/dist/assets/api_vite-plugin.md.DC8Li09k.js +0 -13
  87. package/docs/.vitepress/dist/assets/api_vite-plugin.md.DC8Li09k.lean.js +0 -1
  88. package/docs/.vitepress/dist/assets/app.BfblNDJy.js +0 -1
  89. package/docs/.vitepress/dist/assets/chunks/@localSearchIndexroot.Crdp7-Zp.js +0 -1
  90. package/docs/.vitepress/dist/assets/chunks/VPLocalSearchBox.C18E44rY.js +0 -9
  91. package/docs/.vitepress/dist/assets/chunks/framework.B7OFBR9X.js +0 -19
  92. package/docs/.vitepress/dist/assets/chunks/theme.VX3itTW6.js +0 -2
  93. package/docs/.vitepress/dist/assets/examples_form.md.DQoAgbLR.js +0 -34
  94. package/docs/.vitepress/dist/assets/examples_form.md.DQoAgbLR.lean.js +0 -1
  95. package/docs/.vitepress/dist/assets/examples_index.md.CVJJjXXE.js +0 -28
  96. package/docs/.vitepress/dist/assets/examples_index.md.CVJJjXXE.lean.js +0 -1
  97. package/docs/.vitepress/dist/assets/examples_routing.md.sRnA5RXw.js +0 -338
  98. package/docs/.vitepress/dist/assets/examples_routing.md.sRnA5RXw.lean.js +0 -1
  99. package/docs/.vitepress/dist/assets/examples_sfc-showcase.md.DPf9Wm99.js +0 -13
  100. package/docs/.vitepress/dist/assets/examples_sfc-showcase.md.DPf9Wm99.lean.js +0 -1
  101. package/docs/.vitepress/dist/assets/examples_todo-app.md.CqF4JaWn.js +0 -297
  102. package/docs/.vitepress/dist/assets/examples_todo-app.md.CqF4JaWn.lean.js +0 -1
  103. package/docs/.vitepress/dist/assets/guide_cdn-usage.md.CjIjusre.js +0 -182
  104. package/docs/.vitepress/dist/assets/guide_cdn-usage.md.CjIjusre.lean.js +0 -1
  105. package/docs/.vitepress/dist/assets/guide_components.md.CMU3iM6R.js +0 -174
  106. package/docs/.vitepress/dist/assets/guide_components.md.CMU3iM6R.lean.js +0 -1
  107. package/docs/.vitepress/dist/assets/guide_contributing.md.Crrv3T_0.js +0 -1
  108. package/docs/.vitepress/dist/assets/guide_contributing.md.Crrv3T_0.lean.js +0 -1
  109. package/docs/.vitepress/dist/assets/guide_directives.md.DFwqvqOv.js +0 -140
  110. package/docs/.vitepress/dist/assets/guide_directives.md.DFwqvqOv.lean.js +0 -1
  111. package/docs/.vitepress/dist/assets/guide_getting-started.md.DtaJPe0i.js +0 -107
  112. package/docs/.vitepress/dist/assets/guide_getting-started.md.DtaJPe0i.lean.js +0 -1
  113. package/docs/.vitepress/dist/assets/guide_index.md.DtJVpLI9.js +0 -2
  114. package/docs/.vitepress/dist/assets/guide_index.md.DtJVpLI9.lean.js +0 -1
  115. package/docs/.vitepress/dist/assets/guide_lifecycle.md.CfY3jlU1.js +0 -304
  116. package/docs/.vitepress/dist/assets/guide_lifecycle.md.CfY3jlU1.lean.js +0 -1
  117. package/docs/.vitepress/dist/assets/guide_quick-start.md.CwdNNA21.js +0 -33
  118. package/docs/.vitepress/dist/assets/guide_quick-start.md.CwdNNA21.lean.js +0 -1
  119. package/docs/.vitepress/dist/assets/guide_reactivity.md.DgTH0MTn.js +0 -135
  120. package/docs/.vitepress/dist/assets/guide_reactivity.md.DgTH0MTn.lean.js +0 -1
  121. package/docs/.vitepress/dist/assets/guide_routing.md.nMB0QOBR.js +0 -193
  122. package/docs/.vitepress/dist/assets/guide_routing.md.nMB0QOBR.lean.js +0 -1
  123. package/docs/.vitepress/dist/assets/guide_sfc.md.BUkWma1z.js +0 -187
  124. package/docs/.vitepress/dist/assets/guide_sfc.md.BUkWma1z.lean.js +0 -1
  125. package/docs/.vitepress/dist/assets/guide_templating.md.XI3uUlYI.js +0 -119
  126. package/docs/.vitepress/dist/assets/guide_templating.md.XI3uUlYI.lean.js +0 -1
  127. package/docs/.vitepress/dist/assets/index.md.M4_o26kF.js +0 -23
  128. package/docs/.vitepress/dist/assets/index.md.M4_o26kF.lean.js +0 -1
  129. package/docs/.vitepress/dist/assets/inter-italic-cyrillic-ext.r48I6akx.woff2 +0 -0
  130. package/docs/.vitepress/dist/assets/inter-italic-cyrillic.By2_1cv3.woff2 +0 -0
  131. package/docs/.vitepress/dist/assets/inter-italic-greek-ext.1u6EdAuj.woff2 +0 -0
  132. package/docs/.vitepress/dist/assets/inter-italic-greek.DJ8dCoTZ.woff2 +0 -0
  133. package/docs/.vitepress/dist/assets/inter-italic-latin-ext.CN1xVJS-.woff2 +0 -0
  134. package/docs/.vitepress/dist/assets/inter-italic-latin.C2AdPX0b.woff2 +0 -0
  135. package/docs/.vitepress/dist/assets/inter-italic-vietnamese.BSbpV94h.woff2 +0 -0
  136. package/docs/.vitepress/dist/assets/inter-roman-cyrillic-ext.BBPuwvHQ.woff2 +0 -0
  137. package/docs/.vitepress/dist/assets/inter-roman-cyrillic.C5lxZ8CY.woff2 +0 -0
  138. package/docs/.vitepress/dist/assets/inter-roman-greek-ext.CqjqNYQ-.woff2 +0 -0
  139. package/docs/.vitepress/dist/assets/inter-roman-greek.BBVDIX6e.woff2 +0 -0
  140. package/docs/.vitepress/dist/assets/inter-roman-latin-ext.4ZJIpNVo.woff2 +0 -0
  141. package/docs/.vitepress/dist/assets/inter-roman-latin.Di8DUHzh.woff2 +0 -0
  142. package/docs/.vitepress/dist/assets/inter-roman-vietnamese.BjW4sHH5.woff2 +0 -0
  143. package/docs/.vitepress/dist/assets/style.eycE2Jhw.css +0 -1
  144. package/docs/.vitepress/dist/examples/form.html +0 -58
  145. package/docs/.vitepress/dist/examples/index.html +0 -52
  146. package/docs/.vitepress/dist/examples/routing.html +0 -362
  147. package/docs/.vitepress/dist/examples/sfc-showcase.html +0 -37
  148. package/docs/.vitepress/dist/examples/todo-app.html +0 -321
  149. package/docs/.vitepress/dist/guide/cdn-usage.html +0 -206
  150. package/docs/.vitepress/dist/guide/components.html +0 -198
  151. package/docs/.vitepress/dist/guide/contributing.html +0 -25
  152. package/docs/.vitepress/dist/guide/directives.html +0 -164
  153. package/docs/.vitepress/dist/guide/getting-started.html +0 -131
  154. package/docs/.vitepress/dist/guide/index.html +0 -26
  155. package/docs/.vitepress/dist/guide/lifecycle.html +0 -328
  156. package/docs/.vitepress/dist/guide/quick-start.html +0 -57
  157. package/docs/.vitepress/dist/guide/reactivity.html +0 -159
  158. package/docs/.vitepress/dist/guide/routing.html +0 -217
  159. package/docs/.vitepress/dist/guide/sfc.html +0 -211
  160. package/docs/.vitepress/dist/guide/templating.html +0 -143
  161. package/docs/.vitepress/dist/hashmap.json +0 -1
  162. package/docs/.vitepress/dist/index.html +0 -47
  163. package/docs/.vitepress/dist/logo.svg +0 -38
  164. package/docs/.vitepress/dist/vp-icons.css +0 -1
  165. package/examples/vite-app/src/main.js +0 -11
  166. package/examples.js +0 -99
package/CHANGELOG.md ADDED
@@ -0,0 +1,44 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## [1.0.0] - 2026-01-10
6
+
7
+ **The Launch Release!** 🚀
8
+ LegoDOM moves out of beta with a finalized API, robust routing, and a hybrid rendering engine.
9
+
10
+ ### 🌟 Major features
11
+
12
+ - **Surgical Routing:** Introduced a groundbreaking `b-target` attribute that allows any link to update any part of the page without a full reload.
13
+ - **Smart History:** The router now tracks surgical updates in `history.state`, correctly restoring "fragment" states when using the Back/Forward buttons.
14
+ - **Persistent Layouts:** Support for "Holy Grail" layouts where sidebars never reload or lose state (scroll position, inputs) while main content changes.
15
+ - **Hybrid Rendering Engine:**
16
+ - **Light DOM Support:** The engine now hydrates `{{mustaches}}` in `index.html` and Light DOM slots, not just inside Shadow Roots.
17
+ - **Global Reactivity:** Components now automatically broadcast global state changes (like URL params) to all active subscribers.
18
+ - **Optimized Updates:** A dependency tracking system ensures only components that *use* global state are re-rendered.
19
+ - **Developer Experience (DX):**
20
+ - **Automatic Injection:** `$route` and `$go` are now injected into every component's script scope (`this.$route`, `this.$go`), removing the need for `Lego.globals.xxx`.
21
+ - **Cleaner Templates:** Template expressions now support `$route` directly (`{{ $route.params.id }}`) without `global.` prefix.
22
+ - **HMR 2.0:** The Vite plugin now correctly handles adding/deleting `.lego` files and performs smarter hot updates.
23
+
24
+ ### ⚡ Improvements
25
+
26
+ - **Router:**
27
+ - Exposed `$go(path, ...targets).get()` for programmatic surgical navigation.
28
+ - Fixed `TypeError` where `$go` was not found in component scopes.
29
+ - Support for multiple URL parameters (e.g., `/customers/:id/orders/:orderId`).
30
+ - Defaults `b-link` to `true` (always push history) unless explicitly set to `false`.
31
+ - **Core:**
32
+ - `Lego.init()` is now required to start the engine, allowing for explicit control over startup timing.
33
+ - `e.composedPath()` is used for event delegation, allowing links inside Shadow DOM to trigger the global router.
34
+ - Fixed `b-sync` losing reactivity inside `b-for` loops.
35
+ - Fixed hydration of attributes like `href="/user/{{id}}"`.
36
+ - **Docs:**
37
+ - Complete overhaul of Routing guide with "Surgical Swaps", "Deep Linking", and "Self-Healing" patterns.
38
+ - Clarified component naming conventions (Filename for Vite vs. `b-id` for CDN).
39
+
40
+ ### 🐛 Bug Fixes
41
+
42
+ - Fixed "Literal Mustaches" appearing in `href` and text content on initial load.
43
+ - Fixed Deep Linking where hitting Refresh on a sub-route would render an empty shell (addressed via Self-Healing pattern).
44
+ - Fixed an issue where `Lego.globals` changes triggered a full re-render of unrelated components.
package/README.md CHANGED
@@ -14,6 +14,7 @@ Lego embraces the web platform. It turns standard HTML `<template>` tags into re
14
14
  - 📦 **Zero Dependencies** – Weighs less than 4kb gzipped.
15
15
  - 🛠️ **No Build Step** – Works directly in the browser with standard `<script>` tags.
16
16
  - 🧩 **Native Web Components** – Real Custom Elements, real Shadow DOM.
17
+ - 🌐 **Built-in Routing** – Lego Router included for client-side routing.
17
18
  - 📝 **Familiar Mentals** – Plain JavaScript objects for state, plain HTML for templates.
18
19
 
19
20
  ---
@@ -8,7 +8,14 @@
8
8
  </head>
9
9
 
10
10
  <body @todo-added="() => {console.log('Todo added!')}">
11
- <template b-id="todo-list">
11
+ <template b-id="todo-list" b-data="{
12
+ title: 'My Todo List',
13
+ items: [],
14
+ newItem: '',
15
+ mounted() {
16
+ console.log('Todo list mounted!');
17
+ }
18
+ }">
12
19
  <style>
13
20
  :host {
14
21
  display: block;
@@ -52,14 +59,13 @@
52
59
  <h3>{{title}}</h3>
53
60
  <p>{{ items.filter(t => !t.done).length }} of {{ items.length }} items remaining</p>
54
61
  <div style="margin-bottom: 20px;">
55
- <input b-sync="newItem" placeholder="Add task..." class="input" @keydown="() => {
56
- }">
62
+ <input b-sync="newItem" placeholder="Add task..." class="input">
57
63
  <button @click="() => {
58
- if(!newItem.trim()) return;
59
- items.push({text: `${newItem} - ${items.length + 1} - ${$ancestors('user-card').name}`, done: false});
60
- newItem = '';
61
- $emit('todo-added', { item: newItem });
62
- }">Add</button>
64
+ if(!newItem.trim()) return;
65
+ items.push({text: `${newItem} - ${items.length + 1}`, done: false});
66
+ newItem = '';
67
+ $emit('todo-added', { item: newItem });
68
+ }">Add</button>
63
69
  </div>
64
70
 
65
71
  <div b-for="todo in items">
@@ -70,7 +76,10 @@
70
76
  </div>
71
77
  </template>
72
78
 
73
- <template b-id="user-card">
79
+ <template b-id="user-card" b-data="{
80
+ name: 'Anonymous',
81
+ bio: 'No bio provided'
82
+ }">
74
83
  <style>
75
84
  :host {
76
85
  display: block;
@@ -78,6 +87,7 @@
78
87
  padding: 20px;
79
88
  border: 1px solid #ccc;
80
89
  border-radius: 8px;
90
+ margin-bottom: 20px;
81
91
  }
82
92
 
83
93
  h3 {
@@ -91,25 +101,22 @@
91
101
  <slot></slot>
92
102
  </template>
93
103
 
104
+ <!-- Using defaults -->
105
+ <user-card>
106
+ <p>This user uses default data from the template.</p>
107
+ </user-card>
108
+
109
+ <!-- Overriding defaults -->
94
110
  <user-card b-data="{
95
- name: 'John Doe',
96
- bio: 'Software Engineer'
97
- }">
98
- <p>Additional content here</p>
99
- <todo-list b-data="{
100
- title: 'Enterprise Todo List',
101
- items: [{text: 'Fix b-for strikethrough', done: true}],
102
- newItem: '',
103
- mounted() {
104
- console.log('THis lego block has been mounted!');
105
- },
106
- updated() {
107
- console.log('This lego block has been updated!');
108
- },
109
- unmounted() {
110
- console.log('This lego block has been unmounted!');
111
- }
111
+ name: 'John Doe',
112
+ bio: 'Software Engineer'
112
113
  }">
114
+ <p>This user overrides the defaults.</p>
115
+
116
+ <todo-list b-data="{
117
+ title: 'Work Tasks',
118
+ items: [{text: 'Implement template defaults', done: true}]
119
+ }">
113
120
  </todo-list>
114
121
  </user-card>
115
122
  </body>
@@ -10,10 +10,12 @@ export default defineConfig({
10
10
 
11
11
  nav: [
12
12
  { text: 'Guide', link: '/guide/' },
13
+ { text: 'Contributing', link: '/contributing/' },
13
14
  { text: 'API', link: '/api/' },
14
15
  { text: 'Examples', link: '/examples/' },
16
+ { text: 'Router', link: '/router/' },
15
17
  {
16
- text: 'v0.0.7',
18
+ text: 'v1.0.0',
17
19
  items: [
18
20
  { text: 'Changelog', link: 'https://github.com/rayattack/LegoJS/releases' }
19
21
 
@@ -22,6 +24,30 @@ export default defineConfig({
22
24
  ],
23
25
 
24
26
  sidebar: {
27
+ '/contributing/': [
28
+ {
29
+ text: 'Contributing',
30
+ items: [
31
+ { text: 'Topic 1 - Welcome', link: '/contributing/01-welcome' },
32
+ { text: 'Topic 2 - The Registry', link: '/contributing/02-registry' },
33
+ { text: 'Topic 3 - Batching', link: '/contributing/03-batcher' },
34
+ { text: 'Topic 4 - Reactivity', link: '/contributing/04-reactivity' },
35
+ { text: 'Topic 5 - Caching', link: '/contributing/05-caching' },
36
+ { text: 'Topic 6 - LegoDOM Init', link: '/contributing/06-init' },
37
+ { text: 'Topic 7 - Observer', link: '/contributing/07-observer' },
38
+ { text: 'Topic 8 - Snap', link: '/contributing/08-snap' },
39
+ { text: 'Topic 9 - Diffing', link: '/contributing/09-diffing' },
40
+ { text: 'Topic 10 - State', 'link': '/contributing/10-studs' },
41
+ { text: 'Topic 11 - Scanner', 'link': '/contributing/11-scanner' },
42
+ { text: 'Topic 12 - Render', 'link': '/contributing/12-render' },
43
+ { text: 'Topic 13 - Directives', 'link': '/contributing/13-directives' },
44
+ { text: 'Topic 14 - Events', 'link': '/contributing/14-events' },
45
+ { text: 'Topic 15 - Router', 'link': '/contributing/15-router' },
46
+ { text: 'Topic 16 - State', 'link': '/contributing/16-state' },
47
+ { text: 'Topic 17 - LegoDOM', 'link': '/contributing/17-legodom' },
48
+ ]
49
+ }
50
+ ],
25
51
  '/guide/': [
26
52
  {
27
53
  text: 'Introduction',
@@ -65,6 +91,18 @@ export default defineConfig({
65
91
  ]
66
92
  }
67
93
  ],
94
+ '/router/': [
95
+ {
96
+ text: 'LegoDOM Router',
97
+ items: [
98
+ { text: 'About', link: '/router/' },
99
+ { text: 'Basic Routing', link: '/router/basic-routing' },
100
+ { text: 'Surgical Swaps', link: '/router/surgical-swaps' },
101
+ { text: 'Cold Entry', link: '/router/cold-entry' },
102
+ { text: 'History', link: '/router/history' }
103
+ ]
104
+ }
105
+ ],
68
106
  '/examples/': [
69
107
  {
70
108
  text: 'Examples',
@@ -2,13 +2,13 @@
2
2
 
3
3
  Special attributes that control DOM behavior.
4
4
 
5
- ## b-if
5
+ ## b-show
6
6
 
7
7
  Conditionally render an element.
8
8
 
9
9
  ```html
10
- <div b-if="loading">Loading...</div>
11
- <div b-if="!loading">Content loaded!</div>
10
+ <div b-show="loading">Loading...</div>
11
+ <div b-show="!loading">Content loaded!</div>
12
12
  ```
13
13
 
14
14
  ## b-for
package/docs/api/index.md CHANGED
@@ -11,7 +11,7 @@ Welcome to the Lego API documentation.
11
11
 
12
12
  ## Templates & Binding
13
13
 
14
- - [Directives](/api/directives) - `b-if`, `b-for`, `b-sync`
14
+ - [Directives](/api/directives) - `b-show`, `b-for`, `b-sync`
15
15
 
16
16
  ## Browser Support
17
17
 
@@ -0,0 +1,36 @@
1
+ # Topic 1: The Module Pattern & Private Scope
2
+
3
+ LegoDOM is wrapped in an **IIFE** (Immediately Invoked Function Expression) assigned to `const Lego`. This creates a closure, meaning any variable declared at the top (like `registry` or `proxyCache`) is "private"—it cannot be accessed or tampered with from the browser console unless explicitly exposed.
4
+
5
+ ```js
6
+ const Lego = (() => {
7
+ // ... all the logic ...
8
+ return {
9
+ init: () => { ... },
10
+ define: (tagName, templateHTML, logic = {}) => { ... },
11
+ // ...
12
+ };
13
+ })();
14
+
15
+ if (typeof window !== 'undefined') {
16
+ document.addEventListener('DOMContentLoaded', Lego.init);
17
+ window.Lego = Lego;
18
+ }
19
+ ```
20
+
21
+ ### Why Not Modular ES6?
22
+
23
+ I started with an **IIFE** and underestimated how big it could grow. It might be a better idea to use ES6 modules, but I'm too lazy to refactor it at the moment.
24
+
25
+ ### The use of `WeakMap`
26
+
27
+ You’ll notice the use of `WeakMap` for `proxyCache`, `privateData`, and `forPools`.
28
+
29
+ - **Why not a regular Map?** A `WeakMap` allows the keys (which are DOM elements in this code) to be **garbage collected** if the element is removed from the DOM.
30
+
31
+ - **Memory Leak Prevention:** If we used a regular `Map`, the library would hold a reference to every component ever created, even if you deleted them, eventually crashing the browser tab.
32
+
33
+
34
+ ### Internal Registry
35
+
36
+ `const registry = {}` acts as the library's "brain." It stores the `<template>` elements that define what a component looks like. When you write `<my-button>`, Lego looks into this object to find the blueprint.
@@ -0,0 +1,99 @@
1
+ # The Good Ole Registry (Lego Basket)
2
+
3
+ Let's not keep our toys everywhere, let's be good citizens and put them in a basket.
4
+
5
+ PSS!!! Come here lemme tell you a secret - are you a frontend developer? "The DOM is not your enemy"
6
+ we talk about Light DOM and Shadow DOM in a minute ;-).
7
+
8
+
9
+ ## Topic 2: The Registry & Internal Storage
10
+
11
+ LegoDOM uses three specialized collections to store the "DNA" of your application. This separation allows the framework to distinguish between what a component **looks like** versus how it **behaves**.
12
+
13
+ ```js
14
+ const registry = {};
15
+ const sfcLogic = new Map();
16
+ const sharedStates = new Map();
17
+ ```
18
+
19
+ ### 1. The HTML Blueprint Collection (`registry`)
20
+
21
+ `const registry = {}` is a plain object that stores references to `<template>` elements.
22
+
23
+ - When the library initializes, it scans the DOM for any `<template b-id="my-component">` and saves it here.
24
+
25
+ - The `b-id` becomes the key, and the DOM node itself is the value.
26
+
27
+ - **Purpose:** This is the "Light DOM" source used to populate the "Shadow DOM" later during the "snapping" process.
28
+
29
+
30
+ ### 2. The SFC Logic Collection (`sfcLogic`)
31
+
32
+ `const sfcLogic = new Map();` stores the JavaScript objects passed into `Lego.define()`.
33
+
34
+ - While `registry` holds the HTML/CSS, `sfcLogic` holds the functions like `mounted()`, `updated()`, or custom methods.
35
+
36
+ - **Why a Map?** Unlike a plain object, a `Map` is more performant for frequent lookups by string keys (tag names) - I think!!! or maybe I read wrong (call me out).
37
+
38
+
39
+ ### 3. The Singleton States Collection (`sharedStates`)
40
+
41
+ `const sharedStates = new Map();` is one of the most powerful "hidden" features of LegoDOM.
42
+
43
+ - Every time you define a component, Lego creates a **reactive version** of its logic and stores it here.
44
+
45
+ - This allows other components to access a specific component's state globally via the `$registry('tag-name')` helper. **NOTE** the component's (template/blueprint) state, not the instance state.
46
+
47
+ - **Example:** If you have 3 `user-profile` components, any other component on the page can peek at their (shared) state data by asking the `sharedStates` map.
48
+
49
+
50
+ #### Dissecting Registration
51
+
52
+ The `registry` doesn't just wait for you to type; it's fed by three distinct streams across 2 paradigms.
53
+
54
+ **Paradigm 1: Explicitly**
55
+
56
+ ```js
57
+ const sfcLogic = new Map(); // Specifically for SFC script logic
58
+ // ...
59
+ define: (tagName, templateHTML, logic = {}) => {
60
+ const t = document.createElement('template');
61
+ // ... stores template in registry
62
+ sfcLogic.set(tagName, logic); // Stores the JS part separately
63
+ }
64
+ ```
65
+
66
+ **Paradigm 2: Implicitly**
67
+
68
+ ```js
69
+ // vite-plugin.js
70
+ async buildStart() {
71
+ const root = config?.root || process.cwd();
72
+ legoFiles = await fg(include, { cwd: searchPath, absolute: true }); // Scans for .lego files
73
+ }
74
+ // ...
75
+ async load(id) {
76
+ if (id.endsWith('.lego')) {
77
+ const defineCall = generateDefineCall(parsed); // Converts .lego file to Lego.define()
78
+ return `import { Lego } from 'lego-dom/main.js';\n${defineCall}`;
79
+ }
80
+ }
81
+
82
+ ```
83
+
84
+ **The Three Ways to Register:**
85
+ 1. **The HTML Manual Method:** You put `<template b-id="my-comp">` directly in your `*.html` files. During `Lego.init()`, the library scrapes these and populates the registry. This is great for "no-build" prototypes.
86
+
87
+ 2. **The `Lego.define()` JS Method:** You call `Lego.define('my-comp', '<h1>Hi</h1>', { ... logic })` in a standard JavaScript file.
88
+
89
+ 3. **The SFC Automatic Method (The "Vite Way"):** * The **Vite Plugin** (as seen in `vite-plugin.js`) acts as a build-time robot.
90
+
91
+ - It uses `fast-glob` (`fg`) to scan your entire `src/components` directory for any file ending in `.lego`.
92
+
93
+ - It parses the `<template>` and `<script>` inside that `.lego` file.
94
+
95
+ - It **injects** a `Lego.define()` call into your JavaScript bundle automatically.
96
+
97
+ - **Result:** You just create a file named `UserCard.lego`, and suddenly `<user-card>` is a valid HTML tag in your app.
98
+
99
+ **Key Insight:** Notice in `main.js` how `define` uses `sfcLogic.set(tagName, logic)`. This is where the plugin "parks" your component's JavaScript code so that when the component "snaps" (Topic 23), it can find its specific logic.
@@ -0,0 +1,110 @@
1
+ # Batching, Scheduling, and doing things the right way
2
+
3
+ Say you are building the next big thing, if you update checkboxes, input fields a 100 times,
4
+ you don't want the DOM to re-render 100 times. That would be a performance nightmare.
5
+ LegoDOM uses Batching & Scheduling to do things the right way.
6
+
7
+
8
+ ## Topic 3: The Global Batcher & Scheduler
9
+
10
+ When you change data in a reactive application, you often change multiple things at once (e.g., updating a user's name, age, and profile picture). Without a **Batcher**, the browser would try to re-render the HTML every single time one of those properties changed. This would cause "jank" (stuttering) and poor performance.
11
+
12
+ ### The `createBatcher` Factory
13
+
14
+ The library defines `createBatcher` as a closure that manages the update cycle. It provides three critical layers of protection:
15
+
16
+ ```js
17
+ const createBatcher = () => {
18
+ let queued = false;
19
+ const componentsToUpdate = new Set();
20
+ let isProcessing = false;
21
+
22
+ return {
23
+ add: (el) => {
24
+ if (!el || isProcessing) return;
25
+ componentsToUpdate.add(el);
26
+ if (queued) return;
27
+ queued = true;
28
+
29
+ requestAnimationFrame(() => {
30
+ isProcessing = true;
31
+ const batch = Array.from(componentsToUpdate);
32
+ componentsToUpdate.clear();
33
+ queued = false;
34
+
35
+ batch.forEach(el => render(el));
36
+
37
+ setTimeout(() => {
38
+ batch.forEach(el => {
39
+ const state = el._studs;
40
+ if (state && typeof state.updated === 'function') {
41
+ try {
42
+ state.updated.call(state);
43
+ } catch (e) {
44
+ console.error(`[Lego] Error in updated hook:`, e);
45
+ }
46
+ }
47
+ });
48
+ isProcessing = false;
49
+ }, 0);
50
+ });
51
+ }
52
+ };
53
+ };
54
+
55
+ const globalBatcher = createBatcher();
56
+ ```
57
+
58
+ 1. **Deduplication with `Set`**:
59
+
60
+ - The batcher maintains a `componentsToUpdate = new Set()`.
61
+
62
+ - Because a `Set` only stores unique values, if you trigger an update on the same component 50 times in a single loop, it is only added to the "todo" list **once**.
63
+
64
+ 2. **The `queued` Gatekeeper**:
65
+
66
+ - A boolean flag `queued` prevents multiple update cycles from being scheduled simultaneously.
67
+
68
+ - Once the first change hits the batcher, it "locks the gate," schedules the work, and ignores further requests to start a new cycle until the current one begins.
69
+
70
+ 3. **The `isProcessing` Lock**:
71
+
72
+ - This flag ensures that if a component’s state changes _while_ the render is actually happening, it doesn't cause a collision or infinite loop.
73
+
74
+
75
+ ### Timing: `requestAnimationFrame` (rAF)
76
+
77
+ Instead of updating immediately, the library uses `requestAnimationFrame`.
78
+
79
+ - **What it does**: It tells the browser, "Wait until you are just about to draw the next frame on the screen, then run this code".
80
+
81
+ - **Efficiency**: It bundles every single change from every component into a single "tick."
82
+
83
+ - **The Benefit**: This syncs your JavaScript logic with the monitor's refresh rate (usually 60 times per second), making animations and updates look buttery smooth.
84
+
85
+
86
+ ### The Execution Phase
87
+
88
+ When the "frame" triggers, the batcher:
89
+
90
+ 1. Takes a snapshot of the `Set`.
91
+
92
+ 2. Clears the `Set` for the next round.
93
+
94
+ 3. Runs `render(el)` for every component in that batch.
95
+
96
+
97
+ ### The `updated` Lifecycle Hook
98
+
99
+ After the render is complete, the batcher uses a `setTimeout(() => ..., 0)`.
100
+
101
+ - **The Trick**: Even with a delay of `0`, this "macro-task" ensures the code inside runs **after** the browser has finished its rendering work.
102
+
103
+ - **The Hook**: It looks for `our` lifecycle hook function a.k.a or notoriously known as `updated`
104
+ in each component's state (`_studs`) and executes it. This is the perfect place for us to run code that needs to measure the new size of an element or scroll a list to the bottom.
105
+
106
+ **Example**
107
+ If you have a `chat-box` component and you update the messages, you might use the `updated()` hook to scroll to the bottom. Because of this batcher, you are guaranteed that the DOM has finished changing before your scroll logic runs.
108
+
109
+
110
+ > **Visualizing the flow:** State Change -> `batcher.add(el)` -> `Set` collects `el` -> `rAF` triggers -> `render(el)` runs -> `updated()` hook fires.
@@ -0,0 +1,87 @@
1
+ # Reacting to stimuli is how we react to stimuli
2
+
3
+ If living things react to stimuli, then so should our components.
4
+
5
+
6
+ ## Topic 4: Reactivity (The Proxy)
7
+
8
+ LegoDOM uses the JavaScript **`Proxy`** object to create its reactivity. Think of a Proxy as a "security guard" that sits in front of your data object. Every time you try to read or change a property, the guard intercepts the request.
9
+
10
+ ### The `reactive(obj, el, batcher)` Function
11
+
12
+ When a component is "snapped" (created), its data is passed through this function.
13
+
14
+ ```js
15
+ //... rest of the code
16
+ const reactive = (obj, el, batcher = globalBatcher) => {
17
+ if (obj === null || typeof obj !== 'object' || obj instanceof Node) return obj;
18
+ if (proxyCache.has(obj)) return proxyCache.get(obj);
19
+
20
+ const handler = {
21
+ get: (t, k) => {
22
+ const val = Reflect.get(t, k);
23
+ if (val !== null && typeof val === 'object' && !(val instanceof Node)) {
24
+ return reactive(val, el, batcher);
25
+ }
26
+ return val;
27
+ },
28
+ set: (t, k, v) => {
29
+ const old = t[k];
30
+ const r = Reflect.set(t, k, v);
31
+ if (old !== v) batcher.add(el);
32
+ return r;
33
+ },
34
+ deleteProperty: (t, k) => {
35
+ const r = Reflect.deleteProperty(t, k);
36
+ batcher.add(el);
37
+ return r;
38
+ }
39
+ };
40
+
41
+ const p = new Proxy(obj, handler);
42
+ proxyCache.set(obj, p);
43
+ return p;
44
+ };
45
+
46
+ //... rest of the code
47
+ ```
48
+
49
+ 1. **The Traps (`get` and `set`)**:
50
+
51
+ - **The `get` trap**: When you access a property (e.g., `state.count`), the Proxy checks if that property is _also_ an object. If it is, it recursively wraps that object in a Proxy too. This ensures that "deep" data like `user.profile.name` is also reactive.
52
+
53
+ - **The `set` trap**: This is the trigger. When you do `state.count = 5`, the Proxy compares the `old` value with the `new` value. If they are different, it immediately calls `batcher.add(el)`.
54
+
55
+ - **The `deleteProperty` trap**: Even if you delete a key (e.g., `delete state.tempData`), the Proxy intercepts this and tells the batcher to re-render the UI.
56
+
57
+ 2. **Handling Objects vs. Nodes**:
58
+
59
+ - The code explicitly checks if a value is an `instanceof Node`. If you try to store a raw HTML element in your state, the library **will not** wrap it in a Proxy. This prevents the library from accidentally trying to "observe" the entire DOM tree, which would crash the browser.
60
+
61
+
62
+ ### Concrete Example
63
+
64
+ Imagine you have a component defined like this:
65
+
66
+ ```js
67
+ Lego.define('counter-app', '<h1>{{count}}</h1>', {
68
+ count: 0,
69
+ increment() { this.count++; }
70
+ });
71
+
72
+ ```
73
+
74
+ - **Step A**: Lego takes that object `{ count: 0, ... }` and wraps it in a Proxy.
75
+
76
+ - **Step B**: You call `increment()`.
77
+
78
+ - **Step C**: The line `this.count++` triggers the Proxy's `set` trap.
79
+
80
+ - **Step D**: The `set` trap notices `0` is now `1` and calls `globalBatcher.add(thisElement)`.
81
+
82
+ - **Step E**: The Batcher (from Topic 3) schedules a render for the next animation frame.
83
+
84
+
85
+ ### Why this is "Surgical"
86
+
87
+ Because the `reactive` function is passed the specific element (`el`) it belongs to, it knows exactly which component in the DOM needs to re-render. It doesn't have to guess or refresh the whole page; it targets the specific "Lego block" that owns that data.
@@ -0,0 +1,59 @@
1
+ # There are 2 hard things in computer science
2
+
3
+ - cache invalidation
4
+ - naming things
5
+ - off-by-one errors
6
+
7
+
8
+ ## Proxy Caching (`proxyCache`)
9
+
10
+ In [Topic 4](/contributing/04-reactivity), we saw how `reactive()` wraps objects in a Proxy.
11
+ However, a common issue in reactive programming is trying to wrap the same object multiple
12
+ times, or dealing with circular references
13
+ (e.g. Object A points to Object B, and Object B points back to Object A).
14
+
15
+ ### The Problem: Infinite Recursion
16
+
17
+ Without a cache, every time you access a nested object, the `get` trap would create a **new** Proxy wrapper.
18
+
19
+ ```js
20
+ // Without a cache:
21
+ const p1 = state.user;
22
+ const p2 = state.user;
23
+ console.log(p1 === p2); // false! They are different "guards" for the same data.
24
+
25
+ ```
26
+
27
+ This wastes memory and breaks object identity. Even worse, if an object points to itself, the code would keep creating Proxies until the browser crashed with a "Maximum call stack size exceeded" error.
28
+
29
+ ### The Solution: `proxyCache`
30
+
31
+ The library uses `const proxyCache = new WeakMap()` to keep track of every object it has already turned into a Proxy.
32
+
33
+ 1. **Checking the Map**: At the very start of the `reactive()` function, the code checks: `if (proxyCache.has(obj)) return proxyCache.get(obj);`.
34
+
35
+ 2. **Storing the Result**: If it's a new object, the code creates the Proxy and then immediately saves it: `proxyCache.set(obj, p);`.
36
+
37
+ 3. **The Result**: If you access `state.user` 100 times, you get the exact same Proxy instance every time. It ensures that `p1 === p2` is always `true`.
38
+
39
+
40
+ ### Why a `WeakMap`?
41
+
42
+ This is a critical "expert-level" choice.
43
+
44
+ - A regular `Map` holds a "strong reference" to its keys. If you deleted a piece of data from your state, but that data was still a key in a regular `Map`, the browser could never delete it from memory.
45
+
46
+ - Because `proxyCache` is a `WeakMap`, as soon as your component is destroyed and the original object is no longer needed, the browser’s Garbage Collector can automatically wipe it from the cache.
47
+
48
+
49
+ ### Summary of Logic:
50
+
51
+ - **Step 1:** Request to make `obj` reactive.
52
+
53
+ - **Step 2:** Check `proxyCache`. Found it? Return the existing Proxy.
54
+
55
+ - **Step 3:** Not found? Create a new Proxy.
56
+
57
+ - **Step 4:** Store `obj -> Proxy` in `proxyCache`.
58
+
59
+ - **Step 5:** Return the new Proxy.