lego-dom 1.3.4 → 1.4.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 (91) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/main.js +24 -3
  3. package/package.json +1 -1
  4. package/vite-plugin.js +0 -14
  5. package/.github/workflows/deploy-docs.yml +0 -56
  6. package/.legodom +0 -87
  7. package/docs/.vitepress/config.js +0 -161
  8. package/docs/api/config.md +0 -95
  9. package/docs/api/define.md +0 -58
  10. package/docs/api/directives.md +0 -50
  11. package/docs/api/globals.md +0 -29
  12. package/docs/api/index.md +0 -30
  13. package/docs/api/lifecycle.md +0 -40
  14. package/docs/api/route.md +0 -37
  15. package/docs/api/vite-plugin.md +0 -58
  16. package/docs/contributing/01-welcome.md +0 -38
  17. package/docs/contributing/02-registry.md +0 -133
  18. package/docs/contributing/03-batcher.md +0 -110
  19. package/docs/contributing/04-reactivity.md +0 -87
  20. package/docs/contributing/05-caching.md +0 -59
  21. package/docs/contributing/06-init.md +0 -136
  22. package/docs/contributing/07-observer.md +0 -72
  23. package/docs/contributing/08-snap.md +0 -140
  24. package/docs/contributing/09-diffing.md +0 -69
  25. package/docs/contributing/10-studs.md +0 -78
  26. package/docs/contributing/11-scanner.md +0 -117
  27. package/docs/contributing/12-render.md +0 -138
  28. package/docs/contributing/13-directives.md +0 -243
  29. package/docs/contributing/14-events.md +0 -57
  30. package/docs/contributing/15-router.md +0 -57
  31. package/docs/contributing/16-state.md +0 -47
  32. package/docs/contributing/17-legodom.md +0 -48
  33. package/docs/contributing/index.md +0 -24
  34. package/docs/examples/form.md +0 -42
  35. package/docs/examples/index.md +0 -104
  36. package/docs/examples/routing.md +0 -409
  37. package/docs/examples/sfc-showcase.md +0 -34
  38. package/docs/examples/todo-app.md +0 -383
  39. package/docs/guide/cdn-usage.md +0 -354
  40. package/docs/guide/components.md +0 -418
  41. package/docs/guide/directives.md +0 -539
  42. package/docs/guide/directory-structure.md +0 -248
  43. package/docs/guide/faq.md +0 -210
  44. package/docs/guide/getting-started.md +0 -262
  45. package/docs/guide/index.md +0 -88
  46. package/docs/guide/lifecycle.md +0 -525
  47. package/docs/guide/quick-start.md +0 -49
  48. package/docs/guide/reactivity.md +0 -415
  49. package/docs/guide/routing.md +0 -334
  50. package/docs/guide/server-side.md +0 -134
  51. package/docs/guide/sfc.md +0 -464
  52. package/docs/guide/templating.md +0 -388
  53. package/docs/index.md +0 -160
  54. package/docs/public/logo.svg +0 -17
  55. package/docs/router/basic-routing.md +0 -103
  56. package/docs/router/cold-entry.md +0 -91
  57. package/docs/router/history.md +0 -69
  58. package/docs/router/index.md +0 -73
  59. package/docs/router/resolver.md +0 -74
  60. package/docs/router/surgical-swaps.md +0 -134
  61. package/docs/tutorial/01-project-setup.md +0 -152
  62. package/docs/tutorial/02-your-first-component.md +0 -226
  63. package/docs/tutorial/03-adding-routes.md +0 -279
  64. package/docs/tutorial/04-multi-page-app.md +0 -329
  65. package/docs/tutorial/05-state-and-globals.md +0 -285
  66. package/docs/tutorial/index.md +0 -40
  67. package/examples/vite-app/README.md +0 -71
  68. package/examples/vite-app/index.html +0 -42
  69. package/examples/vite-app/package.json +0 -18
  70. package/examples/vite-app/src/app.css +0 -3
  71. package/examples/vite-app/src/app.js +0 -29
  72. package/examples/vite-app/src/components/app-navbar.lego +0 -34
  73. package/examples/vite-app/src/components/customers/customer-details.lego +0 -24
  74. package/examples/vite-app/src/components/customers/customer-orders.lego +0 -21
  75. package/examples/vite-app/src/components/customers/order-list.lego +0 -55
  76. package/examples/vite-app/src/components/greeting-card.lego +0 -41
  77. package/examples/vite-app/src/components/sample-component.lego +0 -75
  78. package/examples/vite-app/src/components/shells/customers-shell.lego +0 -21
  79. package/examples/vite-app/src/components/side-menu.lego +0 -46
  80. package/examples/vite-app/src/components/todo-list.lego +0 -239
  81. package/examples/vite-app/src/components/widgets/user-card.lego +0 -27
  82. package/examples/vite-app/vite.config.js +0 -22
  83. package/tests/error.test.js +0 -74
  84. package/tests/main.test.js +0 -103
  85. package/tests/memory.test.js +0 -68
  86. package/tests/monitoring.test.js +0 -74
  87. package/tests/naming.test.js +0 -74
  88. package/tests/parse-lego.test.js +0 -65
  89. package/tests/security.test.js +0 -67
  90. package/tests/server.test.js +0 -114
  91. package/tests/syntax.test.js +0 -67
