ladrillosjs 0.1.8 → 1.0.0-rc.10
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.
- package/README.md +238 -91
- package/dist/index-5_a431JU.js +3 -0
- package/dist/index-DJN3i2LF.mjs +215 -0
- package/dist/ladrillosjs.cjs.js +1 -1
- package/dist/ladrillosjs.es.js +4 -2
- package/dist/ladrillosjs.umd.js +3 -5
- package/dist/webcomponent-6tQP-rUH.js +1 -0
- package/dist/webcomponent-BGA1yU7J.mjs +358 -0
- package/package.json +12 -5
- package/dist/main-BaJULV0N.js +0 -5
- package/dist/main-CE6RxSxw.mjs +0 -145
- package/dist/webcomponent-UVarlU1-.js +0 -1
- package/dist/webcomponent-u6r_KhfX.mjs +0 -184
package/README.md
CHANGED
|
@@ -4,121 +4,268 @@
|
|
|
4
4
|
|
|
5
5
|
A lightweight, zero-dependency web component framework for building modular web applications.
|
|
6
6
|
|
|
7
|
+
"I designed this framework to empower developers with the ability to componentize their code efficiently and effectively, without the need for a full-scale framework. By focusing on simplicity and leveraging core web fundamentals, my goal was to create a lightweight and accessible solution that enhances development while staying true to the basics."
|
|
8
|
+
|
|
7
9
|
## Getting Starting with samples
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
The repository includes several example applications that demonstrate various features:
|
|
12
|
+
|
|
13
|
+
- **Notes App**: Example of using stores for state management
|
|
14
|
+
- **Markdown Editor**: Simple markdown-to-HTML converter
|
|
15
|
+
- **API Example**: Fetching and displaying data from an external API
|
|
16
|
+
- **Button Game**: Interactive game demonstrating component events
|
|
17
|
+
- **Simple Button**: Basic component with state and event handling
|
|
18
|
+
|
|
19
|
+
To run the examples:
|
|
20
|
+
|
|
21
|
+
1. Clone the repository
|
|
22
|
+
2. Run `npm install`
|
|
23
|
+
3. Run `npm run dev`
|
|
11
24
|
|
|
12
25
|
## Usage
|
|
13
26
|
|
|
14
|
-
###
|
|
27
|
+
### Install & import
|
|
15
28
|
|
|
16
29
|
```bash
|
|
17
30
|
npm install ladrillosjs
|
|
18
31
|
```
|
|
19
32
|
|
|
20
|
-
|
|
33
|
+
### cdn
|
|
21
34
|
|
|
22
35
|
```js
|
|
23
|
-
<script src="https://cdn.jsdelivr.net/npm/ladrillosjs
|
|
24
|
-
<script type="module">
|
|
25
|
-
ladrillosjs.ladrillos.registerComponent(
|
|
26
|
-
"alert-button",
|
|
27
|
-
"alert-button.html"
|
|
28
|
-
);
|
|
29
|
-
</script>
|
|
36
|
+
<script defer src="https://cdn.jsdelivr.net/npm/ladrillosjs"></script>
|
|
30
37
|
```
|
|
31
38
|
|
|
32
|
-
|
|
39
|
+
## First Component
|
|
40
|
+
|
|
41
|
+
A component in LadrillosJS is a reusable custom HTML element that bundles its own template, logic (bindings) and styles into a single file.
|
|
42
|
+
|
|
43
|
+
To create your first component, follow these steps:
|
|
44
|
+
|
|
45
|
+
1. Create an HTML file that defines your component’s template, script bindings and CSS. For example:
|
|
46
|
+
|
|
47
|
+
```html
|
|
48
|
+
<!-- hello.html -->
|
|
49
|
+
|
|
50
|
+
<p>Hello, LadrillosJS!</p>
|
|
51
|
+
<button onclick="increment">Clicked {count} times</button>
|
|
52
|
+
|
|
53
|
+
<script>
|
|
54
|
+
// declare a bound variable
|
|
55
|
+
let count = 0;
|
|
56
|
+
|
|
57
|
+
// declare a handler for the button click
|
|
58
|
+
const increment = () => {
|
|
59
|
+
count++;
|
|
60
|
+
// update component state and re-render
|
|
61
|
+
this.setState({ count });
|
|
62
|
+
};
|
|
63
|
+
</script>
|
|
64
|
+
|
|
65
|
+
<style>
|
|
66
|
+
/* component‐scoped CSS */
|
|
67
|
+
p {
|
|
68
|
+
font-size: 1.25rem;
|
|
69
|
+
color: #1a73e8;
|
|
70
|
+
}
|
|
71
|
+
button {
|
|
72
|
+
margin-top: 0.5rem;
|
|
73
|
+
padding: 0.5rem 1rem;
|
|
74
|
+
}
|
|
75
|
+
</style>
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
2. Import and register your component in the page where you want to use it:
|
|
79
|
+
|
|
80
|
+
```html
|
|
81
|
+
<!-- import -->
|
|
82
|
+
<script type="module">
|
|
83
|
+
import { registerComponent } from "ladrillosjs";
|
|
84
|
+
|
|
85
|
+
registerComponent("hello-world", "hello-world.html");
|
|
86
|
+
</script>
|
|
87
|
+
|
|
88
|
+
<!-- import multiple components -->
|
|
89
|
+
<script type="module">
|
|
90
|
+
import { registerComponents } from "ladrillosjs";
|
|
91
|
+
|
|
92
|
+
await registerComponents(
|
|
93
|
+
[
|
|
94
|
+
{ name: "my-widget", path: "/components/widget.html" },
|
|
95
|
+
{ name: "my-card", path: "/components/card.html" },
|
|
96
|
+
// …
|
|
97
|
+
],
|
|
98
|
+
10 // sets 10 parallel fetches - defaults to 5
|
|
99
|
+
);
|
|
100
|
+
</script>
|
|
101
|
+
|
|
102
|
+
<!-- CDN -->
|
|
103
|
+
<script type="module">
|
|
104
|
+
ladrillosjs.registerComponent("hello-world", "hello-world.html");
|
|
105
|
+
</script>
|
|
106
|
+
|
|
107
|
+
<!-- CDN multiple components -->
|
|
108
|
+
<script type="module">
|
|
109
|
+
await ladrillos.registerComponents(
|
|
110
|
+
[
|
|
111
|
+
{ name: "my-widget", path: "/components/widget.html" },
|
|
112
|
+
{ name: "my-card", path: "/components/card.html" },
|
|
113
|
+
// …
|
|
114
|
+
],
|
|
115
|
+
10 // sets 10 parallel fetches - defaults to 5
|
|
116
|
+
);
|
|
117
|
+
</script>
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
```html
|
|
121
|
+
<!-- then use it in markup -->
|
|
122
|
+
<hello-world></hello-world>
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Under the hood, LadrillosJS will fetch, parse and cache hello.html, then define a `<hello-world>`.
|
|
126
|
+
|
|
127
|
+
- Template placeholders `{…}` automatically bind to this.state.
|
|
128
|
+
- Top‐level `let/const/function` in your `<script>` block are hoisted and initialized into `this.state` if they appear in a template or event.
|
|
129
|
+
- Event attributes like `onclick="increment"` register listeners under the hood.
|
|
130
|
+
|
|
131
|
+
## Binding Variables & Events
|
|
132
|
+
|
|
133
|
+
- To bind data into your markup, wrap state keys in `{}`
|
|
134
|
+
|
|
135
|
+
```html
|
|
136
|
+
<span>{user.name}</span>
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
- To bind an event, prefix an attribute with `on`:
|
|
33
140
|
|
|
34
141
|
```html
|
|
35
|
-
|
|
36
|
-
<html lang="en">
|
|
37
|
-
<head>
|
|
38
|
-
<meta charset="UTF-8" />
|
|
39
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
40
|
-
<title>Hello World</title>
|
|
41
|
-
<style>
|
|
42
|
-
:root {
|
|
43
|
-
--btn-bg: #1a73e8;
|
|
44
|
-
--btn-color: #ffffff;
|
|
45
|
-
--btn-padding: 0.75rem 1.5rem;
|
|
46
|
-
--btn-radius: 0.375rem;
|
|
47
|
-
--btn-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
48
|
-
--btn-hover-bg: #1669c1;
|
|
49
|
-
--btn-transition: background-color 0.2s ease, transform 0.2s ease,
|
|
50
|
-
box-shadow 0.2s ease;
|
|
51
|
-
}
|
|
52
|
-
body {
|
|
53
|
-
display: flex;
|
|
54
|
-
justify-content: center;
|
|
55
|
-
align-items: center;
|
|
56
|
-
height: 100vh;
|
|
57
|
-
margin: 0;
|
|
58
|
-
}
|
|
59
|
-
</style>
|
|
60
|
-
</head>
|
|
61
|
-
<body>
|
|
62
|
-
<!-- Add component -->
|
|
63
|
-
<alert-button></alert-button>
|
|
64
|
-
<script type="module">
|
|
65
|
-
// import framework
|
|
66
|
-
import { ladrillos } from "ladrillosjs";
|
|
67
|
-
// register component (name, location)
|
|
68
|
-
ladrillos.registerComponent("alert-button", "alert-button.html");
|
|
69
|
-
</script>
|
|
70
|
-
</body>
|
|
71
|
-
</html>
|
|
142
|
+
<button onclick="doSomething">Do it</button>
|
|
72
143
|
```
|
|
73
144
|
|
|
74
|
-
|
|
145
|
+
## Initializing from Attributes
|
|
146
|
+
|
|
147
|
+
Component attributes sync to `this.state` automatically and can be reference by using `this.state["some-prop"]` in your template or code.
|
|
148
|
+
|
|
149
|
+
## Internal vs. External Scripts
|
|
75
150
|
|
|
76
|
-
|
|
151
|
+
- Inline scripts (no src) are parsed, top‑level bindings registered, then executed in component context.
|
|
152
|
+
- External scripts with `bind` attribute are fetched, and processed exactly like inline scripts.
|
|
153
|
+
|
|
154
|
+
- For external module scripts with `bind` attribute, you must export a default function where methods are defined on the component instance:
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
// component-logic.js
|
|
158
|
+
export default function () {
|
|
159
|
+
this.handleClick = () => {
|
|
160
|
+
console.log("Button clicked");
|
|
161
|
+
this.setState({ clicked: true });
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
```
|
|
77
165
|
|
|
78
166
|
```html
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
background: var(--btn-bg);
|
|
82
|
-
color: var(--btn-color);
|
|
83
|
-
padding: var(--btn-padding);
|
|
84
|
-
border: none;
|
|
85
|
-
border-radius: var(--btn-radius);
|
|
86
|
-
box-shadow: var(--btn-shadow);
|
|
87
|
-
font-size: 1rem;
|
|
88
|
-
font-weight: 600;
|
|
89
|
-
letter-spacing: 0.5px;
|
|
90
|
-
cursor: pointer;
|
|
91
|
-
transition: var(--btn-transition);
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
button:hover {
|
|
95
|
-
background: var(--btn-hover-bg);
|
|
96
|
-
transform: translateY(-1px);
|
|
97
|
-
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.12);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
button:active {
|
|
101
|
-
transform: translateY(0);
|
|
102
|
-
box-shadow: var(--btn-shadow);
|
|
103
|
-
opacity: 0.9;
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
button:focus {
|
|
107
|
-
outline: none;
|
|
108
|
-
box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.4);
|
|
109
|
-
}
|
|
110
|
-
</style>
|
|
111
|
-
<button onclick="{increaseCount()}">Clicked: {count}</button>
|
|
167
|
+
<!-- In your component HTML -->
|
|
168
|
+
<button onclick="handleClick">Click me</button>
|
|
112
169
|
|
|
113
|
-
<script>
|
|
114
|
-
|
|
170
|
+
<script src="component-logic.js" type="module" bind></script>
|
|
171
|
+
```
|
|
115
172
|
|
|
116
|
-
|
|
117
|
-
|
|
173
|
+
```js
|
|
174
|
+
<script src="path_to_file.js" bind></script>
|
|
175
|
+
```
|
|
118
176
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
177
|
+
- External scripts without bind are injected via a `<script>` tag (for non‑module, or third‑party scripts).
|
|
178
|
+
- `type="module"` scripts (inline or external) are added to the shadow/root as real modules.
|
|
179
|
+
|
|
180
|
+
## Managing State
|
|
181
|
+
|
|
182
|
+
To manage state in LadrillosJS, you can use the `this.setState()` method to update the component's state. The `this.state` object holds the component's state variables, and you can modify them as needed.
|
|
183
|
+
|
|
184
|
+
When you call `this.setState({ key: value, … })`, LadrillosJS will automatically re-render the component with the updated state.
|
|
185
|
+
|
|
186
|
+
## Emitting
|
|
187
|
+
|
|
188
|
+
To emit events from your component, you can use the `this.emit()` method. This allows you to trigger custom events that can be listened to by parent components or other parts of your application. If you don't pass a second argument, the event will be emitted with the component's state as the data.
|
|
189
|
+
|
|
190
|
+
```js
|
|
191
|
+
this.emit("event-name", { some: "data" });
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
To listen to emitted events, you can use the `this.listen()` method on the component instance:
|
|
195
|
+
|
|
196
|
+
```js
|
|
197
|
+
this.listen("event-name", (payload) => {
|
|
198
|
+
console.log(payload); // Access the emitted data
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Two‑Way Binding
|
|
203
|
+
|
|
204
|
+
LadrillosJS provides built‑in two‑way data binding for form controls and contenteditable elements via the `data-bind` attribute.
|
|
205
|
+
When a component is initialized, any element with `data-bind="key"` will:
|
|
206
|
+
|
|
207
|
+
- Push its initial value/content into `this.state.key`.
|
|
208
|
+
- Listen for user input (e.g. `input` or `change` events) and update `this.state.key` automatically.
|
|
209
|
+
- Re-render whenever you call `this.setState({ key: newValue })`, updating the element’s value or innerText.
|
|
210
|
+
|
|
211
|
+
Usage example:
|
|
212
|
+
|
|
213
|
+
```html
|
|
214
|
+
<!-- In your component HTML -->
|
|
215
|
+
<input type="text" placeholder="Username" data-bind="username" />
|
|
216
|
+
<div contenteditable="true" placeholder="About you…" data-bind="bio"></div>
|
|
217
|
+
<button onclick="submit">Submit</button>
|
|
218
|
+
|
|
219
|
+
<script>
|
|
220
|
+
const submit = () => {
|
|
221
|
+
console.log("Username:", this.state.username);
|
|
222
|
+
console.log("Bio:", this.state.bio);
|
|
223
|
+
// reset state
|
|
224
|
+
this.setState({ username: "", bio: "" });
|
|
122
225
|
};
|
|
123
226
|
</script>
|
|
124
227
|
```
|
|
228
|
+
|
|
229
|
+
## State Management with Stores
|
|
230
|
+
|
|
231
|
+
LadrillosJS provides a simple store implementation for managing shared state across components:
|
|
232
|
+
|
|
233
|
+
- `createStore(initialState)`: Creates a new store with the specified initial state
|
|
234
|
+
- `getState()`: Returns the current state of the store
|
|
235
|
+
- `setState(partial)`: Updates store state by merging partial object and notifies subscribers
|
|
236
|
+
- `subscribe(fn)`: Registers a callback function that executes immediately and on every state change
|
|
237
|
+
|
|
238
|
+
```js
|
|
239
|
+
import { createStore } from "ladrillosjs";
|
|
240
|
+
|
|
241
|
+
// Create a store with initial state
|
|
242
|
+
export const notesStore = createStore({ notes: [] });
|
|
243
|
+
|
|
244
|
+
// Update store state
|
|
245
|
+
export function addNote(note) {
|
|
246
|
+
const { notes } = notesStore.getState();
|
|
247
|
+
notesStore.setState({ notes: [...notes, note] });
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### add to store
|
|
252
|
+
|
|
253
|
+
```js
|
|
254
|
+
import { addNote } from "../stores/notesStore.js";
|
|
255
|
+
|
|
256
|
+
export default function () {
|
|
257
|
+
this.save = () => {
|
|
258
|
+
const id = Math.floor(Math.random() * 1000);
|
|
259
|
+
addNote({ id: 123, title: "my note", note: "my note content" });
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
### subscribing to store changes
|
|
265
|
+
|
|
266
|
+
```js
|
|
267
|
+
import { notesStore } from "../stores/notesStore.js";
|
|
268
|
+
notesStore.subscribe(({ notes }) => {
|
|
269
|
+
console.log("Notes updated:", notes);
|
|
270
|
+
});
|
|
271
|
+
```
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var T=Object.defineProperty;var E=Object.getOwnPropertySymbols;var j=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable;var W=r=>{throw TypeError(r)};var P=(r,e,t)=>e in r?T(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,x=(r,e)=>{for(var t in e||(e={}))j.call(e,t)&&P(r,t,e[t]);if(E)for(var t of E(e))H.call(e,t)&&P(r,t,e[t]);return r};var q=(r,e,t)=>e.has(r)||W("Cannot "+t);var d=(r,e,t)=>(q(r,e,"read from private field"),t?t.call(r):e.get(r)),y=(r,e,t)=>e.has(r)?W("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t);var v=(r,e,t)=>(q(r,e,"access private method"),t);var u=(r,e,t)=>new Promise((s,o)=>{var l=a=>{try{c(t.next(a))}catch(g){o(g)}},i=a=>{try{c(t.throw(a))}catch(g){o(g)}},c=a=>a.done?s(a.value):Promise.resolve(a.value).then(l,i);c((t=t.apply(r,e)).next())});const h={log(r,...e){},error(r,...e){console.error(r,...e)},warn(r,...e){}};var m,w,C,A;const S=class S{constructor(){y(this,m,new Map);y(this,w,new DOMParser);this.components={}}registerComponent(e,t,s=!0){return u(this,null,function*(){var o,l,i;if(this.components[e]){h.log(`Component ${e} already registered.`);return}this.components[e]={__registering:!0};try{const c=yield u(this,null,function*(){const n=d(this,m).get(t);if(n)return n;const k=yield(yield fetch(t)).text();return d(this,m).set(t,k),k}),a=d(this,w).parseFromString(c.replace(/<!--[\s\S]*?-->/g,""),"text/html"),g=[],$=[];for(const n of a.querySelectorAll("script")){if(n.src)$.push({src:n.src,type:(o=n.type)!=null?o:null,bind:n.hasAttribute("bind")});else if(n.textContent){let p=n.textContent.trim();p=p.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm,"").trim(),g.push({content:p,type:(l=n.type)!=null?l:null})}n.remove()}let f="";for(const n of a.querySelectorAll("link[rel='stylesheet']"))f+=`
|
|
2
|
+
`+(yield v(i=S,C,A).call(i,`${n.href}?raw`)),n.remove();for(const n of a.querySelectorAll("style")){if(n.textContent){let p=n.textContent.trim();p=p.replace(/\/\*[\s\S]*?\*\//g,"").trim(),f+=`
|
|
3
|
+
`+p}n.remove()}f=f.trim(),this.components[e]={tagName:e,template:a.body.innerHTML.trim(),scripts:g,externalScripts:$,style:f},yield this._defineWebComponent(e,s),h.log(`Component ${e} registered successfully`)}catch(c){h.error(`Failed to register component ${e}:`,c),delete this.components[e]}})}registerComponents(e,t=5){return u(this,null,function*(){const s=e.map(({name:l,path:i,useShadowDOM:c})=>()=>this.registerComponent(l,i,c)),o=yield this._runWithConcurrency(s,t);return o.forEach((l,i)=>{if(l.status==="rejected"){const{name:c}=e[i];h.error(`registration failed for ${c}:`,l.reason)}}),o})}_runWithConcurrency(e,t){return u(this,null,function*(){const s=[],o=[];for(const l of e){let i;const c=l();s.push(c),i=c.then(()=>{o.splice(o.indexOf(i),1)}),o.push(i),o.length>=t&&(yield Promise.race(o))}return Promise.allSettled(s)})}_defineWebComponent(e,t){return u(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>require("./webcomponent-6tQP-rUH.js"));s(this.components[e],t)})}};m=new WeakMap,w=new WeakMap,C=new WeakSet,A=function(e){return u(this,null,function*(){try{const t=yield fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);return yield t.text()}catch(t){return h.error(`Failed to fetch resource at ${e}:`,t),""}})},y(S,C);let b=S;const F=new b;function O(r={}){let e=r;const t=new Set;return{getState(){return e},setState(s){e=x(x({},e),s),t.forEach(o=>o(e))},subscribe(s){return t.add(s),s(e),()=>t.delete(s)},reset(){e=r,t.forEach(s=>s(e))}}}const _=(...r)=>F.registerComponent(...r),M=(...r)=>F.registerComponents(...r);typeof window!="undefined"&&(window.ladrillosjs={registerComponent:_,registerComponents:M});exports.createStore=O;exports.logger=h;exports.registerComponent=_;exports.registerComponents=M;
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
var v = Object.defineProperty;
|
|
2
|
+
var E = Object.getOwnPropertySymbols;
|
|
3
|
+
var M = Object.prototype.hasOwnProperty, T = Object.prototype.propertyIsEnumerable;
|
|
4
|
+
var A = (r) => {
|
|
5
|
+
throw TypeError(r);
|
|
6
|
+
};
|
|
7
|
+
var W = (r, e, t) => e in r ? v(r, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[e] = t, S = (r, e) => {
|
|
8
|
+
for (var t in e || (e = {}))
|
|
9
|
+
M.call(e, t) && W(r, t, e[t]);
|
|
10
|
+
if (E)
|
|
11
|
+
for (var t of E(e))
|
|
12
|
+
T.call(e, t) && W(r, t, e[t]);
|
|
13
|
+
return r;
|
|
14
|
+
};
|
|
15
|
+
var F = (r, e, t) => e.has(r) || A("Cannot " + t);
|
|
16
|
+
var d = (r, e, t) => (F(r, e, "read from private field"), t ? t.call(r) : e.get(r)), y = (r, e, t) => e.has(r) ? A("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(r) : e.set(r, t);
|
|
17
|
+
var P = (r, e, t) => (F(r, e, "access private method"), t);
|
|
18
|
+
var u = (r, e, t) => new Promise((s, o) => {
|
|
19
|
+
var l = (a) => {
|
|
20
|
+
try {
|
|
21
|
+
c(t.next(a));
|
|
22
|
+
} catch (f) {
|
|
23
|
+
o(f);
|
|
24
|
+
}
|
|
25
|
+
}, i = (a) => {
|
|
26
|
+
try {
|
|
27
|
+
c(t.throw(a));
|
|
28
|
+
} catch (f) {
|
|
29
|
+
o(f);
|
|
30
|
+
}
|
|
31
|
+
}, c = (a) => a.done ? s(a.value) : Promise.resolve(a.value).then(l, i);
|
|
32
|
+
c((t = t.apply(r, e)).next());
|
|
33
|
+
});
|
|
34
|
+
const g = {
|
|
35
|
+
/**
|
|
36
|
+
* Log a message only in development mode
|
|
37
|
+
* @param {string} message - The message to log
|
|
38
|
+
* @param {any[]} args - Additional arguments to log
|
|
39
|
+
*/
|
|
40
|
+
log(r, ...e) {
|
|
41
|
+
},
|
|
42
|
+
/**
|
|
43
|
+
* Log an error (always logs in both dev and production)
|
|
44
|
+
* @param {string} message - The error message
|
|
45
|
+
* @param {any[]} args - Additional arguments to log
|
|
46
|
+
*/
|
|
47
|
+
error(r, ...e) {
|
|
48
|
+
console.error(r, ...e);
|
|
49
|
+
},
|
|
50
|
+
/**
|
|
51
|
+
* Log a warning only in development mode
|
|
52
|
+
* @param {string} message - The warning message
|
|
53
|
+
* @param {any[]} args - Additional arguments to log
|
|
54
|
+
*/
|
|
55
|
+
warn(r, ...e) {
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
var m, w, C, _;
|
|
59
|
+
const x = class x {
|
|
60
|
+
constructor() {
|
|
61
|
+
y(this, m, /* @__PURE__ */ new Map());
|
|
62
|
+
y(this, w, new DOMParser());
|
|
63
|
+
this.components = {};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Registers a web‐component by fetching its HTML, scripts, and styles.
|
|
67
|
+
* @param {string} name
|
|
68
|
+
* @param {string} path
|
|
69
|
+
* @param {boolean} [useShadowDOM=true]
|
|
70
|
+
*/
|
|
71
|
+
registerComponent(e, t, s = !0) {
|
|
72
|
+
return u(this, null, function* () {
|
|
73
|
+
var o, l, i;
|
|
74
|
+
if (this.components[e]) {
|
|
75
|
+
g.log(`Component ${e} already registered.`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this.components[e] = { __registering: !0 };
|
|
79
|
+
try {
|
|
80
|
+
const c = yield u(this, null, function* () {
|
|
81
|
+
const n = d(this, m).get(t);
|
|
82
|
+
if (n) return n;
|
|
83
|
+
const k = yield (yield fetch(t)).text();
|
|
84
|
+
return d(this, m).set(t, k), k;
|
|
85
|
+
}), a = d(this, w).parseFromString(
|
|
86
|
+
c.replace(/<!--[\s\S]*?-->/g, ""),
|
|
87
|
+
"text/html"
|
|
88
|
+
), f = [], $ = [];
|
|
89
|
+
for (const n of a.querySelectorAll("script")) {
|
|
90
|
+
if (n.src)
|
|
91
|
+
$.push({
|
|
92
|
+
src: n.src,
|
|
93
|
+
type: (o = n.type) != null ? o : null,
|
|
94
|
+
bind: n.hasAttribute("bind")
|
|
95
|
+
});
|
|
96
|
+
else if (n.textContent) {
|
|
97
|
+
let p = n.textContent.trim();
|
|
98
|
+
p = p.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, "").trim(), f.push({
|
|
99
|
+
content: p,
|
|
100
|
+
type: (l = n.type) != null ? l : null
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
n.remove();
|
|
104
|
+
}
|
|
105
|
+
let h = "";
|
|
106
|
+
for (const n of a.querySelectorAll("link[rel='stylesheet']"))
|
|
107
|
+
h += `
|
|
108
|
+
` + (yield P(i = x, C, _).call(i, `${n.href}?raw`)), n.remove();
|
|
109
|
+
for (const n of a.querySelectorAll("style")) {
|
|
110
|
+
if (n.textContent) {
|
|
111
|
+
let p = n.textContent.trim();
|
|
112
|
+
p = p.replace(/\/\*[\s\S]*?\*\//g, "").trim(), h += `
|
|
113
|
+
` + p;
|
|
114
|
+
}
|
|
115
|
+
n.remove();
|
|
116
|
+
}
|
|
117
|
+
h = h.trim(), this.components[e] = {
|
|
118
|
+
tagName: e,
|
|
119
|
+
template: a.body.innerHTML.trim(),
|
|
120
|
+
scripts: f,
|
|
121
|
+
externalScripts: $,
|
|
122
|
+
style: h
|
|
123
|
+
}, yield this._defineWebComponent(e, s), g.log(`Component ${e} registered successfully`);
|
|
124
|
+
} catch (c) {
|
|
125
|
+
g.error(`Failed to register component ${e}:`, c), delete this.components[e];
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Registers multiple components with optional concurrency throttling.
|
|
131
|
+
* @param {{name: string, path: string,useShadowDOM:boolean}[]} components
|
|
132
|
+
* @param {number} [concurrency=5] max simultaneous registrations
|
|
133
|
+
*/
|
|
134
|
+
registerComponents(e, t = 5) {
|
|
135
|
+
return u(this, null, function* () {
|
|
136
|
+
const s = e.map(
|
|
137
|
+
({ name: l, path: i, useShadowDOM: c }) => () => this.registerComponent(l, i, c)
|
|
138
|
+
), o = yield this._runWithConcurrency(s, t);
|
|
139
|
+
return o.forEach((l, i) => {
|
|
140
|
+
if (l.status === "rejected") {
|
|
141
|
+
const { name: c } = e[i];
|
|
142
|
+
g.error(`registration failed for ${c}:`, l.reason);
|
|
143
|
+
}
|
|
144
|
+
}), o;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/** @private */
|
|
148
|
+
_runWithConcurrency(e, t) {
|
|
149
|
+
return u(this, null, function* () {
|
|
150
|
+
const s = [], o = [];
|
|
151
|
+
for (const l of e) {
|
|
152
|
+
let i;
|
|
153
|
+
const c = l();
|
|
154
|
+
s.push(c), i = c.then(() => {
|
|
155
|
+
o.splice(o.indexOf(i), 1);
|
|
156
|
+
}), o.push(i), o.length >= t && (yield Promise.race(o));
|
|
157
|
+
}
|
|
158
|
+
return Promise.allSettled(s);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** @private */
|
|
162
|
+
_defineWebComponent(e, t) {
|
|
163
|
+
return u(this, null, function* () {
|
|
164
|
+
const { defineWebComponent: s } = yield import("./webcomponent-BGA1yU7J.mjs");
|
|
165
|
+
s(this.components[e], t);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
m = new WeakMap(), w = new WeakMap(), C = new WeakSet(), _ = function(e) {
|
|
170
|
+
return u(this, null, function* () {
|
|
171
|
+
try {
|
|
172
|
+
const t = yield fetch(e);
|
|
173
|
+
if (!t.ok) throw new Error(`HTTP ${t.status}`);
|
|
174
|
+
return yield t.text();
|
|
175
|
+
} catch (t) {
|
|
176
|
+
return g.error(`Failed to fetch resource at ${e}:`, t), "";
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}, y(x, C);
|
|
180
|
+
let b = x;
|
|
181
|
+
const q = new b();
|
|
182
|
+
function D(r = {}) {
|
|
183
|
+
let e = r;
|
|
184
|
+
const t = /* @__PURE__ */ new Set();
|
|
185
|
+
return {
|
|
186
|
+
// read-only access
|
|
187
|
+
getState() {
|
|
188
|
+
return e;
|
|
189
|
+
},
|
|
190
|
+
// update state by merging partial, then notify
|
|
191
|
+
setState(s) {
|
|
192
|
+
e = S(S({}, e), s), t.forEach((o) => o(e));
|
|
193
|
+
},
|
|
194
|
+
// subscribe: fn will be called immediately and on every change
|
|
195
|
+
subscribe(s) {
|
|
196
|
+
return t.add(s), s(e), () => t.delete(s);
|
|
197
|
+
},
|
|
198
|
+
// clear store
|
|
199
|
+
reset() {
|
|
200
|
+
e = r, t.forEach((s) => s(e));
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
const j = (...r) => q.registerComponent(...r), H = (...r) => q.registerComponents(...r);
|
|
205
|
+
typeof window != "undefined" && (window.ladrillosjs = {
|
|
206
|
+
registerComponent: j,
|
|
207
|
+
registerComponents: H
|
|
208
|
+
// changed code
|
|
209
|
+
});
|
|
210
|
+
export {
|
|
211
|
+
H as a,
|
|
212
|
+
D as c,
|
|
213
|
+
g as l,
|
|
214
|
+
j as r
|
|
215
|
+
};
|
package/dist/ladrillosjs.cjs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-5_a431JU.js");exports.createStore=e.createStore;exports.registerComponent=e.registerComponent;exports.registerComponents=e.registerComponents;
|
package/dist/ladrillosjs.es.js
CHANGED
package/dist/ladrillosjs.umd.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`+(yield b(t))
|
|
3
|
-
`+i.textContent,i.
|
|
4
|
-
`+(yield b(t+"?raw"))),i.remove()}const T=Array.from(w.querySelectorAll("style"));for(const i of T)y+=`
|
|
5
|
-
`+i.textContent,i.remove();y=y.trim();const v=document.createElement("template");v.innerHTML=w.body.innerHTML,this.components[c]={tagName:c,template:v,script:E,style:y,externalScripts:f},this._defineWebComponent(c,u),e.log(`Component ${c} registered successfully`)}catch(f){e.error(`Failed to register component ${c}:`,f)}})}_defineWebComponent(c,d){return A(this,null,function*(){const{defineWebComponent:u}=yield Promise.resolve().then(()=>x);u(this.components[c],d)})}}p=new WeakMap,C(_,"_SCRIPT_ALL",/<script>([\s\S]*?)<\/script>/g),C(_,"_STYLE_ALL",/<style>([\s\S]*?)<\/style>/g),C(_,"_SCRIPT_ONE",/<script>([\s\S]*?)<\/script>/),C(_,"_STYLE_ONE",/<style>([\s\S]*?)<\/style>/);const S=new _;function $(a,c={}){return new Proxy(c,{set(d,u,f){const g=d[u];return d[u]=f,g!==f&&!a._initializing&&(typeof a._updateBinding=="function"?a._updateBinding(u,f):a._update()),!0},get(d,u){return d[u]}})}const x=Object.freeze(Object.defineProperty({__proto__:null,defineWebComponent:(a,c)=>{if(!a){e.error("Component is not defined or invalid.");return}if(customElements.get(a.tagName)){e.warn(`Component ${a.tagName} is already defined.`);return}const{tagName:d,template:u,script:f,style:g,externalScripts:N}=a,R=/{(.*?)}/g,w=/{\s*([\w$]+)\(\)\s*}/,B=(i=>{const t=new Set;return i.innerHTML.replace(R,(r,s)=>t.add(s.trim().toLowerCase())),Array.from(t)})(u),b=f.replace(/\b(?:const|let|var)\s+([\w$]+)\s*=/g,"state.$1 =").replace(/function\s+([\w$]+)\s*\(/g,"state.$1 = function (").replace(/\bclass\s+([\w$]+)\s*(extends\s+[\w$]+\s*)?{/g,"state.$1 = class $1 $2{"),y=f?new Function("state",`with(state){${b}}`):()=>{},T=(i=>{const t=[];return i.content.querySelectorAll("*").forEach(r=>{Array.from(r.attributes).forEach(s=>{if(!s.name.startsWith("on"))return;const l=s.name.slice(2),m=s.value.match(w);m&&(r.dataset._evtIndex=t.length,t.push({evt:l,fnName:m[1]}),r.removeAttribute(s.name))})}),t})(u);class v extends HTMLElement{constructor(){super(),c&&this.attachShadow({mode:"open"}),this.state={},this.styleElement=document.createElement("style"),this.scriptElement=document.createElement("script"),this.styleElement.textContent=g||"",this._textBindings={},this._origText=new Map,this._hasConnected=!1,this._isUpdating=!1,this._isBinding=!1}connectedCallback(){if(this._hasConnected)return;this._hasConnected=!0,this._textBindings={},this._origText=new Map;const t=u.content.cloneNode(!0);this.shadowRoot?this.shadowRoot.innerHTML="":this.innerHTML="",N.forEach(s=>{const l=document.createElement("script");l.src=s,l.onload=()=>{e.log(`Loaded external script: ${s}`)},document.head.appendChild(l)}),this.shadowRoot?(this.shadowRoot.appendChild(this.scriptElement),this.shadowRoot.appendChild(this.styleElement),this.shadowRoot.appendChild(t)):(this.appendChild(this.styleElement),this.appendChild(t)),this.state=$(this,{}),this._initializing=!0;try{y.call(this,this.state)}catch(s){console.error("Error initializing component script:",s)}finally{this._initializing=!1}const r=this.shadowRoot||this;this._processTemplate(r)}_processTemplate(t){this._getAllTextNodes(t).forEach(s=>{const l=s.textContent;l.includes("{")&&l.includes("}")&&(this._origText.set(s,l),s.textContent=l.replace(/{([^}]+)}/g,(m,h)=>(h=h.trim(),this._textBindings[h]=this._textBindings[h]||[],this._textBindings[h].push(s),this.hasAttribute(h)?this.getAttribute(h):this.state[h]!==void 0?this.state[h]:m)))}),T.forEach((s,l)=>{const m=t.querySelector(`[data-_evt-index="${l}"]`);m.removeAttribute("data-_evt-index"),m.addEventListener(s.evt,h=>{const H=this.state[s.fnName];typeof H=="function"&&H.call(m,h)})})}_getAllTextNodes(t){const r=[],s=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null,!1);let l;for(;l=s.nextNode();)r.push(l);return r}_update(){if(!this._isUpdating){this._isUpdating=!0;try{const t=u.content.cloneNode(!0);this._processTemplate(t),this.shadowRoot?(this.shadowRoot.innerHTML="",this.shadowRoot.appendChild(this.styleElement),this.shadowRoot.appendChild(t)):(this.innerHTML="",this.appendChild(this.styleElement),this.appendChild(t))}finally{this._isUpdating=!1}}}_updateBinding(t){if(!this._isBinding){this._isBinding=!0;try{(this._textBindings[t]||[]).forEach(s=>{const l=this._origText.get(s)||"";s.textContent=l.replace(R,(m,h)=>(h=h.trim(),this.hasAttribute(h)?this.getAttribute(h):this.state[h]))})}finally{this._isBinding=!1,this.emit(t,this.state[t])}}}disconnectedCallback(){this._hasConnected=!1,T.forEach((t,r)=>{const s=(this.shadowRoot||this).querySelector(`[data-_evt-index="${r}"]`);s&&s.removeEventListener(t.evt,this.state[t.fnName])}),e.log("disconnectedCallback",this)}static get observedAttributes(){return B}attributeChangedCallback(t,r,s){r!==s&&(this.state[t]=s)}emit(t,r){const s=r!=null?r:this.state;this.dispatchEvent(new CustomEvent(t,{detail:s,bubbles:!0}))}querySelector(t){return this.shadowRoot?this.shadowRoot.querySelector(t):super.querySelector(t)}querySelectorAll(t){return this.shadowRoot?this.shadowRoot.querySelectorAll(t):super.querySelectorAll(t)}}customElements.define(d,v),e.log(`Web component defined: <${d}></${d}>`)}},Symbol.toStringTag,{value:"Module"}));n.ladrillos=S,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(c,a){typeof exports=="object"&&typeof module!="undefined"?a(exports):typeof define=="function"&&define.amd?define(["exports"],a):(c=typeof globalThis!="undefined"?globalThis:c||self,a(c.ladrillosjs={}))})(this,function(c){"use strict";var J=Object.defineProperty;var P=Object.getOwnPropertySymbols;var D=Object.prototype.hasOwnProperty,G=Object.prototype.propertyIsEnumerable;var U=c=>{throw TypeError(c)};var z=(c,a,l)=>a in c?J(c,a,{enumerable:!0,configurable:!0,writable:!0,value:l}):c[a]=l,M=(c,a)=>{for(var l in a||(a={}))D.call(a,l)&&z(c,l,a[l]);if(P)for(var l of P(a))G.call(a,l)&&z(c,l,a[l]);return c};var V=(c,a,l)=>a.has(c)||U("Cannot "+l);var j=(c,a,l)=>(V(c,a,"read from private field"),l?l.call(c):a.get(c)),k=(c,a,l)=>a.has(c)?U("Cannot add the same private member more than once"):a instanceof WeakSet?a.add(c):a.set(c,l);var H=(c,a,l)=>(V(c,a,"access private method"),l);var S=(c,a,l)=>new Promise((A,T)=>{var q=w=>{try{x(l.next(w))}catch($){T($)}},L=w=>{try{x(l.throw(w))}catch($){T($)}},x=w=>w.done?A(w.value):Promise.resolve(w.value).then(q,L);x((l=l.apply(c,a)).next())});var B,W,N,Z;var a=typeof document!="undefined"?document.currentScript:null;const l={log(y,...r){},error(y,...r){console.error(y,...r)},warn(y,...r){}},R=class R{constructor(){k(this,B,new Map);k(this,W,new DOMParser);this.components={}}registerComponent(r,h,f=!0){return S(this,null,function*(){var p,_,b;if(this.components[r]){l.log(`Component ${r} already registered.`);return}this.components[r]={__registering:!0};try{const m=yield S(this,null,function*(){const t=j(this,B).get(h);if(t)return t;const e=yield(yield fetch(h)).text();return j(this,B).set(h,e),e}),v=j(this,W).parseFromString(m.replace(/<!--[\s\S]*?-->/g,""),"text/html"),O=[],E=[];for(const t of v.querySelectorAll("script")){if(t.src)E.push({src:t.src,type:(p=t.type)!=null?p:null,bind:t.hasAttribute("bind")});else if(t.textContent){let n=t.textContent.trim();n=n.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm,"").trim(),O.push({content:n,type:(_=t.type)!=null?_:null})}t.remove()}let F="";for(const t of v.querySelectorAll("link[rel='stylesheet']"))F+=`
|
|
2
|
+
`+(yield H(b=R,N,Z).call(b,`${t.href}?raw`)),t.remove();for(const t of v.querySelectorAll("style")){if(t.textContent){let n=t.textContent.trim();n=n.replace(/\/\*[\s\S]*?\*\//g,"").trim(),F+=`
|
|
3
|
+
`+n}t.remove()}F=F.trim(),this.components[r]={tagName:r,template:v.body.innerHTML.trim(),scripts:O,externalScripts:E,style:F},yield this._defineWebComponent(r,f),l.log(`Component ${r} registered successfully`)}catch(m){l.error(`Failed to register component ${r}:`,m),delete this.components[r]}})}registerComponents(r,h=5){return S(this,null,function*(){const f=r.map(({name:_,path:b,useShadowDOM:m})=>()=>this.registerComponent(_,b,m)),p=yield this._runWithConcurrency(f,h);return p.forEach((_,b)=>{if(_.status==="rejected"){const{name:m}=r[b];l.error(`registration failed for ${m}:`,_.reason)}}),p})}_runWithConcurrency(r,h){return S(this,null,function*(){const f=[],p=[];for(const _ of r){let b;const m=_();f.push(m),b=m.then(()=>{p.splice(p.indexOf(b),1)}),p.push(b),p.length>=h&&(yield Promise.race(p))}return Promise.allSettled(f)})}_defineWebComponent(r,h){return S(this,null,function*(){const{defineWebComponent:f}=yield Promise.resolve().then(()=>$);f(this.components[r],h)})}};B=new WeakMap,W=new WeakMap,N=new WeakSet,Z=function(r){return S(this,null,function*(){try{const h=yield fetch(r);if(!h.ok)throw new Error(`HTTP ${h.status}`);return yield h.text()}catch(h){return l.error(`Failed to fetch resource at ${r}:`,h),""}})},k(R,N);let A=R;const T=new A;function q(y={}){let r=y;const h=new Set;return{getState(){return r},setState(f){r=M(M({},r),f),h.forEach(p=>p(r))},subscribe(f){return h.add(f),f(r),()=>h.delete(f)},reset(){r=y,h.forEach(f=>f(r))}}}const L=(...y)=>T.registerComponent(...y),x=(...y)=>T.registerComponents(...y);typeof window!="undefined"&&(window.ladrillosjs={registerComponent:L,registerComponents:x});const $=Object.freeze(Object.defineProperty({__proto__:null,defineWebComponent:(y,r)=>{var v,I;const{tagName:h,template:f,scripts:p,externalScripts:_,style:b}=y,E=class E extends HTMLElement{constructor(){super(),r&&this.attachShadow({mode:"open"}),this.root=r?this.shadowRoot:document,this.state={},this._bindings=[],this._eventBindings=[],this.observer=new MutationObserver(t=>{t.forEach(n=>{if(n.type==="attributes"){const e=n.attributeName,s=this.getAttribute(e);this._handleAttributeChange(e,s)}})}),this.observer.observe(this,{attributes:!0,attributeOldValue:!0})}connectedCallback(){this._loadTemplate(),this._loadStyles(),this._loadScript(),this._initializeStateFromAttributes(),this._setupTwoWayBindings()}disconnectedCallback(){this.observer.disconnect(),this._eventBindings.forEach(({element:t,event:n,listener:e})=>{t.removeEventListener(n,e)}),this._eventBindings=[]}_handleAttributeChange(t,n){var s;const e=H(s=E,v,I).call(s,n);this.state[t]=e,this._render()}_loadTemplate(){r?this.shadowRoot.innerHTML=f:this.innerHTML=f,this._scanBindings()}_scanBindings(){const t=document.createTreeWalker(this.root,NodeFilter.SHOW_TEXT,null,!1);let n;for(;n=t.nextNode();){const e=[...n.textContent.matchAll(/{([^}]+)}/g)];if(e.length){const s=e.map(([,i])=>({node:n,template:n.textContent,key:i.trim()}));this._bindings.push(s)}}this.root.querySelectorAll("*").forEach(e=>{Array.from(e.attributes).forEach(s=>{const i=[...s.value.matchAll(/{([^}]+)}/g)];i.length&&i.forEach(([,o])=>{this._bindings.push({element:e,attrName:s.name,template:s.value,key:o.trim()})})})}),this._getEventBindings()}_getEventBindings(){this.root.querySelectorAll("*").forEach(t=>{Array.from(t.attributes).forEach(n=>{if(!n.name.startsWith("on"))return;const e=n.name.slice(2),s=n.value.trim();t.removeAttribute(n.name);let i;const o=s.trim();if(/^\([^)]*\)\s*=>/.test(o)){const u=new Function(`return (${o})`).call(this);i=d=>u(d)}else o.includes("(")?i=()=>new Function(`return ${o}`).call(this):i=u=>{typeof this[o]=="function"?this[o](u):typeof this.state[o]=="function"&&this.state[o](u)};t.addEventListener(e,i),this._eventBindings.push({key:s,element:t,event:e,listener:i})})})}_loadStyles(){const t=document.createElement("style");t.textContent=b,r?this.root.appendChild(t):this.root.head.appendChild(t)}_loadScript(){return S(this,null,function*(){var t;for(const n of _){const e=new URL(n.src,typeof document=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:a&&a.tagName.toUpperCase()==="SCRIPT"&&a.src||new URL("ladrillosjs.umd.js",document.baseURI).href).href;if(n.type==="module"&&(n!=null&&n.bind))try{const s=yield import(e);typeof s.default=="function"?s.default.call(this):typeof s.init=="function"?s.init.call(this):l.error(`Module ${n.src} does not export a default function or init function.`)}catch(s){console.error(`Failed to load component module ${n.src}`,s)}else n!=null&&n.bind?yield fetch(e).then(s=>s.text()).then(s=>this._processScriptText(s.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm,"").trim())):yield this._injectScriptTag(n.src,n.type)}for(const n of p)if(n.type==="module"){const e=document.createElement("script");e.type="module",e.textContent=n.content,((t=this.shadowRoot)!=null?t:this).appendChild(e)}else this._processScriptText(n.content);this._render()})}_injectScriptTag(t,n){return new Promise((e,s)=>{const i=document.createElement("script");i.src=t,n&&(i.type=n),i.onload=e,i.onerror=s,document.head.appendChild(i)})}_initializeStateFromAttributes(){this.getAttributeNames().forEach(t=>{const n=this.getAttribute(t);this._handleAttributeChange(t,n)})}_setupTwoWayBindings(){const t=this.root.querySelectorAll("[data-bind]"),n={};t.forEach(e=>{const s=e.getAttribute("data-bind"),i=e.isContentEditable,o="value"in e,u=i||o?"input":"change",d=()=>{const X=i?e.innerText:o?e.value:e.textContent;this.setState({[s]:X})};e.addEventListener(u,d),this._eventBindings.push({element:e,event:u,listener:d});const g=o?"value":void 0,C=o?e.getAttribute("value")||`{${s}}`:i?e.innerHTML:e.textContent;this._bindings.push({element:e,key:s,attrName:g,template:C}),n[s]=o?e.value:i?e.innerText:e.textContent}),this.setState(n)}_render(){this._bindings.forEach(t=>{const n=Array.isArray(t)?t:[t],{node:e,template:s}=n[0];if(!e)return;const i={};n.forEach(({key:d})=>{var g;i[d]=(g=this.state[d])!=null?g:""});const o=this._renderTemplate(s,i);if(/<[a-z][\s\S]*>/i.test(o)){const d=document.createRange().createContextualFragment(o);e.nodeType===Node.TEXT_NODE?e.replaceWith(d):e.innerHTML=o}else e==null||e.nodeType,Node.TEXT_NODE,e.textContent=o}),this._bindings.filter(t=>t.element).forEach(({element:t,attrName:n,template:e,key:s})=>{var u;const i=(u=s.split(".").reduce((d,g)=>d==null?void 0:d[g],this.state))!=null?u:"",o=new RegExp(`\\{\\s*${s}\\s*\\}`,"g");t.setAttribute(n,e.replace(o,i))}),this.root.querySelectorAll("[data-bind]").forEach(t=>{var s;const n=t.getAttribute("data-bind"),e=(s=this.state[n])!=null?s:"";t.isContentEditable?t.innerText!==e&&(t.innerText=e):"value"in t?t.value!==e&&(t.value=e):t.textContent!==e&&(t.textContent=e)})}_renderTemplate(t,n){return t.replace(/\{\s*([-\w.]+)\s*}/g,(e,s)=>{let i=s.split(".").reduce((o,u)=>o==null?void 0:o[u],this.state);if(typeof i=="function")try{i=i.call(this)}catch(o){i=""}return i!=null?i:""})}_processScriptText(t){const n=/(?:const|let|var)\s+([$_A-Za-z][$_A-Za-z0-9]*)\s*=\s*([\s\S]+?);/g,e=/=>\s*{([\s\S]*?)};/g,s={};let i=0;for(;(i=t.indexOf("function ",i))!==-1;){const u=/^function\s+([$_A-Za-z][$_A-Za-z0-9]*)\s*\([^)]*\)\s*{/.exec(t.slice(i));if(!u){i+=8;continue}const d=u[1];let g=0,C=i+u[0].length-1;do t[C]==="{"?g++:t[C]==="}"&&g--,C++;while(C<t.length&&g>0);s[d]=t.slice(i,C),i=C}for(const u in s)if(this._isBound(u))try{const d=new Function(`return (${s[u]});`).call(this).bind(this);this[u]=d}catch(d){console.error("failed to eval function",u,d)}let o;for(;o=n.exec(t);){const[,u,d]=o;if(!this._isBound(u))continue;const g=this._evalExpression(d.trim(),t,e,u);typeof g=="function"?this[u]=g.bind(this):this.state[u]=g}new Function(t).call(this)}_evalExpression(t,n,e,s){try{return new Function(`return (${t});`).call(this)}catch(i){let o,u;for(;o=e.exec(n);)if(u=o[1].trim(),u)try{return new Function(`${u}`).bind(this)}catch(d){return console.error(d),u}return t}}_isBound(t){const n=this._eventBindings.some(s=>s.key===t),e=this._bindings.some(s=>Array.isArray(s)?s.some(i=>i.key===t):s.key===t);return n||e}emit(t,n){const e=n!=null?n:this.state;this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}listen(t,n){const e=s=>n(s.detail);document.addEventListener(t,e),this._eventBindings.push({element:document,event:t,listener:e})}setState(t){Object.assign(this.state,t),this._render()}querySelector(t){return this.root.querySelector(t)}querySelectorAll(t){return this.root.querySelectorAll(t)}};v=new WeakSet,I=function(t){if(t==="")return null;if(t!=="undefined")try{return JSON.parse(t)}catch(n){return t}},k(E,v);let m=E;customElements.define(h,m),l.log(`Web component defined: <${h}></${h}>`)}},Symbol.toStringTag,{value:"Module"}));c.createStore=q,c.registerComponent=L,c.registerComponents=x,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|