ladrillosjs 2.0.0-beta.3.5 → 2.0.0-beta.3.7
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 +258 -0
- package/dist/index-Bx3jQFpE.js +68 -0
- package/dist/{index-CBW3yTb-.js.map → index-Bx3jQFpE.js.map} +1 -1
- package/dist/{index-COl4zCLy.mjs → index-DZqKSX8_.mjs} +220 -142
- package/dist/{index-COl4zCLy.mjs.map → index-DZqKSX8_.mjs.map} +1 -1
- package/dist/ladrillosjs.cjs.js +1 -1
- package/dist/ladrillosjs.es.js +1 -1
- package/dist/ladrillosjs.umd.js +89 -18
- package/dist/ladrillosjs.umd.js.map +1 -1
- package/dist/vite/copyComponentsPlugin.d.ts +7 -1
- package/dist/vite.cjs +50 -1
- package/dist/vite.cjs.map +3 -3
- package/dist/vite.js +50 -1
- package/dist/vite.js.map +3 -3
- package/dist/webcomponent-BRRZJV0q.js +111 -0
- package/dist/webcomponent-BRRZJV0q.js.map +1 -0
- package/dist/{webcomponent-WCW6485Z.mjs → webcomponent-DyrhK3aa.mjs} +273 -224
- package/dist/webcomponent-DyrhK3aa.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/index-CBW3yTb-.js +0 -19
- package/dist/webcomponent-BdxW-3sK.js +0 -89
- package/dist/webcomponent-BdxW-3sK.js.map +0 -1
- package/dist/webcomponent-WCW6485Z.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -23,6 +23,7 @@ A lightweight, zero-dependency web component framework for building modular web
|
|
|
23
23
|
- [List Rendering](#list-rendering)
|
|
24
24
|
- [Slots](#slots)
|
|
25
25
|
- [Component Props](#component-props)
|
|
26
|
+
- [Lifecycle Hooks](#lifecycle-hooks)
|
|
26
27
|
- [Advanced Features](#advanced-features)
|
|
27
28
|
- [Lazy Loading](#lazy-loading)
|
|
28
29
|
- [Global Event Bus](#global-event-bus)
|
|
@@ -142,9 +143,83 @@ interface CopyComponentsOptions {
|
|
|
142
143
|
|
|
143
144
|
/** Copy during development server (default: false) */
|
|
144
145
|
copyOnDev?: boolean;
|
|
146
|
+
|
|
147
|
+
/** Process component module scripts (default: true) */
|
|
148
|
+
processScripts?: boolean;
|
|
145
149
|
}
|
|
146
150
|
```
|
|
147
151
|
|
|
152
|
+
### Processing Component Module Scripts
|
|
153
|
+
|
|
154
|
+
When `processScripts` is enabled (default), the plugin automatically transforms component scripts using `type="module"` to work with the window scope. This is essential when building with Vite and using ES modules in your components.
|
|
155
|
+
|
|
156
|
+
**What It Does:**
|
|
157
|
+
|
|
158
|
+
- Converts ES module imports to window references
|
|
159
|
+
- Wraps scripts in an async IIFE that waits for the library to load
|
|
160
|
+
- Handles multiple components efficiently with a shared loading promise
|
|
161
|
+
|
|
162
|
+
**Example:**
|
|
163
|
+
|
|
164
|
+
Before build (in your component):
|
|
165
|
+
|
|
166
|
+
```html
|
|
167
|
+
<script type="module">
|
|
168
|
+
import { registerComponent } from "ladrillosjs";
|
|
169
|
+
|
|
170
|
+
let count = 0;
|
|
171
|
+
|
|
172
|
+
export const increment = () => {
|
|
173
|
+
count++;
|
|
174
|
+
};
|
|
175
|
+
</script>
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
After build (automatically transformed):
|
|
179
|
+
|
|
180
|
+
```html
|
|
181
|
+
<script>
|
|
182
|
+
(async () => {
|
|
183
|
+
try {
|
|
184
|
+
if (!window.__ladrillosPromise__) {
|
|
185
|
+
window.__ladrillosPromise__ = new Promise((resolve) => {
|
|
186
|
+
// Wait for LadrillosJS to load...
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
await window.__ladrillosPromise__;
|
|
191
|
+
|
|
192
|
+
(async () => {
|
|
193
|
+
const { registerComponent } = window.ladrillosjs;
|
|
194
|
+
|
|
195
|
+
let count = 0;
|
|
196
|
+
|
|
197
|
+
// Component code...
|
|
198
|
+
})();
|
|
199
|
+
} catch (error) {
|
|
200
|
+
console.error("Failed to execute component module:", error);
|
|
201
|
+
}
|
|
202
|
+
})();
|
|
203
|
+
</script>
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
**Disable Processing (if needed):**
|
|
207
|
+
|
|
208
|
+
```javascript
|
|
209
|
+
import { defineConfig } from "vite";
|
|
210
|
+
import { copyComponentsPlugin } from "ladrillosjs/vite";
|
|
211
|
+
|
|
212
|
+
export default defineConfig({
|
|
213
|
+
plugins: [
|
|
214
|
+
copyComponentsPlugin({
|
|
215
|
+
src: "components",
|
|
216
|
+
dest: "components",
|
|
217
|
+
processScripts: false, // Disable script processing
|
|
218
|
+
}),
|
|
219
|
+
],
|
|
220
|
+
});
|
|
221
|
+
```
|
|
222
|
+
|
|
148
223
|
### Complete Example
|
|
149
224
|
|
|
150
225
|
Project structure:
|
|
@@ -709,6 +784,189 @@ Pass data to components using HTML attributes:
|
|
|
709
784
|
<my-greeting name="Jane" age="30"></my-greeting>
|
|
710
785
|
```
|
|
711
786
|
|
|
787
|
+
### Lifecycle Hooks
|
|
788
|
+
|
|
789
|
+
LadrillosJS provides Vue.js-style lifecycle hooks so you can run code at specific times in a component's lifecycle. These hooks are tied directly to Web Component lifecycle methods for maximum control.
|
|
790
|
+
|
|
791
|
+
#### Available Hooks
|
|
792
|
+
|
|
793
|
+
| Hook | Called | Purpose |
|
|
794
|
+
| ------------ | ------------------------------------------------ | ---------------------------------- |
|
|
795
|
+
| `$onMount` | After component is mounted and fully initialized | Setup, initialization, API calls |
|
|
796
|
+
| `$onUpdate` | After component state changes and re-renders | React to state changes |
|
|
797
|
+
| `$onUnmount` | Before component is removed from DOM | Cleanup, unsubscribe, clear timers |
|
|
798
|
+
|
|
799
|
+
#### `$onMount(callback)`
|
|
800
|
+
|
|
801
|
+
Called once when the component is fully mounted and ready. Perfect for initialization, API calls, and setup logic.
|
|
802
|
+
|
|
803
|
+
```html
|
|
804
|
+
<div>
|
|
805
|
+
<h2>User Profile</h2>
|
|
806
|
+
<p $if="{loading}">Loading...</p>
|
|
807
|
+
<div $else>
|
|
808
|
+
<h3>{user.name}</h3>
|
|
809
|
+
<p>{user.email}</p>
|
|
810
|
+
</div>
|
|
811
|
+
</div>
|
|
812
|
+
|
|
813
|
+
<script>
|
|
814
|
+
let user = { name: "", email: "" };
|
|
815
|
+
let loading = true;
|
|
816
|
+
|
|
817
|
+
// Called after component mounts with state ready
|
|
818
|
+
$onMount(() => {
|
|
819
|
+
console.log("✅ Component mounted!");
|
|
820
|
+
|
|
821
|
+
// Perfect for API calls, initialization, etc
|
|
822
|
+
fetch("/api/user/123")
|
|
823
|
+
.then((res) => res.json())
|
|
824
|
+
.then((data) => {
|
|
825
|
+
user = data;
|
|
826
|
+
loading = false;
|
|
827
|
+
});
|
|
828
|
+
});
|
|
829
|
+
</script>
|
|
830
|
+
```
|
|
831
|
+
|
|
832
|
+
**When to use `$onMount`:**
|
|
833
|
+
|
|
834
|
+
- ✅ Fetch data from APIs
|
|
835
|
+
- ✅ Initialize timers or subscriptions
|
|
836
|
+
- ✅ Set up event listeners
|
|
837
|
+
- ✅ Run component setup logic
|
|
838
|
+
- ✅ Validate initial state
|
|
839
|
+
|
|
840
|
+
#### `$onUpdate(callback)`
|
|
841
|
+
|
|
842
|
+
Called after component state changes and the component re-renders. Perfect for reacting to state changes.
|
|
843
|
+
|
|
844
|
+
```html
|
|
845
|
+
<div>
|
|
846
|
+
<p>Count: {count}</p>
|
|
847
|
+
<button onclick="count++">Increment</button>
|
|
848
|
+
</div>
|
|
849
|
+
|
|
850
|
+
<script>
|
|
851
|
+
let count = 0;
|
|
852
|
+
|
|
853
|
+
$onUpdate(() => {
|
|
854
|
+
console.log("🔄 Component updated! New count:", count);
|
|
855
|
+
|
|
856
|
+
// React to state changes
|
|
857
|
+
if (count === 10) {
|
|
858
|
+
console.log("Count reached 10!");
|
|
859
|
+
}
|
|
860
|
+
});
|
|
861
|
+
</script>
|
|
862
|
+
```
|
|
863
|
+
|
|
864
|
+
**When to use `$onUpdate`:**
|
|
865
|
+
|
|
866
|
+
- ✅ Log state changes for debugging
|
|
867
|
+
- ✅ Trigger side effects when specific properties change
|
|
868
|
+
- ✅ Sync with external systems
|
|
869
|
+
- ✅ Perform validations on updated state
|
|
870
|
+
|
|
871
|
+
#### `$onUnmount(callback)`
|
|
872
|
+
|
|
873
|
+
Called before the component is removed from the DOM. Perfect for cleanup operations.
|
|
874
|
+
|
|
875
|
+
```html
|
|
876
|
+
<div>
|
|
877
|
+
<p>Timer: {seconds}</p>
|
|
878
|
+
</div>
|
|
879
|
+
|
|
880
|
+
<script>
|
|
881
|
+
let seconds = 0;
|
|
882
|
+
let interval = null;
|
|
883
|
+
|
|
884
|
+
$onMount(() => {
|
|
885
|
+
// Start timer
|
|
886
|
+
interval = setInterval(() => {
|
|
887
|
+
seconds++;
|
|
888
|
+
}, 1000);
|
|
889
|
+
});
|
|
890
|
+
|
|
891
|
+
$onUnmount(() => {
|
|
892
|
+
console.log("❌ Component unmounting, cleaning up...");
|
|
893
|
+
|
|
894
|
+
// Clear timer to prevent memory leaks
|
|
895
|
+
if (interval) {
|
|
896
|
+
clearInterval(interval);
|
|
897
|
+
}
|
|
898
|
+
});
|
|
899
|
+
</script>
|
|
900
|
+
```
|
|
901
|
+
|
|
902
|
+
**When to use `$onUnmount`:**
|
|
903
|
+
|
|
904
|
+
- ✅ Clear timers and intervals
|
|
905
|
+
- ✅ Remove event listeners
|
|
906
|
+
- ✅ Unsubscribe from observables
|
|
907
|
+
- ✅ Cleanup resources
|
|
908
|
+
- ✅ Cancel pending API requests
|
|
909
|
+
|
|
910
|
+
#### Complete Lifecycle Example
|
|
911
|
+
|
|
912
|
+
```html
|
|
913
|
+
<div>
|
|
914
|
+
<h3>Lifecycle Demo</h3>
|
|
915
|
+
<p>Status: {status}</p>
|
|
916
|
+
<button onclick="status = 'active'">Activate</button>
|
|
917
|
+
<button onclick="status = 'inactive'">Deactivate</button>
|
|
918
|
+
</div>
|
|
919
|
+
|
|
920
|
+
<script>
|
|
921
|
+
let status = "initializing";
|
|
922
|
+
|
|
923
|
+
$onMount(() => {
|
|
924
|
+
console.log("✅ $onMount - Component ready to go!");
|
|
925
|
+
status = "ready";
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
$onUpdate(() => {
|
|
929
|
+
console.log("🔄 $onUpdate - Status changed to:", status);
|
|
930
|
+
});
|
|
931
|
+
|
|
932
|
+
$onUnmount(() => {
|
|
933
|
+
console.log("❌ $onUnmount - Cleaning up before removal");
|
|
934
|
+
});
|
|
935
|
+
</script>
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
#### Lifecycle Timing Diagram
|
|
939
|
+
|
|
940
|
+
```
|
|
941
|
+
┌─────────────────────────────────────────────────────────┐
|
|
942
|
+
│ Element added to DOM │
|
|
943
|
+
│ ↓ │
|
|
944
|
+
│ connectedCallback() starts │
|
|
945
|
+
│ ├─ Parse template │
|
|
946
|
+
│ ├─ Load styles │
|
|
947
|
+
│ ├─ Execute scripts & initialize state │
|
|
948
|
+
│ ├─ Render bindings, conditionals, loops │
|
|
949
|
+
│ │ │
|
|
950
|
+
│ ├─→ $onMount() called ← Component ready! │
|
|
951
|
+
│ │ │
|
|
952
|
+
│ State changes (click, setState, etc) │
|
|
953
|
+
│ ├─ Proxy detects change │
|
|
954
|
+
│ ├─ Schedule update (requestAnimationFrame) │
|
|
955
|
+
│ ├─ Re-render bindings, conditionals, loops │
|
|
956
|
+
│ │ │
|
|
957
|
+
│ ├─→ $onUpdate() called ← After each update │
|
|
958
|
+
│ │ ... (can happen many times) │
|
|
959
|
+
│ │ │
|
|
960
|
+
│ Element removed from DOM │
|
|
961
|
+
│ ├─→ $onUnmount() called ← Before cleanup │
|
|
962
|
+
│ │ │
|
|
963
|
+
│ disconnectedCallback() cleanup │
|
|
964
|
+
│ ├─ Remove event listeners │
|
|
965
|
+
│ ├─ Clear subscriptions │
|
|
966
|
+
│ └─ Complete │
|
|
967
|
+
└─────────────────────────────────────────────────────────┘
|
|
968
|
+
```
|
|
969
|
+
|
|
712
970
|
## Advanced Features
|
|
713
971
|
|
|
714
972
|
### Lazy Loading
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"use strict";var U=Object.defineProperty,X=Object.defineProperties;var Q=Object.getOwnPropertyDescriptors;var k=Object.getOwnPropertySymbols;var V=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable;var j=t=>{throw TypeError(t)};var L=(t,e,r)=>e in t?U(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,h=(t,e)=>{for(var r in e||(e={}))V.call(e,r)&&L(t,r,e[r]);if(k)for(var r of k(e))Y.call(e,r)&&L(t,r,e[r]);return t},w=(t,e)=>X(t,Q(e));var Z=(t,e,r)=>e.has(t)||j("Cannot "+r);var z=(t,e,r)=>e.has(t)?j("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var P=(t,e,r)=>(Z(t,e,"access private method"),r);var p=(t,e,r)=>new Promise((s,o)=>{var i=c=>{try{l(r.next(c))}catch(d){o(d)}},a=c=>{try{l(r.throw(c))}catch(d){o(d)}},l=c=>c.done?s(c.value):Promise.resolve(c.value).then(i,a);l((r=r.apply(t,e)).next())});const T=()=>{try{return!1}catch(t){return process.env.NODE_ENV==="development"}},n={log(t,...e){T()&&console.log(t,...e)},error(t,...e){console.error(t,...e)},warn(t,...e){T()&&console.warn(t,...e)}},f=(t,e)=>{const r=[t];return e&&(e.componentName&&r.push(`
|
|
2
|
+
Component: <${e.componentName}>`),e.componentPath&&r.push(`
|
|
3
|
+
File: ${e.componentPath}`),e.expression&&r.push(`
|
|
4
|
+
Expression: ${e.expression}`),e.attributeName&&r.push(`
|
|
5
|
+
Attribute: ${e.attributeName}`),e.eventType&&r.push(`
|
|
6
|
+
Event: ${e.eventType}`),e.elementTag&&r.push(`
|
|
7
|
+
Element: <${e.elementTag}>`),e.lineHint&&r.push(`
|
|
8
|
+
Location: ${e.lineHint}`)),r.join("")},ee=(t,e,r)=>{const s=f("⚠️ Binding Error: Failed to evaluate expression",w(h({},r),{expression:t,lineHint:(r==null?void 0:r.lineHint)||"Template binding expression"}));n.error(s),n.error(` Error details: ${e.message}`),e.stack&&console.debug(" Stack trace:",e.stack)},te=(t,e,r,s)=>{const o=f("⚠️ Event Handler Error: Failed to execute handler",w(h({},s),{eventType:t,expression:e,lineHint:(s==null?void 0:s.lineHint)||`on${t} handler`}));n.error(o),n.error(` Error details: ${r.message}`),r.stack&&console.debug(" Stack trace:",r.stack)},re=(t,e,r)=>{const s=f("⚠️ Conditional Error: Failed to evaluate condition",w(h({},r),{expression:t,lineHint:(r==null?void 0:r.lineHint)||"$if/$else-if condition"}));n.error(s),n.error(` Error details: ${e.message}`),e.stack&&console.debug(" Stack trace:",e.stack)},se=(t,e,r)=>{const s=f("⚠️ Loop Error: Failed to process loop",w(h({},r),{expression:t,lineHint:(r==null?void 0:r.lineHint)||"$for loop expression"}));n.error(s),n.error(` Error details: ${e.message}`),e.stack&&console.debug(" Stack trace:",e.stack)},F=(t,e,r)=>{const s=f("⚠️ Registration Error: Failed to register component",{componentName:t,componentPath:e});n.error(s),n.error(` Error details: ${r.message}`),r.stack&&console.debug(" Stack trace:",r.stack)},M=(t,e,r)=>{const s=f("⚠️ Fetch Error: Failed to load resource",w(h({},r),{componentPath:t}));n.error(s),n.error(` Error details: ${e.message}`)},b=(t,e)=>{const r=f(`⚠️ Parse Error: ${t}`,e);n.error(r)},oe=(t,e)=>{const r=f("⚠️ Script Error: Failed to execute component script",e);n.error(r),n.error(` Error details: ${t.message}`),t.stack&&console.debug(" Stack trace:",t.stack)},ne=(t,e,r)=>{const s=f("⚠️ Two-Way Binding Error: Failed to setup binding",w(h({},r),{expression:t,lineHint:(r==null?void 0:r.lineHint)||"$model binding"}));n.error(s),n.error(` Error details: ${e.message}`)},ie=(t,e)=>{var r;return h({componentName:(t==null?void 0:t.tagName)||((r=t==null?void 0:t.constructor)==null?void 0:r.name),componentPath:(t==null?void 0:t.sourcePath)||(t==null?void 0:t._sourcePath)},e)},g=new Map,le=25,ae=t=>{const e=g.get(t);return e&&(g.delete(t),g.set(t,e)),e},ce=(t,e)=>{if(g.has(t))g.delete(t);else if(g.size>=le){const r=g.keys().next().value;r&&g.delete(r)}g.set(t,e)},N=t=>p(null,null,function*(){if(!t)throw new Error("Path cannot be null or empty");const e=ae(t);if(e)return e;try{const r=yield fetch(t);if(!r.ok)throw new Error(`Failed to fetch component from ${t}: ${r.statusText}`);const s=yield r.text();return ce(t,s),s}catch(r){M(t,r,{componentPath:t})}}),de=t=>p(null,null,function*(){try{const e=yield fetch(t);if(!e.ok)throw new Error(`HTTP ${e.status}`);return yield e.text()}catch(e){return M(t,e),""}}),$={bindings:/{([^}]+)}/g,comments:{js:/\/\*[\s\S]*?\*\/|\/\/.*$/gm,css:/\/\*[\s\S]*?\*\//g,html:/<!--[\s\S]*?-->/g}},pe=new DOMParser,H=(t,e)=>p(null,null,function*(){const r=ue(t),{scripts:s,externalScripts:o}=ge(r),i=yield he(r),a=r.body.innerHTML.trim();return{tagName:e,template:a,scripts:s,externalScripts:o,styles:i}}),ue=t=>pe.parseFromString(t.replace($.comments.html,""),"text/html"),me=t=>["/@vite/","/__vite","/webpack-dev-server","/hot-update","/__webpack_hmr","/browser-sync/","/livereload.js"].some(r=>t.includes(r)),ge=t=>{var s,o;const e=[],r=[];for(const i of t.querySelectorAll("script")){if(i.src){if(me(i.src)){i.remove();continue}const a=i.hasAttribute("external");r.push({src:i.getAttribute("src")||i.src,type:(s=i.type)!=null?s:null,external:a})}else if(i.textContent){let a=i.textContent.trim();a=a.replace($.comments.js,"").trim(),e.push({content:a,type:(o=i.type)!=null?o:null})}i.remove()}return{scripts:e,externalScripts:r}},fe=t=>{const e=t.match(/const __vite__css = "((?:[^"\\]|\\.)*)"/);if(e&&e[1])return e[1].replace(/\\r\\n/g,`
|
|
9
|
+
`).replace(/\\n/g,`
|
|
10
|
+
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\");const r=t.match(/export\s+default\s+"((?:[^"\\]|\\.)*)"/);return r&&r[1]?r[1].replace(/\\r\\n/g,`
|
|
11
|
+
`).replace(/\\n/g,`
|
|
12
|
+
`).replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"):t.includes("import")||t.includes("export")?(n.warn("CSS file returned JavaScript module format. CSS may not load correctly."),""):t},he=t=>p(null,null,function*(){let e="";const r=t.querySelectorAll("style, link[rel='stylesheet']");for(const s of r){if(s.tagName==="LINK"){const i=yield de(s.href),a=fe(i);a&&(e+=`
|
|
13
|
+
`+a)}else if(s.tagName==="STYLE"){const o=s;if(o.textContent){let i=o.textContent.trim();i=i.replace($.comments.css,"").trim(),e+=`
|
|
14
|
+
`+i}}s.remove()}return e.trim()});var E,x,A;class we{constructor(){z(this,E);this.components={},this.lazyComponents=new Set,this.intersectionObserver=null,this.lazyLoadingInProgress=new Map,this.lazyComponentsLoaded=new Set}registerComponent(e,r,s=!0,o=!1){return p(this,null,function*(){if(this.components[e]){n.warn(`Component with name "${e}" is already registered.`);return}if(o){this.lazyComponents.add(e),P(this,E,x).call(this,e,r,s),n.log(`Component ${e} registered as lazy-loaded`);return}try{const i=yield N(r),a=yield H(i,e);this.components[e]={tagName:e,template:a.template,scripts:a.scripts,externalScripts:a.externalScripts,styles:a.styles,sourcePath:r,lazy:!1},n.log(`Component ${e} registered successfully`),yield P(this,E,A).call(this,e,s)}catch(i){F(e,r,i);return}})}}E=new WeakSet,x=function(e,r,s){const o=this;class i extends HTMLElement{constructor(){super(),this.loaded=!1,this.observer=null,s&&(this.attachShadow({mode:"open"}),this.shadowRoot&&(this.shadowRoot.innerHTML=`
|
|
15
|
+
<style>
|
|
16
|
+
:host { display: block; min-height: 1px; }
|
|
17
|
+
</style>
|
|
18
|
+
`))}connectedCallback(){if(!this.loaded){if(this.hasAttribute("eager")){this.loaded=!0,this.loadComponent();return}this.observer=new IntersectionObserver(l=>{l.forEach(c=>{c.isIntersecting&&!this.loaded&&(this.loaded=!0,this.loadComponent())})},{rootMargin:"100px"}),this.observer.observe(this)}}disconnectedCallback(){this.observer&&(this.observer.disconnect(),this.observer=null)}loadComponent(){return p(this,null,function*(){try{if(o.lazyComponentsLoaded.has(e)){n.log(`Component ${e} already loaded, upgrading placeholder...`),this.upgradePlaceholder();return}if(o.lazyLoadingInProgress.has(e)){n.log(`Component ${e} is already loading, waiting...`),yield o.lazyLoadingInProgress.get(e),this.upgradePlaceholder();return}const l=this.performLoad();o.lazyLoadingInProgress.set(e,l),yield l,o.lazyLoadingInProgress.delete(e),o.lazyComponentsLoaded.add(e),o.lazyComponents.delete(e),n.log(`Component ${e} lazy-loaded successfully`)}catch(l){o.lazyLoadingInProgress.delete(e),F(e,r,l)}})}performLoad(){return p(this,null,function*(){n.log(`Lazy loading component: ${e}`);const l=this.parentNode;if(this.nextSibling,!l){b(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:r});return}const c=yield N(r),d=yield H(c,e);n.log(`Component ${e} parsed successfully`),o.components[e]={tagName:e,template:d.template,scripts:d.scripts,externalScripts:d.externalScripts,styles:d.styles,sourcePath:r,lazy:!0};const m=`${e}-real`;n.log(`Defining real component with temp name: ${m}`);const y=o.components[e].tagName;o.components[e].tagName=m;const{defineWebComponent:C}=yield Promise.resolve().then(()=>require("./webcomponent-BRRZJV0q.js"));C(o.components[e],s),n.log(`Real component ${m} defined`),o.components[e].tagName=y,this.upgradePlaceholder()})}upgradePlaceholder(){const l=this,c=this.parentNode,d=this.nextSibling;if(!c){b(`Placeholder for ${e} has no parent node`,{componentName:e,componentPath:r});return}const m=`${e}-real`,y=document.createElement(m);for(n.log(`Created real component instance: ${m}`),Array.from(l.attributes).forEach(C=>{C.name!=="eager"&&y.setAttribute(C.name,C.value)});l.firstChild;)y.appendChild(l.firstChild);d?(c.insertBefore(y,d),n.log("Inserted real component before next sibling")):(c.appendChild(y),n.log("Appended real component to parent")),c.removeChild(l),n.log("Removed placeholder element")}}customElements.get(e)||customElements.define(e,i)},A=function(e,r){return p(this,null,function*(){const{defineWebComponent:s}=yield Promise.resolve().then(()=>require("./webcomponent-BRRZJV0q.js"));this.components[e]&&s(this.components[e],r)})};const q=new we;class ye{constructor(){this.listeners=new Map}emit(e,r){const s=new CustomEvent(e,{detail:r,bubbles:!0,composed:!0});document.dispatchEvent(s);const o=this.listeners.get(e);if(!o||o.size===0)return Promise.resolve();const i=[];return o.forEach(a=>{try{const l=a(r);l instanceof Promise&&i.push(l)}catch(l){n.error(`⚠️ Event Bus Error: Failed to execute listener for "${e}"`),n.error(` Error details: ${l.message}`),i.push(Promise.reject(l))}}),i.length>0?Promise.all(i).then(()=>{}):Promise.resolve()}listen(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>{this.off(e,r)}}off(e,r){const s=this.listeners.get(e);s&&(s.delete(r),s.size===0&&this.listeners.delete(e))}clear(e){e?this.listeners.delete(e):this.listeners.clear()}listenerCount(e){var r,s;return(s=(r=this.listeners.get(e))==null?void 0:r.size)!=null?s:0}}const _=new ye,u={};function R(t){return p(this,null,function*(){const e=yield u.readdir(t,{withFileTypes:!0});for(const r of e){const s=u.resolve(t,r.name);if(r.isDirectory())yield R(s);else if(r.name.endsWith(".html")){let o=yield u.readFile(s,"utf-8");o=o.replace(/<script type="module">([\s\S]*?)<\/script>/g,(i,a)=>`<script>
|
|
19
|
+
(async () => {
|
|
20
|
+
try {
|
|
21
|
+
// Use a shared promise to avoid multiple components polling independently
|
|
22
|
+
if (!window.__ladrillosPromise__) {
|
|
23
|
+
if (window.ladrillosjs) {
|
|
24
|
+
// Library already loaded, resolve immediately
|
|
25
|
+
window.__ladrillosPromise__ = Promise.resolve(window.ladrillosjs);
|
|
26
|
+
} else {
|
|
27
|
+
// Set up a one-time promise that waits for library to load
|
|
28
|
+
window.__ladrillosPromise__ = new Promise((resolve) => {
|
|
29
|
+
// Quick check first
|
|
30
|
+
if (window.ladrillosjs) {
|
|
31
|
+
resolve(window.ladrillosjs);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Use a short timeout (libraries load almost instantly)
|
|
36
|
+
const timeout = setTimeout(() => {
|
|
37
|
+
if (!window.ladrillosjs) {
|
|
38
|
+
throw new Error('LadrillosJS failed to load');
|
|
39
|
+
}
|
|
40
|
+
clearInterval(interval);
|
|
41
|
+
resolve(window.ladrillosjs);
|
|
42
|
+
}, 100);
|
|
43
|
+
|
|
44
|
+
// Fallback polling as safety net
|
|
45
|
+
const interval = setInterval(() => {
|
|
46
|
+
if (window.ladrillosjs) {
|
|
47
|
+
clearTimeout(timeout);
|
|
48
|
+
clearInterval(interval);
|
|
49
|
+
resolve(window.ladrillosjs);
|
|
50
|
+
}
|
|
51
|
+
}, 5);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Wait for the shared promise
|
|
57
|
+
await window.__ladrillosPromise__;
|
|
58
|
+
|
|
59
|
+
// Execute the component script
|
|
60
|
+
(async () => {
|
|
61
|
+
${a.replace(/import\s+\*\s+as\s+(\w+)\s+from\s+["']ladrillosjs["']/g,"const $1 = window.ladrillosjs;").replace(/import\s+\{\s*([^}]+)\s*\}\s+from\s+["']ladrillosjs["']/g,"const { $1 } = window.ladrillosjs;").replace(/import\s+(\w+)\s+from\s+["']ladrillosjs["']/g,"const $1 = window.ladrillosjs.default;")}
|
|
62
|
+
})();
|
|
63
|
+
} catch (error) {
|
|
64
|
+
console.error('Failed to execute component module:', error);
|
|
65
|
+
}
|
|
66
|
+
})();
|
|
67
|
+
<\/script>`),yield u.writeFile(s,o)}}})}function Ee(t={}){const{src:e="components",dest:r="components",copyOnDev:s=!1,processScripts:o=!0}=t;return{name:"ladrillosjs:copy-components",apply:s?"serve":"build",generateBundle(a,l){return p(this,null,function*(){const c=u.resolve(process.cwd(),e),d=u.resolve(process.cwd(),"dist",r);if(!u.existsSync(c)){console.warn(`[ladrillosjs:copy-components] Source directory not found: ${c}`);return}try{u.existsSync(d)&&u.rmSync(d,{recursive:!0,force:!0}),u.cpSync(c,d,{recursive:!0}),console.log(`[ladrillosjs:copy-components] Copied components from ${c} to ${d}`),o&&(yield R(d),console.log(`[ladrillosjs:copy-components] Processed component scripts in ${d}`))}catch(m){throw console.error("[ladrillosjs:copy-components] Error copying components:",m),m}})}}}const I=(t,e,r,s)=>q.registerComponent(t,e,r,s),B=t=>p(null,null,function*(){yield Promise.all(t.map(({name:e,path:r,useShadowDOM:s,lazy:o})=>q.registerComponent(e,r,s,o)))}),D=(t,e)=>_.listen(t,e),W=(t,e)=>{_.emit(t,e)},Ce=(t,e)=>{if(e){const r=e.tagName.toLowerCase();window.__ladrilloContexts||(window.__ladrilloContexts=new Map),window.__ladrilloContexts.set(r,{shadowRoot:t,element:e})}},v=()=>{const t=window.__ladrilloContexts;if(t&&t.size>0){const e=Array.from(t.values());return e[e.length-1]}return null},O=()=>{const t=v();return t&&t.element?t.element.state||{}:{}},S=t=>{const e=v();e&&e.setState&&e.setState(t)},G=(t,e)=>(S({[t]:e}),r=>{S({[t]:r})}),J=(t,e)=>{if(e)return e.querySelector(t);const r=v();if(r){const s=r.shadowRoot||r.element;if(s){const o=s.querySelector(t);if(o)return o}}return document.querySelector(t)},K=(t,e)=>{if(e)return e.querySelectorAll(t);const r=v();if(r){const s=r.shadowRoot||r.element;if(s){const o=s.querySelectorAll(t);if(o.length>0)return o}}return document.querySelectorAll(t)};typeof window!="undefined"&&(window.ladrillosjs={registerComponent:I,registerComponents:B},window.$listen=D,window.$emit=W,window.$querySelector=J,window.$querySelectorAll=K,window.$reactive=G,window.$setState=S,window.$getState=O);exports.$emit=W;exports.$getState=O;exports.$listen=D;exports.$querySelector=J;exports.$querySelectorAll=K;exports.$reactive=G;exports.$setState=S;exports.REGEX_PATTERNS=$;exports.__setComponentContext=Ce;exports.copyComponentsPlugin=Ee;exports.createErrorContext=ie;exports.eventBus=_;exports.logBindingError=ee;exports.logConditionalError=re;exports.logEventHandlerError=te;exports.logLoopError=se;exports.logParseError=b;exports.logScriptError=oe;exports.logTwoWayBindingError=ne;exports.logger=n;exports.registerComponent=I;exports.registerComponents=B;
|
|
68
|
+
//# sourceMappingURL=index-Bx3jQFpE.js.map
|