@@ -1,29 +0,0 @@
1
- # Global Helpers
2
-
3
- Lego exposes a global `Lego` object when loaded via CDN, or as exports when using modules.
4
-
5
- ## Lego.page
6
-
7
- Access to the router's current state.
8
-
9
- ```js
10
- console.log(Lego.page.params); // URL parameters
11
- console.log(Lego.page.query); // Query string parameters
12
- ```
13
-
14
- ## Lego.create()
15
-
16
- Manually create a reactive object (stud) detached from a component.
17
-
18
- ```js
19
- const store = Lego.create({ count: 0 });
20
- ```
21
-
22
- ## Event Bus
23
-
24
- Simple global event bus.
25
-
26
- ```js
27
- Lego.on('user-login', (user) => { ... });
28
- Lego.emit('user-login', { name: 'Alice' });
29
- ```
package/docs/api/index.md DELETED
@@ -1,30 +0,0 @@
1
- # API Reference
2
-
3
- Welcome to the Lego API documentation.
4
-
5
- ## Core
6
-
7
- - [Lego.define()](/api/define) - Defining components
8
- - [Lego.route()](/api/route) - Client-side routing
9
- - [Lego.globals](/api/globals) - Global state
10
- - [Lego.config](/api/config) - Configuration & Error Handling
11
- - [Lifecycle Hooks](/api/lifecycle) - Component lifecycle methods
12
-
13
- ## Templates & Binding
14
-
15
- - [Directives](/api/directives) - `b-show`, `b-for`, `b-sync`
16
-
17
- ## Browser Support
18
-
19
- Lego requires:
20
- - Web Components (Custom Elements v1)
21
- - Shadow DOM v1
22
- - ES6 Proxy
23
- - Template Literals
24
- - MutationObserver
25
-
26
- Supported browsers:
27
- - Chrome 63+
28
- - Firefox 63+
29
- - Safari 11.1+
30
- - Edge 79+
@@ -1,40 +0,0 @@
1
- # Lifecycle Hooks
2
-
3
- Methods that are automatically called during a component's lifecycle.
4
-
5
- ## init()
6
-
7
- Called when the component is initialized and state is reactive, but before rendering.
8
-
9
- ```js
10
- {
11
- init() {
12
- this.fetchData();
13
- }
14
- }
15
- ```
16
-
17
- ## render()
18
-
19
- Called after the DOM has been updated.
20
-
21
- ```js
22
- {
23
- render() {
24
- console.log('Component rendered');
25
- }
26
- }
27
- ```
28
-
29
- ## destroy()
30
-
31
- Called when the component is removed from the DOM.
32
-
33
- ```js
34
- {
35
- destroy() {
36
- // Cleanup timers or listeners
37
- clearInterval(this.timer);
38
- }
39
- }
40
- ```
package/docs/api/route.md DELETED
@@ -1,37 +0,0 @@
1
- # Lego.route()
2
-
3
- Client-side routing.
4
-
5
- ## Type Signature
6
-
7
- ```ts
8
- Lego.route(path: string, componentOrHtml: string | HTMLElement)
9
- ```
10
-
11
- ## Arguments
12
-
13
- - **path**: The URL path pattern (e.g., `/users/:id`).
14
- - **componentOrHtml**: The tag name of the component to render, or raw HTML.
15
-
16
- ## Example
17
-
18
- ```js
19
- // Route to a component
20
- Lego.route('/', 'home-page');
21
- Lego.route('/about', 'about-page');
22
-
23
- // Route with params
24
- Lego.route('/user/:id', 'user-profile');
25
- ```
26
-
27
- ## Router Outlet
28
-
29
- You must have a `<router-outlet>` in your DOM where the routed content will appear.
30
-
31
- ```html
32
- <nav>
33
- <a href="/">Home</a>
34
- <a href="/about">About</a>
35
- </nav>
36
- <router-outlet></router-outlet>
37
- ```
@@ -1,58 +0,0 @@
1
- # Vite Plugin API
2
-
3
- Lego includes a Vite plugin for processing `.lego` Single File Components.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- npm install vite lego-dom
9
- ```
10
-
11
- ## Usage
12
-
13
- ```js
14
- // vite.config.js
15
- import { defineConfig } from 'vite';
16
- import legoPlugin from 'lego-dom/vite-plugin';
17
-
18
- export default defineConfig({
19
- plugins: [
20
- legoPlugin({
21
- // Options
22
- })
23
- ]
24
- });
25
- ```
26
-
27
- ## Options
28
-
29
- ### `componentsDir`
30
-
31
- - **Type**: `string`
32
- - **Default**: `'src/components'`
33
-
34
- Directory to search for `.lego` files.
35
-
36
- ### `include`
37
-
38
- - **Type**: `string | string[]`
39
- - **Default**: `'**/*.lego'`
40
-
41
- Glob pattern(s) to match files.
42
-
43
- ### `exclude`
44
-
45
- - **Type**: `string | string[]`
46
- - **Default**: `null`
47
-
48
- Glob pattern(s) to exclude files.
49
-
50
- ## Virtual Module
51
-
52
- The plugin exposes a virtual module to register all components:
53
-
54
- ```js
55
- import registerComponents from 'virtual:lego-components';
56
-
57
- registerComponents();
58
- ```
@@ -1,38 +0,0 @@
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
- init: () => { ... },
11
- define: (tagName, templateHTML, logic = {}) => { ... },
12
- defineSFC: (content, filename) => { ... }, // Runtime SFC Parser
13
- // ...
14
- };
15
- })();
16
-
17
- if (typeof window !== 'undefined') {
18
- document.addEventListener('DOMContentLoaded', Lego.init);
19
- window.Lego = Lego;
20
- }
21
- ```
22
-
23
- ### Why Not Modular ES6?
24
-
25
- 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.
26
-
27
- ### The use of `WeakMap`
28
-
29
- You’ll notice the use of `WeakMap` for `proxyCache`, `privateData`, and `forPools`.
30
-
31
- - **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.
32
-
33
- - **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.
34
-
35
-
36
- ### Internal Registry
37
-
38
- `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.
@@ -1,133 +0,0 @@
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 `user-card.lego`, and suddenly `<user-card>` is a valid HTML tag in your app.
98
-
99
- **Paradigm 3: Runtime Component Definition (New in v2.0)**
100
-
101
- ```js
102
- defineSFC: (content, filename) => {
103
- // Regex parsing of <template>, <script>, <style>
104
- const templateMatch = content.match(/<template([\s\S]*?)>([\s\S]*?)<\/template>/);
105
- // ...
106
- const logicObj = new Function(`return ${script}`)();
107
- // ...
108
- sfcLogic.set(name, logicObj);
109
- }
110
- ```
111
-
112
- This is the power behind the **Server Loader**. We can fetch a string from the server and "compile" it in the browser using `new Function()`. It populates `registry` and `sfcLogic` just like the build-time tools, but on the fly.
113
-
114
- ### 4. Component Naming Conventions ("Explicit or Go Home")
115
-
116
- When you define a component via a file (e.g. `.lego`), the library automatically derives the tag name. To keep the web platform happy, we enforce **Custom Element Best Practices**:
117
-
118
- 1. **Automatic Conversion**: All filenames are converted to `kebab-case`.
119
- - `UserProfile.lego` -> `<user-profile>`
120
- - `navBar.lego` -> `<nav-bar>`
121
- - `data_table.lego` -> `<data-table>`
122
-
123
- 2. **The Hyphen Rule**: A custom element **MUST** contain a hyphen.
124
- - `Button.lego` -> Error
125
- - `Adidas.lego` -> Error
126
-
127
- > [!TIP]
128
- > **Single Word Component? Namespace It!**
129
- > Custom Element specs require a hyphen to distinguish from native tags. To ensure forward compatibility, **LegoDOM will throw an error** if you try to define a single-word component.
130
- > Simply add your app or product prefix to the filename:
131
- > - `fb-button.lego` -> `<fb-button>`
132
- > - `shop-card.lego` -> `<shop-card>`
133
- > - `mobile-button.lego` -> `<mobile-button>`
@@ -1,110 +0,0 @@
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.
@@ -1,87 +0,0 @@
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.
@@ -1,59 +0,0 @@
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.