@twobirds/microcomponents 0.0.65 → 0.0.66

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 (117) hide show
  1. package/assets/documentation/MC.md +22 -28
  2. package/assets/documentation/elements.md +4 -2
  3. package/assets/documentation/observables.md +2 -0
  4. package/assets/test.html +1 -1
  5. package/dist/MC.d.ts.map +1 -1
  6. package/dist/MC.min.js +20 -15
  7. package/dist/MC.ts +23 -16
  8. package/dist/elements.min.js +1 -1
  9. package/dist/formvValues.min.js +1 -1
  10. package/dist/microcomponents.min.js +1 -1
  11. package/dist/observables.d.ts.map +1 -1
  12. package/dist/observables.min.js +1 -1
  13. package/dist/observables.ts +0 -3
  14. package/dist/selectors.min.js +1 -1
  15. package/package.json +4 -4
  16. package/public/MC.js +20 -15
  17. package/public/MC.js.map +1 -1
  18. package/public/MC.min.js +20 -15
  19. package/public/assets/highlight.css +99 -0
  20. package/public/assets/icons.js +18 -0
  21. package/public/assets/icons.svg +1 -0
  22. package/public/assets/main.js +60 -0
  23. package/public/assets/navigation.js +1 -0
  24. package/public/assets/search.js +1 -0
  25. package/public/assets/style.css +1493 -0
  26. package/public/classes/MC.DC.html +12 -0
  27. package/public/classes/MC.MC.html +6 -0
  28. package/public/classes/MC.McBase.html +3 -0
  29. package/public/classes/MC.McEvent.html +9 -0
  30. package/public/elements.min.js +1 -1
  31. package/public/formvValues.min.js +1 -1
  32. package/public/functions/MC.addListener.html +1 -0
  33. package/public/functions/MC.autoload.html +1 -0
  34. package/public/functions/MC.removeListener.html +1 -0
  35. package/public/functions/elements.defineCE.html +1 -0
  36. package/public/functions/elements.getCE.html +1 -0
  37. package/public/functions/formValues.formValues.html +1 -0
  38. package/public/functions/observables.observe.html +1 -0
  39. package/public/functions/selectors._d.html +1 -0
  40. package/public/functions/selectors._t.html +1 -0
  41. package/public/hierarchy.html +1 -0
  42. package/public/index.html +56 -0
  43. package/public/interfaces/MC.HTMLMcElement.html +758 -0
  44. package/public/interfaces/selectors.DSelector.html +50 -0
  45. package/public/interfaces/selectors.TSelector.html +34 -0
  46. package/public/microcomponents.min.js +1 -1
  47. package/public/modules/MC.html +9 -0
  48. package/public/modules/elements.html +3 -0
  49. package/public/modules/formValues.html +2 -0
  50. package/public/modules/observables.html +3 -0
  51. package/public/modules/selectors.html +7 -0
  52. package/public/modules.html +6 -0
  53. package/public/observables.js.map +1 -1
  54. package/public/observables.min.js +1 -1
  55. package/public/selectors.min.js +1 -1
  56. package/public/types/observables.Observable.html +1 -0
  57. package/public/types/selectors.selection.html +1 -0
  58. package/public/types/selectors.singleSelector.html +1 -0
  59. package/src/MC.ts +23 -16
  60. package/src/observables.ts +0 -3
  61. package/src/test/testmc.ts +7 -1
  62. package/assets/documentation/comparision.md +0 -0
  63. package/assets/documentation/how_tos.md +0 -0
  64. package/assets/documentation/introduction.md +0 -0
  65. package/assets/documentation/proposal_draft.md +0 -37
  66. package/public/3d.html +0 -42
  67. package/public/documentation/MC.md +0 -594
  68. package/public/documentation/ajaxian-1.png +0 -0
  69. package/public/documentation/ajaxian-2.png +0 -0
  70. package/public/documentation/ajaxian-3.png +0 -0
  71. package/public/documentation/comparision.md +0 -0
  72. package/public/documentation/elements.md +0 -276
  73. package/public/documentation/functional_requirements.md +0 -8
  74. package/public/documentation/history.md +0 -436
  75. package/public/documentation/how_tos.md +0 -0
  76. package/public/documentation/introduction.md +0 -0
  77. package/public/documentation/magic.md +0 -29
  78. package/public/documentation/observables.md +0 -105
  79. package/public/documentation/proposal_draft.md +0 -37
  80. package/public/documentation/rnd0023-1.jpg +0 -0
  81. package/public/documentation/rnd0023-2.jpg +0 -0
  82. package/public/documentation/rnd0023-3.jpg +0 -0
  83. package/public/documentation/tB_react.md +0 -207
  84. package/public/documentation/usage.md +0 -142
  85. package/public/documentation/why.md +0 -25
  86. package/public/fiddle/MicroComponents.svg +0 -15
  87. package/public/fiddle/fiddle.css +0 -0
  88. package/public/fiddle/fiddle.js +0 -0
  89. package/public/fiddle/index.html +0 -0
  90. package/public/grandparent.css +0 -13
  91. package/public/my-tag.css +0 -19
  92. package/public/src/MC.ts +0 -598
  93. package/public/src/McEvent.ts +0 -96
  94. package/public/src/autoloader.ts +0 -98
  95. package/public/src/elements.ts +0 -76
  96. package/public/src/formValues.ts +0 -233
  97. package/public/src/helpers.ts +0 -149
  98. package/public/src/microcomponents.ts +0 -8
  99. package/public/src/observables.ts +0 -404
  100. package/public/src/selectors.ts +0 -1634
  101. package/public/src/test.ts +0 -193
  102. package/public/test/child.js +0 -15
  103. package/public/test/child.js.map +0 -1
  104. package/public/test/grandchild.js +0 -15
  105. package/public/test/grandchild.js.map +0 -1
  106. package/public/test/grandparent.js +0 -1
  107. package/public/test/grandparent.js.map +0 -1
  108. package/public/test/greatgrandchild.js +0 -29
  109. package/public/test/greatgrandchild.js.map +0 -1
  110. package/public/test/parent.js +0 -15
  111. package/public/test/parent.js.map +0 -1
  112. package/public/test/testform.js +0 -1
  113. package/public/test/testform.js.map +0 -1
  114. package/public/test/testmc.js +0 -10
  115. package/public/test/testmc.js.map +0 -1
  116. package/public/test.html +0 -27
  117. /package/public/{MicroComponents.svg → media/MicroComponents.svg} +0 -0
@@ -1,37 +0,0 @@
1
- ### RFC Proposal to WHATWG
2
-
3
- **Title:** Proposal for a **Micro Component Interface** in the DOM
4
-
5
- **Abstract:**
6
-
7
- This proposal introduces a standardized interface for managing micro components within HTML elements, enhancing modularity and reusability in web development.
8
-
9
- **Introduction:**
10
-
11
- Microcomponents provide a way to encapsulate functionality and state within a target DOM element. This proposal outlines methods for adding, removing, and querying micro components.
12
-
13
- **Proposed API:**
14
-
15
- - **Static Methods:**
16
- - `MC.add( target, key, element)`: Attach a top level micro component to an HTMLElement.
17
- - `MC.remove( target, key )`: Detach a top level micro component from an HTMLElement.
18
- - `MC.siblings( target )`: get top level micro components from an HTMLElement.
19
-
20
- - **Instance Methods:**
21
- - `add( key, element )`: Attach a private Micro Component to a Micro Component.
22
- - `remove( key )`: Detach a private Micro Component from a Micro Component.
23
- - `siblings(search?)`: Retrieve sibling micro components.
24
- - `parent(search?)`: Get parent top level micro components.
25
- - `parents(search?)`: Get all ancestor top level micro components.
26
- - `children(search?)`: Retrieve child top level micro components.
27
- - `descendants(search?)`: Get all descendant top level micro components.
28
-
29
- **Use Cases:**
30
- 1. Modular web applications.
31
- 2. Enhancing component-based architecture.
32
-
33
- **Conclusion:**
34
- Implementing this interface will streamline microcomponent management, fostering cleaner code and improved performance.
35
-
36
- **References:**
37
- - [Microcomponents Repository](https://gitlab.com/twoBirds/microcomponents) for a polyfill implementation and usage examples.
package/public/3d.html DELETED
@@ -1,42 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>3D Positioned Image with CSS</title>
7
- <style>
8
- body {
9
- display: flex;
10
- justify-content: center;
11
- align-items: center;
12
- height: 100vh;
13
- background-color: #222;
14
- perspective: 800px; /* Depth effect */
15
- }
16
-
17
- .container {
18
- width: 300px;
19
- height: 200px;
20
- transform-style: preserve-3d; /* Needed for 3D transformations */
21
- }
22
-
23
- .image3d {
24
- width: 100%;
25
- height: 100%;
26
- transform: rotateY(20deg) rotateX(10deg) translateZ(50px);
27
- transition: transform 0.5s ease-in-out;
28
- box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.5);
29
- }
30
-
31
- /* Hover effect */
32
- .container:hover .image3d {
33
- transform: rotateY(-20deg) rotateX(-10deg) translateZ(100px);
34
- }
35
- </style>
36
- </head>
37
- <body>
38
- <div class="container">
39
- <img class="image3d" src="https://via.placeholder.com/300x200" alt="3D Image">
40
- </div>
41
- </body>
42
- </html>
@@ -1,594 +0,0 @@
1
- # Microcomponent Framework Documentation <span style="float:right; height:1em;"><img height="24px" src="./MicroComponents.svg" /></span>
2
-
3
- This document details a lightweight JavaScript framework for creating and managing "microcomponents" (MCs) associated with DOM elements or other microcomponents. It allows you to define reusable components and attach them to build complex functionalities.
4
-
5
- The framework exports 2 main classes:
6
-
7
- - **MC**: Micro Component. The base component class, suitable for logic that doesn't directly interact with the DOM or for use on the server.
8
- - **DC**: DOM Component. Extends `MC` and adds DOM-specific methods (like traversal). Use this for components that need to interact with the browser's DOM.
9
-
10
- ## Table of Contents
11
-
12
- - [Usage Guidance](#usage-guidance)
13
- - [Core Concepts](#core-concepts)
14
- - [Microcomponents (MCs)](#microcomponents-mcs)
15
- - [`_mc` Property](#_mc-property)
16
- - [DOM Association & `target`](#dom-association--target)
17
- - [Event System](#event-system)
18
- - [Observables (Mention)](#observables-mention)
19
- - [DOM Traversal](#dom-traversal)
20
- - [Autoloading Concept](#autoloading-concept)
21
- - [Important Rule](#important-rule)
22
- - [Classes](#classes)
23
- - [Not Exported: `McBase` (Superclass)](#not-exported-mcbase-superclass)
24
- - [Exported: `MC` Class](#exported-mc-class)
25
- - [Exported: `DC` Class](#exported-dc-class)
26
- - [Examples](#examples)
27
- - [Typical Workflow](#typical-workflow)
28
- - [Attach Micro Components (`DC.add`)](#attach-micro-components-dcadd)
29
- - [Remove Micro Components (`DC.remove`)](#remove-micro-components-dcremove)
30
- - [Retrieve Micro Components](#retrieve-micro-components)
31
- - [Triggering Events](#triggering-events)
32
- - [Retrieving Inner Micro Components](#retrieving-inner-micro-components)
33
- - [Navigating Parent/Ancestor MCs](#navigating-parentancestor-mcs)
34
- - [Retrieving Child/Descendant MCs](#retrieving-childdescendant-mcs)
35
- - [Auto-attaching DOM Listeners](#auto-attaching-dom-listeners)
36
- - [Lifecycle Events](#lifecycle-events)
37
- - [Init](#init)
38
- - [Destroy (TBD)](#destroy-tbd)
39
- - [Helper Functions (Internal)](#helper-functions-internal)
40
- - [`isBrowser()`](#isbrowser)
41
- - [`nativeEventNames`](#nativeeventnames)
42
- - [`getMicroComponents(...)`](#getmicrocomponents)
43
- - [`traverseNodes(...)`](#traversenodes)
44
- - [`isDOM(...)`](#isdom)
45
- - [`addListener(...)`](#addlistener)
46
- - [`removeListener(...)`](#removelistener)
47
- - [`add(...)`](#add)
48
- - [`remove(...)`](#remove)
49
- - [`trigger(...)`](#trigger)
50
- - [`init(...)`](#init-helper)
51
- - [`autoAttachListeners(...)`](#autoattachlisteners)
52
- - [`bubbleEvent(...)`](#bubbleevent)
53
- - [Interfaces and Types](#interfaces-and-types)
54
- - [`LooseObject`](#looseobject)
55
- - [`McEvent`](#mcevent)
56
- - [`HTMLMcElement`](#htmlmcelement)
57
- - [Autoloading](#auto-loading)
58
-
59
- ## Usage Guidance
60
-
61
- - **If your component needs to access or manipulate the DOM** (e.g., find other components in the DOM, attach listeners directly, read element properties), **your class MUST extend `DC`**. This is client-side only.
62
- - **Otherwise** (e.g., for pure logic, state management, or server-side usage), **your class should extend `MC`**.
63
-
64
- Think **DRY** (Don't Repeat Yourself) and **SOLID** principles when designing your components.
65
-
66
- ## Core Concepts
67
-
68
- Fundamental ideas behind the framework.
69
-
70
- ### Microcomponents (MCs)
71
-
72
- Plain JavaScript objects or class instances (extending `MC` or `DC`) that encapsulate behavior and state. They can be attached to DOM elements (via `DC`) or nested within other MCs.
73
-
74
- ### `_mc` Property
75
-
76
- A special property attached to `HTMLElement` instances (when using `DC.add`) or parent `MC`/`DC` instances. It acts as an object container (`{ key: mcInstance, ... }`) holding one or more named microcomponent instances.
77
-
78
- - On HTMLElements, the presence of attached components is also marked by a `_mc` attribute for CSS selection and discovery. This attribute is added by `DC.add` and removed by `DC.remove` when the `_mc` object becomes empty.
79
-
80
- ### DOM Association & `target`
81
-
82
- Each microcomponent instance has a read-only `target` property providing a back-reference:
83
-
84
- - If the instance extends **`DC`** and was added via `DC.add`, `target` refers to the **DOM HTMLElement** it's attached to.
85
- - If the instance extends **`MC`** (or `DC`) and is nested within another component's `_mc` property, `target` refers to the **parent MC/DC instance**.
86
-
87
- This reference is managed using `WeakRef` internally by `McBase` to prevent circular references and potential memory leaks.
88
-
89
- ### Event System
90
-
91
- A custom event system using the `McEvent` class allows components to communicate.
92
-
93
- - **Triggering:** Events are dispatched using the `trigger` method:
94
- - `DC.trigger(targetElement, ...)`: Dispatches to all MCs on a specific DOM element. Handles bubbling (`u`/`d`).
95
- - `this.trigger(...)`: Dispatches within the current MC instance and its potential nested MCs. Can also initiate bubbling if the instance is a `DC`.
96
- - **Handling:**
97
- - Components listen for events by defining methods named `onEventName` or `oneEventName` (for once-off handling).
98
- - These are automatically detected by `autoAttachListeners`.
99
- - Native DOM events matching this pattern on `DC` instances are also automatically bound to the target element.
100
- - **Bubbling:** Events triggered via `DC.trigger` or `dcInstance.trigger` can bubble:
101
- - `'l'`: Local only (default). Handlers on the target element's/instance's MCs are executed.
102
- - `'u'`: Upwards. Event propagates to MCs on parent elements (DOM tree).
103
- - `'d'`: Downwards. Event propagates to MCs on descendant elements (DOM tree).
104
- - Combinations are possible (e.g., `'lu'`, `'ldu'`). Bubbling (`u`/`d`) occurs asynchronously via `setTimeout`.
105
-
106
- ### Observables (Mention)
107
-
108
- - MCs can utilize observables (implementation not detailed here) for data-driven workflows.
109
- - `DC` components can leverage observables and potentially form values for 1-way or 2-way data binding with the DOM.
110
-
111
- ### DOM Traversal
112
-
113
- The `DC` class provides methods (`parent`, `ancestors`, `children`, `descendants`) to find related `DC` instances attached to elements elsewhere in the DOM hierarchy, skipping over elements without attached microcomponents.
114
-
115
- ### Autoloading Concept
116
-
117
- An optional feature (`autoload()`) that automatically detects specific HTML tags (e.g., `<my-component>`) or elements with an `_mc="MyComponent"` attribute and attempts to dynamically load the corresponding JavaScript module (e.g., `/my/Component.js`).
118
-
119
- ### Important Rule
120
-
121
- **Your own application code MUST NOT overwrite the core properties and methods provided by the `McBase`, `MC`, and `DC` classes (like `_mc`, `target`, `trigger`, `parent`, etc.). Doing so may break framework functionality.**
122
-
123
- ## Classes
124
-
125
- ### Not Exported: `McBase` (Superclass)
126
-
127
- The internal base class for `MC` and `DC`. You don't extend this directly.
128
-
129
- - **Instance Properties**:
130
- - `.target`: Read-only getter returning the containing DOM element (for DCs added via `DC.add`) or parent MC/DC instance (for nested MCs). Uses `WeakRef`.
131
- - **Constructor Behavior**:
132
- - Initializes the `.target` reference.
133
- - Calls `init(this)`: Triggers the 'Init' lifecycle event asynchronously.
134
- - Calls `autoAttachListeners(this)`: Sets up automatic event listeners based on method names (`onEventName`, `oneEventName`).
135
- - **Instance Methods**:
136
- - `.trigger(eventName, data)`: Base trigger logic used by `MC` and `DC`.
137
-
138
- ### Exported: `MC` Class
139
-
140
- Base class for non-DOM or server-side components. Extends `McBase`.
141
-
142
- - **Instance Properties**:
143
- - `.target`: (Inherited from `McBase`) Refers to the parent MC/DC instance it's nested within.
144
- - `._mc`: An object `{}` to hold nested microcomponent instances.
145
- - **Instance Methods**:
146
- - `.trigger(eventName, data)`: (Inherited) Triggers events locally within the instance and its nested `_mc` structure. Does not handle DOM bubbling.
147
-
148
- ### Exported: `DC` Class
149
-
150
- Class for DOM-aware components. Extends `McBase`. **Client-side only.**
151
-
152
- - **Static Methods**:
153
- - `DC.add(domElement, key, mcInstance)`: Attaches an `mcInstance` (should be a `DC` or `MC`) to a `domElement` under the specified `key`. Creates `domElement._mc` if needed and sets the `_mc` attribute.
154
- - `DC.remove(domElement, key)`: Removes the MC instance associated with `key` from `domElement._mc`. Removes the `_mc` attribute if the collection becomes empty.
155
- - `DC.trigger(domElement, eventName, data, bubble)`: Triggers an event on all MCs attached to `domElement`. Handles DOM bubbling (`'l'`, `'u'`, `'d'`).
156
- - **Instance Properties**:
157
- - `.target`: (Inherited from `McBase`) Refers to the DOM HTMLElement this `DC` instance is attached to (via `DC.add`).
158
- - `._mc`: An object `{}` to hold nested microcomponent instances.
159
- - **Instance Methods**:
160
- - `.parent(search?)`: Gets MC instances from the closest parent element that has attached MCs. Optionally filters by `search` key.
161
- - `.ancestors(search?)`: Gets MC instances from all ancestor elements with attached MCs. Optionally filters by `search` key.
162
- - `.children(search?)`: Gets MC instances from direct child elements with attached MCs. Optionally filters by `search` key.
163
- - `.descendants(search?)`: Gets MC instances from all descendant elements with attached MCs. Optionally filters by `search` key.
164
- - `.trigger(eventName, data, bubble)`: Triggers an event on this `DC` instance and its nested `_mc` structure. Can initiate DOM bubbling (`'l'`, `'u'`, `'d'`).
165
-
166
- ## Examples
167
-
168
- ### Typical Workflow
169
-
170
- 1. Define your component classes extending `MC` or `DC`.
171
- 2. Attach top-level `DC` instances to HTMLElements using `DC.add()`.
172
- 3. Nest `MC` or `DC` instances within others using the `._mc` property if needed.
173
- 4. Access other components via the `_mc` property, DOM traversal methods (`ancestors()`, `children()`, etc.), or event communication (`trigger`).
174
-
175
- ### Attach Micro Components (`DC.add`)
176
-
177
- Use the static `DC.add()` method to attach a component (usually a `DC` instance) to an HTMLElement.
178
-
179
- ```javascript
180
- const myElement = document.getElementById('myDiv');
181
-
182
- // Define an inner MC (doesn't need DOM access itself)
183
- class MyInnerClass extends MC {
184
- constructor(target) {
185
- // target will be the parent MyPublicClass instance
186
- super(target);
187
- console.log('Inner MC target:', this.target);
188
- }
189
- doSomethingInner() {
190
- console.log('Inner action!');
191
- }
192
- }
193
-
194
- // Define an outer DC (needs DOM access or is top-level)
195
- class MyPublicClass extends DC {
196
- constructor(target) {
197
- // target will be myElement
198
- super(target);
199
- console.log('Outer DC target:', this.target);
200
- // Add an inner MC instance, nested within this DC instance
201
- this._mc.myInner = new MyInnerClass(this); // 'this' becomes the target for MyInnerClass
202
- }
203
- doSomethingOuter() {
204
- console.log('Outer action!');
205
- }
206
-
207
- // Example DOM event handler
208
- onClick(event) {
209
- console.log('Div clicked!', event);
210
- // Access nested MC
211
- this._mc.myInner?.doSomethingInner();
212
- }
213
- }
214
-
215
- // Attach the outer DC instance to the DOM element
216
- // The key 'myComponent' is used to access it later via myElement._mc.myComponent
217
- DC.add(myElement, 'myComponent', new MyPublicClass(myElement));
218
-
219
- // Hint: After adding, myElement now has:
220
- // 1. A property: myElement._mc = { myComponent: instanceOfMyPublicClass }
221
- // 2. An attribute: <div id="myDiv" _mc>...</div>
222
- ```
223
-
224
- ### Remove Micro Components (DC.remove)
225
-
226
- Use the static DC.remove() method to detach a top-level component.
227
-
228
- ```javascript
229
- const myElement = document.getElementById('myDiv');
230
-
231
- DC.remove(myElement, 'myComponent');
232
-
233
- // If myElement._mc is now empty, the '_mc' attribute is also removed.
234
- ```
235
-
236
- ### Retrieve Micro Components
237
-
238
- Access attached components via the \_mc property of the target element or parent component.
239
-
240
- ```javascript
241
- // Get the container object for all MCs on an element
242
- const myElement = document.getElementById('myDiv');
243
- const mcContainer = myElement._mc;
244
- console.log(mcContainer); // { myComponent: instanceOfMyPublicClass, ... }
245
-
246
- // Get a specific instance by its key
247
- const specificInstance = myElement._mc?.myComponent;
248
- if (specificInstance) {
249
- specificInstance.doSomethingOuter();
250
- }
251
- ```
252
-
253
- ### Triggering Events
254
-
255
- 1. Triggering from outside onto components on an element:
256
-
257
- ```javascript
258
- const targetElement = document.getElementById('myDiv');
259
- const eventData = { message: 'Hello from outside!' };
260
-
261
- // Trigger 'customEvent' locally on MCs attached to targetElement
262
- DC.trigger(targetElement, 'customEvent', eventData, 'l');
263
-
264
- // Trigger 'customEvent' and bubble up the DOM tree
265
- DC.trigger(targetElement, 'customEvent', eventData, 'u');
266
-
267
- // Trigger 'customEvent' locally, bubble up, and bubble down
268
- DC.trigger(targetElement, 'customEvent', eventData, 'lud');
269
- ```
270
-
271
- 2. Triggering from inside a component instance:
272
-
273
- ```javascript
274
- class MyTriggeringComponent extends DC {
275
- // ... constructor ...
276
-
277
- someMethod() {
278
- const eventData = { source: 'MyTriggeringComponent' };
279
-
280
- // Trigger 'internalEvent' only on this instance and its nested _mc components
281
- this.trigger('internalEvent', eventData); // Default bubble 'l'
282
-
283
- // Trigger 'externalEvent' on sibling components attached to the same target element
284
- // (and potentially bubble up/down based on the 'bubble' parameter)
285
- DC.trigger(this.target, 'externalEvent', eventData, 'l'); // Trigger locally on siblings
286
-
287
- // Trigger 'downwardEvent' on components attached to descendant elements
288
- this.trigger('downwardEvent', eventData, 'd'); // Bubbles down from this component's target
289
- }
290
-
291
- // Event handler methods
292
- onCustomEvent(event) {
293
- console.log(`[${this.constructor.name}] received customEvent:`, event.data);
294
- }
295
-
296
- onInternalEvent(event) {
297
- console.log(
298
- `[${this.constructor.name}] received internalEvent:`,
299
- event.data
300
- );
301
- }
302
-
303
- onExternalEvent(event) {
304
- console.log(
305
- `[${this.constructor.name}] received externalEvent:`,
306
- event.data
307
- );
308
- }
309
-
310
- onDownwardEvent(event) {
311
- console.log(
312
- `[${this.constructor.name}] received downwardEvent:`,
313
- event.data
314
- );
315
- }
316
- }
317
- ```
318
-
319
- ### Retrieving Inner Micro Components
320
-
321
- Access nested components directly via the parent's `_mc` property.
322
-
323
- ```javascript
324
- class Inner extends MC {
325
- constructor(target) {
326
- super(target);
327
- }
328
- someInnerMethod() {
329
- console.log('Inner method called!');
330
- }
331
- }
332
-
333
- class Outer extends DC {
334
- constructor(target) {
335
- super(target);
336
- this._mc.inner = new Inner(this);
337
- }
338
-
339
- accessInner() {
340
- this._mc?.inner.someInnerMethod();
341
- }
342
- }
343
- ```
344
-
345
- ### Navigating Parent/Ancestor MCs
346
-
347
- Use .parent() and .ancestors() (available on DC instances) to find components attached to elements higher up the DOM tree.
348
-
349
- These methods skip elements that don't have any MCs attached.
350
-
351
- ```javascript
352
- // Inside a method of a DC instance:
353
- const parentMcs = this.parent(); // Array of MC instances on the first parent element with MCs
354
- console.log(parentMcs);
355
-
356
- const allAncestorMcs = this.ancestors(); // Array of all MC instances on all ancestor elements with MCs
357
- console.log(allAncestorMcs);
358
-
359
- // Find a specific component type/key among ancestors
360
- const specificAncestor = this.ancestors('someSpecificKey')?.[0];
361
-
362
- if (specificAncestor) {
363
- console.log('Found specific ancestor:', specificAncestor);
364
- }
365
- ```
366
-
367
- ### Retrieving Child/Descendant MCs
368
-
369
- Use .children() and .descendants() (available on DC instances) to find components attached to elements lower down the DOM tree.
370
-
371
- ```javascript
372
- // Inside a method of a DC instance:
373
- const childMcs = this.children(); // Array of MCs on direct child elements with MCs
374
- console.log(childMcs);
375
-
376
- const descendantMcs = this.descendants(); // Array of all MCs on all descendant elements with MCs
377
- console.log(descendantMcs);
378
-
379
- // Find specific components among descendants
380
- const specificDescendants = this.descendants('someSpecificKey');
381
- console.log(specificDescendants); // Array of matching descendant MCs
382
- ```
383
-
384
- ### Auto-attaching DOM Listeners
385
-
386
- Methods defined in your DC class starting with `on` or `one` followed by a capital letter, which also match native DOM event names (case-insensitive check), will automatically have listeners attached to the target DOM element:
387
-
388
- ```javascript
389
- class McWithHandlers extends DC {
390
- constructor(target) {
391
- super(target);
392
- }
393
-
394
- // This method name matches the native 'click' event.
395
- // A listener will be automatically added to this.target.
396
- onClick(domEvent) {
397
- console.log('Target element clicked!', domEvent);
398
- // 'this' refers to the MyClickHandler instance
399
- this.target.style.backgroundColor = 'lightblue';
400
- }
401
-
402
- // This method name matches the native 'mouseover' event.
403
- // 'one' means the listener will be removed after the first trigger.
404
- oneMouseover(domEvent) {
405
- console.log('Mouseover detected once!', domEvent);
406
- this.target.style.border = '2px solid red';
407
- }
408
-
409
- // This is a custom event handler, not a native DOM event.
410
- // It will be triggered by this.trigger('CustomAction') or DC.trigger(this.target, 'CustomAction')
411
- onCustomAction(mcEvent) {
412
- console.log('Custom action triggered!', mcEvent.data);
413
- }
414
- }
415
-
416
- const myDiv = document.getElementById('clickableDiv');
417
- DC.add(myDiv, 'clickHandler', new McWithHandlers(myDiv));
418
- // Now clicking or mousing over 'clickableDiv' will trigger the methods.
419
- ```
420
-
421
- ### Lifecycle Events
422
-
423
- The framework defines specific methods that are called at certain points in a component's life.
424
-
425
- #### Init
426
-
427
- Method Name: oneInit(event)
428
-
429
- Triggered: Asynchronously (setTimeout(0)) after the component instance is created (called from McBase constructor via the init helper).
430
-
431
- Execution Order:
432
-
433
- The component's oneInit is called first, then it recursively calls oneInit on any components nested within its `_mc` property.
434
-
435
- Requirement:
436
-
437
- - You must define a method named `oneInit` in your class for it to be called.
438
- - The `one` prefix implies it's intended to run once during initialization.
439
-
440
- ```javascript
441
- class MyLifecycleComponent extends DC {
442
- constructor(target) {
443
- super(target);
444
- console.log('Constructor finished');
445
- this._mc.nested = new NestedComponent(this);
446
- }
447
-
448
- oneInit(event) {
449
- // This code runs shortly after the constructor finishes.
450
- console.log('MyLifecycleComponent oneInit called!', event);
451
- // Safe to access this.target or setup things that depend on the instance being fully constructed.
452
- }
453
- }
454
- ```
455
- ## Auto Loading
456
-
457
- `autoload()` provides a **progressive enhancement** strategy. It allows you to declare custom elements or special micro components in your HTML without needing to include all their JavaScript code upfront.
458
-
459
- The necessary code is fetched and executed only when these components actually appear in the DOM, potentially improving initial page load time and resource usage.
460
-
461
- ### Enabling/Disabling:
462
-
463
- - If you call **`autoload(true)`** (or just **`autoload()`** as true is the parameter default), it initializes a MutationObserver.
464
- This observer watches the document.body for any changes to its child elements or subtree (e.g., when new elements are added to the page).
465
-
466
- **./autoload.html**
467
- ```HTML
468
- <!DOCTYPE html>
469
- <html lang="en">
470
- <head>
471
- <meta charset="UTF-8" />
472
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
473
- <title>Humble Beginnings</title>
474
- <script src="./microcomponents.min.js"></script>
475
- <script>
476
- Object.assign(window, microcomponents); // make system global
477
- autoload(true); // automatically load web components that are undefined
478
- </script>
479
- </head>
480
- <body>
481
- <div _mc="test-mymc"></div> <!--- example of a auto-loading micro component --->
482
- <test-component></test-component> <!--- example of a auto-loading custom element --->
483
- </body>
484
- </html>
485
-
486
- ```
487
-
488
- **./test/testmc.ts**
489
- ```typescript
490
- 'use strict';
491
- import { DC, LooseObject } from '../microcomponents.js';
492
-
493
- export default class extends DC {
494
- constructor(target: HTMLElement) {
495
- super(target);
496
- delete this._mc; // not needed
497
- }
498
-
499
- oneInit() {
500
- // console.log('testmc connected to DOM');
501
- }
502
- }
503
- ```
504
-
505
- **./test/component.ts**
506
- ```typescript
507
- 'use strict';
508
- import { DC, defineCE } from '.././microcomponents.js';
509
-
510
- defineCE(
511
- 'test-mycomponent',
512
-
513
- class extends DC {
514
- data: unknown;
515
-
516
- constructor(target: HTMLElement) {
517
- super(target);
518
-
519
- const that = this; // to help minification, you can use 'this' throughout the constructor as well
520
-
521
- delete that._mc; // no inner classes needed
522
-
523
- let shadow = (that as DC).target.attachShadow({ mode: 'open' });
524
- shadow.innerHTML = `<style>${that.css}</style>${that.template}`;
525
-
526
- }
527
-
528
- get template() {
529
- return /*html*/ `
530
- <span>Hello World</span>
531
- `;
532
- }
533
-
534
- get css() {
535
- return /*css*/ `
536
- div {
537
- background-color: cyan;
538
- }`;
539
- }
540
- }
541
- );
542
- ```
543
-
544
- **Page HTML after loading**
545
- ```HTML
546
- (...)
547
- <div _mc=""></div> <!--- _mc component definition now empty to avoid re-loading --->
548
- <test-component></test-component> <!--- the custom element is initialized now --->
549
- (...)
550
- ```
551
-
552
-
553
- - If you call **`autoload(false)`**, it disconnects the observer, stopping the automatic loading feature.
554
-
555
-
556
- #### Loading Mechanism:
557
-
558
- When enabled and changes are detected in the DOM, the a callback function is triggered. This function scans the DOM for two types of components that might not yet be defined:
559
-
560
- - **Undefined Custom Elements:** It looks for HTML elements whose tag names haven't been defined via customElements.define() (e.g., `<my-custom-tag>`).
561
-
562
- For an element like `<my-custom-tag>`, it will attempt to load a script from a path derived from the tag name, such as **`./my/custom/tag.js`**. The loaded script is expected to then define this custom element.
563
-
564
- - **Undefined Micro Components:** It looks for HTML elements that have an **`_mc`** attribute that is not empty, e.g., **`<div _mc="my-component my-other">`**.
565
-
566
- **For each component name** listed in the **`_mc`** attribute (like **`my-component`**), it will attempt to load a script from a path like **`./my/component.js`**.
567
-
568
- **These scripts are expected to `export default class {...}`** (usually extending DC from your code) that defines the behavior of this micro component.
569
-
570
- **In general:**
571
-
572
- - For each undefined component found, it dynamically creates a **`<script type="module">`** tag in the **`head`** of the document, and sets its src attribute to the appropriate path.
573
-
574
- - The src of the script is determined by converting the component name (e.g., **`my-component`**) into a path (e.g., **`./my/component.js`**).
575
-
576
- - These script tags are appended to the <head> of the document to initiate loading.
577
-
578
- #### Internal Callbacks and Instantiation:
579
-
580
- - Custom Elements: Once the script for a custom element loads and defines the element (using customElements.define()), the browser automatically handles upgrading any existing instances of that tag.
581
- - Micro Components (_mc): When a script for an _mc component loads successfully, a another callback is executed. This callback:
582
- - Stores the loaded component class in an internal repository to avoid unnecessary reloading.
583
- - Finds all HTMLElement in the DOM that declared this _mc component.
584
- - Instantiates the component class and adds it to the HTMLElement.
585
- - Removes the component's name from the _mc attribute to prevent re-processing.
586
-
587
- #### State Tracking:
588
-
589
- `autoload()` internally uses two Map() objects:
590
-
591
- - **`CEs`** (for Custom Elements that are currently loading)
592
- - **`MCs`** (for Micro Components), to keep track of components that are currently loading or have been loaded. This prevents attempting to load the same component multiple times.
593
-
594
- These maps are exposed for debugging purposes. You can access them via `autoload.state` which returns an object with `CEs` and `MCs` properties.
Binary file
Binary file
Binary file
File without changes