@unsetsoft/ryunixjs 1.1.5 → 1.1.6-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Ryunix.js CHANGED
@@ -1 +1,1015 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("lodash")):"function"==typeof define&&define.amd?define(["exports","lodash"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Ryunix={},e.lodash)}(this,(function(e,t){"use strict";const o={containerRoot:void 0,nextUnitOfWork:void 0,currentRoot:void 0,wipRoot:void 0,deletions:void 0,wipFiber:void 0,hookIndex:void 0},r=/[A-Z]/g,n=Object.freeze({TEXT_ELEMENT:Symbol("text.element"),Ryunix_ELEMENT:Symbol("ryunix.element"),RYUNIX_EFFECT:Symbol("ryunix.effect"),RYUNIX_MEMO:Symbol("ryunix.memo"),RYUNIX_URL_QUERY:Symbol("ryunix.urlQuery"),RYUNIX_REF:Symbol("ryunix.ref")}),i=Object.freeze({object:"object",function:"function",style:"ryunix-style",className:"ryunix-class",children:"children",boolean:"boolean"}),s=Object.freeze({style:"style",className:"className"}),a=Object.freeze({PLACEMENT:Symbol(),UPDATE:Symbol(),DELETION:Symbol()}),l=e=>e.children,c=(e,t)=>(t=t||[],null==e||typeof e==i.boolean||(Array.isArray(e)?e.some((e=>{c(e,t)})):t.push(e)),t),p=(e,t,...o)=>{o=c(o,[]);const r=t&&t.key?t.key:`${n.Ryunix_ELEMENT.toString()}-${Math.random().toString(36).substring(2,9)}`;return{type:e,props:{...t,key:r,children:o.map((e=>typeof e===i.object?e:u(e)))}}},u=e=>({type:n.TEXT_ELEMENT,props:{nodeValue:e,children:[]}}),d=(e,t)=>{o.wipRoot={dom:o.containerRoot||t,props:{children:[e]},alternate:o.currentRoot},o.deletions=[],o.nextUnitOfWork=o.wipRoot},f=e=>{const t=o.wipFiber.alternate&&o.wipFiber.alternate.hooks&&o.wipFiber.alternate.hooks[o.hookIndex],r={state:t?t.state:e,queue:t?[...t.queue]:[]};r.queue.forEach((e=>{r.state=typeof e===i.function?e(r.state):e})),r.queue=[];return o.wipFiber&&o.wipFiber.hooks&&(o.wipFiber.hooks.push(r),o.hookIndex++),[r.state,e=>{r.queue.push(e),o.wipRoot={dom:o.currentRoot.dom,props:o.currentRoot.props,alternate:o.currentRoot},o.nextUnitOfWork=o.wipRoot,o.deletions=[]}]},m=(e,r)=>{const i=o.wipFiber.alternate&&o.wipFiber.alternate.hooks&&o.wipFiber.alternate.hooks[o.hookIndex],s={type:n.RYUNIX_EFFECT,deps:r};i&&t.isEqual(i.deps,s.deps)||e(),o.wipFiber.hooks&&(o.wipFiber.hooks.push(s),o.hookIndex++)},h=(e,r)=>{const i=o.wipFiber.alternate&&o.wipFiber.alternate.hooks&&o.wipFiber.alternate.hooks[o.hookIndex],s={type:n.RYUNIX_MEMO,value:null,deps:r};return i&&t.isEqual(i.deps,s.deps)?s.value=i.value:s.value=e(),o.wipFiber.hooks&&(o.wipFiber.hooks.push(s),o.hookIndex++),s.value},y=()=>{const e=new URLSearchParams(window.location.search),t={};for(let[o,r]of e.entries())t[o]=r;return t},b=e=>e.startsWith("on"),E=e=>e!==i.children&&!b(e),w=(e,t)=>o=>e[o]!==t[o],k=e=>t=>!(t in e),R=e=>{e.hooks&&e.hooks.filter((e=>e.tag===n.RYUNIX_EFFECT&&e.cancel)).forEach((e=>{e.cancel()}))},x=e=>{e.hooks&&e.hooks.filter((e=>e.tag===n.RYUNIX_EFFECT&&e.effect)).forEach((e=>{e.cancel=e.effect()}))},F=e=>{const t=e.type==n.TEXT_ELEMENT?document.createTextNode(""):document.createElement(e.type);return _(t,{},e.props),t},_=(e,t,o)=>{Object.keys(t).filter(b).filter((e=>k(o)(e)||w(t,o)(e))).forEach((o=>{const r=o.toLowerCase().substring(2);e.removeEventListener(r,t[o])})),Object.keys(t).filter(E).filter(k(o)).forEach((t=>{e[t]=""})),Object.keys(o).filter(E).filter(w(t,o)).forEach((r=>{if(r===i.style)v(e,o["ryunix-style"]);else if(r===s.style)v(e,o.style);else if(r===i.className){if(""===o["ryunix-class"])throw new Error("data-class cannot be empty.");t["ryunix-class"]&&e.classList.remove(...t["ryunix-class"].split(/\s+/)),e.classList.add(...o["ryunix-class"].split(/\s+/))}else if(r===s.className){if(""===o.className)throw new Error("className cannot be empty.");t.className&&e.classList.remove(...t.className.split(/\s+/)),e.classList.add(...o.className.split(/\s+/))}else e[r]=o[r]})),Object.keys(o).filter(b).filter(w(t,o)).forEach((t=>{const r=t.toLowerCase().substring(2);e.addEventListener(r,o[t])}))},v=(e,t)=>{e.style=Object.keys(t).reduce(((e,o)=>e+=`${o.replace(r,(function(e){return"-"+e.toLowerCase()}))}: ${t[o]};`),"")};var N=Object.freeze({__proto__:null,DomStyle:v,createDom:F,updateDom:_});const T=()=>{o.deletions.forEach(g),o.wipRoot&&o.wipRoot.child&&(g(o.wipRoot.child),o.currentRoot=o.wipRoot),o.wipRoot=void 0},g=e=>{if(!e)return;let t=e.parent;for(;!t.dom;)t=t.parent;const o=t.dom;if(e.effectTag===a.PLACEMENT&&(null!=e.dom&&o.appendChild(e.dom),x(e)),e.effectTag===a.UPDATE&&(R(e),null!=e.dom&&_(e.dom,e.alternate.props,e.props),x(e)),e.effectTag===a.DELETION)return O(e,o),void R(e);g(e.child),g(e.sibling)},O=(e,t)=>{e.dom?t.removeChild(e.dom):O(e.child,t)};var L=Object.freeze({__proto__:null,commitDeletion:O,commitRoot:T,commitWork:g});const I=(e,t)=>{let r=0,n=e.alternate&&e.alternate.child,i=null;const s=new Map;for(;n;){const e=n.props.key||n.type;s.set(e,n),n=n.sibling}for(;r<t.length;){const n=t[r],l=n.props.key||n.type,c=s.get(l);let p;c&&n&&n.type===c.type?(p={type:c.type,props:n.props,dom:c.dom,parent:e,alternate:c,effectTag:a.UPDATE},s.delete(l)):n&&(p={type:n.type,props:n.props,dom:void 0,parent:e,alternate:void 0,effectTag:a.PLACEMENT}),s.forEach((e=>{e.effectTag=a.DELETION,o.deletions.push(e)})),0===r?e.child=p:i&&(i.sibling=p),i=p,r++}};var U=Object.freeze({__proto__:null,reconcileChildren:I});const C=e=>{o.wipFiber=e,o.hookIndex=0,o.wipFiber.hooks=[];const t=e.type(e.props);let r=[];r=Array.isArray(t)?[...t]:[t],I(e,r)},j=e=>{e.dom||(e.dom=F(e)),I(e,e.props.children)};var M=Object.freeze({__proto__:null,updateFunctionComponent:C,updateHostComponent:j});const S=e=>{let t=!1;for(;o.nextUnitOfWork&&!t;)o.nextUnitOfWork=D(o.nextUnitOfWork),t=e.timeRemaining()<1;!o.nextUnitOfWork&&o.wipRoot&&T(),requestIdleCallback(S)};requestIdleCallback(S);const D=e=>{if(e.type instanceof Function?C(e):j(e),e.child)return e.child;let t=e;for(;t;){if(t.sibling)return t.sibling;t=t.parent}};var X={createElement:p,render:d,init:(e,t="__ryunix")=>{o.containerRoot=document.getElementById(t),d(e,o.containerRoot)},Fragment:l,Dom:N,Workers:Object.freeze({__proto__:null,performUnitOfWork:D,workLoop:S}),Reconciler:U,Components:M,Commits:L};window.Ryunix=X,e.Fragment=l,e.default=X,e.useCallback=(e,t)=>h((()=>e),t),e.useEffect=m,e.useMemo=h,e.useQuery=y,e.useRef=e=>{const t=o.wipFiber.alternate&&o.wipFiber.alternate.hooks&&o.wipFiber.alternate.hooks[o.hookIndex],r={type:n.RYUNIX_REF,value:t?t.value:{current:e}};return o.wipFiber.hooks&&(o.wipFiber.hooks.push(r),o.hookIndex++),r.value},e.useRouter=e=>{const[t,o]=f(window.location.pathname),r=e=>{window.history.pushState({},"",e),n(e)},n=e=>{o(e.split("?")[0])};m((()=>{const e=()=>n(window.location.pathname);return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)}),[]);const i=((e,t)=>{const o=t.split("?")[0];for(const{path:t,component:r}of e){if(!t)continue;const e=[],n=new RegExp(`^${t.replace(/:\w+/g,(t=>(e.push(t.substring(1)),"([^/]+)")))}$`),i=o.match(n);if(i){return{route:{component:r},params:e.reduce(((e,t,o)=>(e[t]=i[o+1],e)),{})}}}const r=e.find((e=>e.NotFound));return r?{route:{component:r.NotFound},params:{}}:{route:{component:null},params:{}}})(e,t);return{Children:()=>{const e=y();return i.route.component?i.route.component({params:i.params,query:e}):null},NavLink:({to:e,...t})=>p("a",{href:e,onClick:t=>{t.preventDefault(),r(e)},...t},t.children),navigate:r}},e.useStore=f,Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Ryunix = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ let vars = {
8
+ containerRoot: {},
9
+ nextUnitOfWork: {},
10
+ currentRoot: {},
11
+ wipRoot: {},
12
+ deletions: [],
13
+ wipFiber: {},
14
+ hookIndex: 0,
15
+ };
16
+
17
+ const reg = /[A-Z]/g;
18
+
19
+ const RYUNIX_TYPES = Object.freeze({
20
+ TEXT_ELEMENT: Symbol('text.element'),
21
+ Ryunix_ELEMENT: Symbol('ryunix.element'),
22
+ RYUNIX_EFFECT: Symbol('ryunix.effect'),
23
+ RYUNIX_MEMO: Symbol('ryunix.memo'),
24
+ RYUNIX_URL_QUERY: Symbol('ryunix.urlQuery'),
25
+ RYUNIX_REF: Symbol('ryunix.ref'),
26
+ RYUNIX_STORE: Symbol('ryunix.store'),
27
+ RYUNIX_REDUCE: Symbol('ryunix.reduce'),
28
+ });
29
+
30
+ const STRINGS = Object.freeze({
31
+ object: 'object',
32
+ function: 'function',
33
+ style: 'ryunix-style',
34
+ className: 'ryunix-class',
35
+ children: 'children',
36
+ boolean: 'boolean',
37
+ string: 'string',
38
+ });
39
+
40
+ const OLD_STRINGS = Object.freeze({
41
+ style: 'style',
42
+ className: 'className',
43
+ });
44
+
45
+ const EFFECT_TAGS = Object.freeze({
46
+ PLACEMENT: Symbol('ryunix.reconciler.status.placement').toString(),
47
+ UPDATE: Symbol('ryunix.reconciler.status.update').toString(),
48
+ DELETION: Symbol('ryunix.reconciler.status.deletion').toString(),
49
+ });
50
+
51
+ const generateHash = (prefix) => {
52
+ return `${prefix}-${Math.random().toString(36).substring(2, 9)}`
53
+ };
54
+
55
+ const Fragment = (props) => {
56
+ return props.children
57
+ };
58
+
59
+ const childArray = (children, out) => {
60
+ out = out || [];
61
+ if (children == undefined || typeof children == STRINGS.boolean) ; else if (Array.isArray(children)) {
62
+ children.some((child) => {
63
+ childArray(child, out);
64
+ });
65
+ } else {
66
+ out.push(children);
67
+ }
68
+ return out
69
+ };
70
+
71
+ /**
72
+ * The function creates a new element with the given type, props, and children.
73
+ * @param type - The type of the element to be created, such as "div", "span", "h1", etc.
74
+ * @param props - The `props` parameter is an object that contains the properties or attributes of the
75
+ * element being created. These properties can include things like `className`, `id`, `style`, and any
76
+ * other custom attributes that the user wants to add to the element. The `props` object is spread
77
+ * using the spread
78
+ * @param children - The `children` parameter is a rest parameter that allows the function to accept
79
+ * any number of arguments after the `props` parameter. These arguments will be treated as children
80
+ * elements of the created element. The `map` function is used to iterate over each child and create a
81
+ * new element if it is not
82
+ * @returns A JavaScript object with a `type` property and a `props` property. The `type` property is
83
+ * set to the `type` argument passed into the function, and the `props` property is an object that
84
+ * includes any additional properties passed in the `props` argument, as well as a `children` property
85
+ * that is an array of any child elements passed in the `...children` argument
86
+ */
87
+
88
+ const createElement = (type, props, ...children) => {
89
+ // Validación: Asegurar que type y props sean válidos
90
+ if (typeof type !== 'string' && typeof type !== 'function') {
91
+ throw new Error("El parámetro 'type' debe ser una cadena o una función.")
92
+ }
93
+ if (props && typeof props !== 'object') {
94
+ throw new Error("El parámetro 'props' debe ser un objeto.")
95
+ }
96
+
97
+ children = childArray(children, []);
98
+ const key =
99
+ props && props.key
100
+ ? generateHash(props.key)
101
+ : generateHash(RYUNIX_TYPES.Ryunix_ELEMENT.toString());
102
+
103
+ return {
104
+ type,
105
+ props: {
106
+ ...props,
107
+ key,
108
+ children: children.map((child) =>
109
+ typeof child === STRINGS.object ? child : createTextElement(child),
110
+ ),
111
+ },
112
+ }
113
+ };
114
+
115
+ /**
116
+ * The function creates a text element with a given text value.
117
+ * @param text - The text content that will be used to create a new text element.
118
+ * @returns A JavaScript object with a `type` property set to `"TEXT_ELEMENT"` and a `props` property
119
+ * that contains a `nodeValue` property set to the `text` parameter and an empty `children` array.
120
+ */
121
+
122
+ const createTextElement = (text) => {
123
+ return {
124
+ type: RYUNIX_TYPES.TEXT_ELEMENT,
125
+ props: {
126
+ nodeValue: text,
127
+ children: [],
128
+ },
129
+ }
130
+ };
131
+
132
+ const isEvent = (key) => key.startsWith('on');
133
+ const isProperty = (key) => key !== STRINGS.children && !isEvent(key);
134
+ const isNew = (prev, next) => (key) => prev[key] !== next[key];
135
+ const isGone = (next) => (key) => !(key in next);
136
+
137
+ /**
138
+ * The function cancels all effect hooks in a given fiber.
139
+ * @param fiber - The "fiber" parameter is likely referring to a data structure used in React.js to
140
+ * represent a component and its state. It contains information about the component's props, state, and
141
+ * children, as well as metadata used by React to manage updates and rendering. The function
142
+ * "cancelEffects" is likely intended
143
+ */
144
+ const cancelEffects = (fiber) => {
145
+ if (fiber.hooks) {
146
+ fiber.hooks
147
+ .filter((hook) => hook.tag === RYUNIX_TYPES.RYUNIX_EFFECT && hook.cancel)
148
+ .forEach((effectHook) => {
149
+ effectHook.cancel();
150
+ });
151
+ }
152
+ };
153
+
154
+ /**
155
+ * The function runs all effect hooks in a given fiber.
156
+ * @param fiber - The "fiber" parameter is likely referring to a data structure used in the
157
+ * implementation of a fiber-based reconciliation algorithm, such as the one used in React. A fiber
158
+ * represents a unit of work that needs to be performed by the reconciliation algorithm, and it
159
+ * contains information about a component and its children, as
160
+ */
161
+ const runEffects = (fiber) => {
162
+ if (fiber.hooks) {
163
+ fiber.hooks
164
+ .filter((hook) => hook.tag === RYUNIX_TYPES.RYUNIX_EFFECT && hook.effect)
165
+ .forEach((effectHook) => {
166
+ effectHook.cancel = effectHook.effect();
167
+ });
168
+ }
169
+ };
170
+
171
+ /**
172
+ * The function creates a new DOM element based on the given fiber object and updates its properties.
173
+ * @param fiber - The fiber parameter is an object that represents a node in the fiber tree. It
174
+ * contains information about the element type, props, and children of the node.
175
+ * @returns The `createDom` function returns a newly created DOM element based on the `fiber` object
176
+ * passed as an argument. If the `fiber` object represents a text element, a text node is created using
177
+ * `document.createTextNode("")`. Otherwise, a new element is created using
178
+ * `document.createElement(fiber.type)`. The function then calls the `updateDom` function to update the
179
+ * properties of the newly created
180
+ */
181
+ const createDom = (fiber) => {
182
+ const dom =
183
+ fiber.type == RYUNIX_TYPES.TEXT_ELEMENT
184
+ ? document.createTextNode('')
185
+ : document.createElement(fiber.type);
186
+
187
+ updateDom(dom, {}, fiber.props);
188
+
189
+ return dom
190
+ };
191
+
192
+ /**
193
+ * The function updates the DOM by removing old event listeners and properties, and adding new ones
194
+ * based on the previous and next props.
195
+ * @param dom - The DOM element that needs to be updated with new props.
196
+ * @param prevProps - An object representing the previous props (properties) of a DOM element.
197
+ * @param nextProps - An object containing the new props that need to be updated in the DOM.
198
+ */
199
+ const updateDom = (dom, prevProps, nextProps) => {
200
+ if (!nextProps) nextProps = {}; // Validar que nextProps no sea null o undefined
201
+
202
+ // Optimización: Combinar filtros para mejorar el rendimiento
203
+ Object.keys(prevProps)
204
+ .filter(
205
+ (key) =>
206
+ isEvent(key) &&
207
+ (isGone(nextProps)(key) || isNew(prevProps, nextProps)(key)),
208
+ )
209
+ .forEach((name) => {
210
+ const eventType = name.toLowerCase().substring(2);
211
+ dom.removeEventListener(eventType, prevProps[name]);
212
+ });
213
+
214
+ Object.keys(prevProps)
215
+ .filter(isProperty)
216
+ .filter(isGone(nextProps))
217
+ .forEach((name) => {
218
+ dom[name] = '';
219
+ });
220
+
221
+ Object.keys(nextProps)
222
+ .filter(isProperty)
223
+ .filter(isNew(prevProps, nextProps))
224
+ .forEach((name) => {
225
+ if (name === STRINGS.style) {
226
+ DomStyle(dom, nextProps['ryunix-style']);
227
+ } else if (name === OLD_STRINGS.style) {
228
+ DomStyle(dom, nextProps.style);
229
+ } else if (name === STRINGS.className) {
230
+ if (nextProps['ryunix-class'] === '') {
231
+ throw new Error('data-class cannot be empty.')
232
+ }
233
+
234
+ prevProps['ryunix-class'] &&
235
+ dom.classList.remove(...prevProps['ryunix-class'].split(/\s+/));
236
+ dom.classList.add(...nextProps['ryunix-class'].split(/\s+/));
237
+ } else if (name === OLD_STRINGS.className) {
238
+ if (nextProps.className === '') {
239
+ throw new Error('className cannot be empty.')
240
+ }
241
+
242
+ prevProps.className &&
243
+ dom.classList.remove(...prevProps.className.split(/\s+/));
244
+ dom.classList.add(...nextProps.className.split(/\s+/));
245
+ } else {
246
+ dom[name] = nextProps[name];
247
+ }
248
+ });
249
+
250
+ Object.keys(nextProps)
251
+ .filter(isEvent)
252
+ .filter(isNew(prevProps, nextProps))
253
+ .forEach((name) => {
254
+ const eventType = name.toLowerCase().substring(2);
255
+ dom.addEventListener(eventType, nextProps[name]);
256
+ });
257
+ };
258
+
259
+ const DomStyle = (dom, style) => {
260
+ dom.style = Object.keys(style).reduce((acc, styleName) => {
261
+ const key = styleName.replace(reg, function (v) {
262
+ return '-' + v.toLowerCase()
263
+ });
264
+ acc += `${key}: ${style[styleName]};`;
265
+ return acc
266
+ }, '');
267
+ };
268
+
269
+ // Implementación inicial de Portals
270
+ const createPortal = (children, container) => {
271
+ container.innerHTML = '';
272
+ children.forEach((child) => {
273
+ const domNode = createDom(child);
274
+ container.appendChild(domNode);
275
+ });
276
+ return container
277
+ };
278
+
279
+ var Dom = /*#__PURE__*/Object.freeze({
280
+ __proto__: null,
281
+ DomStyle: DomStyle,
282
+ createDom: createDom,
283
+ createPortal: createPortal,
284
+ updateDom: updateDom
285
+ });
286
+
287
+ /**
288
+ * The function commits changes made to the virtual DOM to the actual DOM.
289
+ */
290
+ const commitRoot = () => {
291
+ vars.deletions.forEach(commitWork);
292
+ if (vars.wipRoot && vars.wipRoot.child) {
293
+ commitWork(vars.wipRoot.child);
294
+ vars.currentRoot = vars.wipRoot;
295
+ }
296
+ vars.wipRoot = undefined;
297
+ };
298
+
299
+ /**
300
+ * The function commits changes made to the DOM based on the effect tag of the fiber.
301
+ * @param fiber - A fiber is a unit of work in Ryunix's reconciliation process. It represents a
302
+ * component and its state at a particular point in time. The `commitWork` function takes a fiber as a
303
+ * parameter to commit the changes made during the reconciliation process to the actual DOM.
304
+ * @returns The function does not return anything, it performs side effects by manipulating the DOM.
305
+ */
306
+ const commitWork = (fiber) => {
307
+ if (!fiber) return
308
+
309
+ let domParentFiber = fiber.parent;
310
+ while (!domParentFiber.dom) {
311
+ domParentFiber = domParentFiber.parent;
312
+ }
313
+ const domParent = domParentFiber.dom;
314
+
315
+ // Optimización: Validar que fiber.dom sea válido antes de manipularlo
316
+ if (fiber.dom && fiber.effectTag === EFFECT_TAGS.PLACEMENT) {
317
+ domParent.appendChild(fiber.dom);
318
+ runEffects(fiber);
319
+ } else if (fiber.dom && fiber.effectTag === EFFECT_TAGS.UPDATE) {
320
+ cancelEffects(fiber);
321
+ updateDom(fiber.dom, fiber.alternate.props, fiber.props);
322
+ runEffects(fiber);
323
+ } else if (fiber.effectTag === EFFECT_TAGS.DELETION) {
324
+ commitDeletion(fiber, domParent);
325
+ cancelEffects(fiber);
326
+ return
327
+ }
328
+
329
+ // Recorre los "fibers" hijos y hermanos
330
+ commitWork(fiber.child);
331
+ commitWork(fiber.sibling);
332
+ };
333
+
334
+ /**
335
+ * The function removes a fiber's corresponding DOM node from its parent node or recursively removes
336
+ * its child's DOM node until it finds a node to remove.
337
+ * @param fiber - a fiber node in a fiber tree, which represents a component or an element in the Ryunix
338
+ * application.
339
+ * @param domParent - The parent DOM element from which the fiber's DOM element needs to be removed.
340
+ */
341
+ const commitDeletion = (fiber, domParent) => {
342
+ if (fiber.dom) {
343
+ domParent.removeChild(fiber.dom);
344
+ } else {
345
+ commitDeletion(fiber.child, domParent);
346
+ }
347
+ };
348
+
349
+ var Commits = /*#__PURE__*/Object.freeze({
350
+ __proto__: null,
351
+ commitDeletion: commitDeletion,
352
+ commitRoot: commitRoot,
353
+ commitWork: commitWork
354
+ });
355
+
356
+ /**
357
+ * This function reconciles the children of a fiber node with a new set of elements, creating new
358
+ * fibers for new elements, updating existing fibers for elements with the same type, and marking old
359
+ * fibers for deletion if they are not present in the new set of elements.
360
+ * @param wipFiber - A work-in-progress fiber object representing a component or element in the virtual
361
+ * DOM tree.
362
+ * @param elements - an array of elements representing the new children to be rendered in the current
363
+ * fiber's subtree
364
+ */
365
+ const reconcileChildren = (wipFiber, elements) => {
366
+ // Manejo de errores: Validar que elements sea un array
367
+ if (!Array.isArray(elements)) {
368
+ throw new Error("El parámetro 'elements' debe ser un array.")
369
+ }
370
+
371
+ let index = 0;
372
+ let oldFiber = wipFiber.alternate && wipFiber.alternate.child;
373
+ let prevSibling = null;
374
+
375
+ const oldFibersMap = new Map();
376
+ while (oldFiber) {
377
+ const oldKey = oldFiber.props.key || oldFiber.type;
378
+ oldFibersMap.set(oldKey, oldFiber);
379
+ oldFiber = oldFiber.sibling;
380
+ }
381
+
382
+ // Refactorización: Reducir redundancia en la creación de newFiber
383
+ const createFiber = (type, props, dom, parent, alternate, effectTag) => ({
384
+ type,
385
+ props,
386
+ dom,
387
+ parent,
388
+ alternate,
389
+ effectTag,
390
+ });
391
+
392
+ while (index < elements.length) {
393
+ const element = elements[index];
394
+ const key = element.props?.key || element.type;
395
+ const oldFiber = oldFibersMap.get(key);
396
+
397
+ let newFiber;
398
+ const sameType = oldFiber && element && element.type === oldFiber.type;
399
+
400
+ if (sameType) {
401
+ newFiber = createFiber(
402
+ oldFiber.type,
403
+ element.props,
404
+ oldFiber.dom,
405
+ wipFiber,
406
+ oldFiber,
407
+ EFFECT_TAGS.UPDATE,
408
+ );
409
+ oldFibersMap.delete(key);
410
+ } else if (element) {
411
+ newFiber = createFiber(
412
+ element.type,
413
+ element.props,
414
+ undefined,
415
+ wipFiber,
416
+ undefined,
417
+ EFFECT_TAGS.PLACEMENT,
418
+ );
419
+ }
420
+
421
+ if (index === 0) {
422
+ wipFiber.child = newFiber;
423
+ } else if (prevSibling) {
424
+ prevSibling.sibling = newFiber;
425
+ }
426
+
427
+ prevSibling = newFiber;
428
+ index++;
429
+ }
430
+
431
+ // Validación adicional: Verificar que cada elemento tenga las propiedades necesarias
432
+ if (!elements.every((el) => el && el.type && el.props)) {
433
+ throw new Error(
434
+ `Cada elemento en 'elements' debe tener 'type' y 'props': ${JSON.stringify(elements)}`,
435
+ )
436
+ }
437
+
438
+ // Optimización: Eliminar claves no utilizadas después de la reconciliación
439
+ oldFibersMap.forEach((oldFiber) => {
440
+ oldFiber.effectTag = EFFECT_TAGS.DELETION;
441
+ vars.deletions.push(oldFiber);
442
+ });
443
+
444
+ // Optimización: Reducir uso de memoria en oldFibersMap
445
+ oldFibersMap.clear(); // Limpiar el mapa después de la reconciliación
446
+ };
447
+
448
+ // Ajustar Suspense para manejar correctamente los componentes Lazy
449
+ const Suspense = ({ fallback, children }) => {
450
+ try {
451
+ const resolvedChildren = children.map((child) => {
452
+ if (typeof child === 'function') {
453
+ return child()
454
+ }
455
+ return child
456
+ });
457
+ return resolvedChildren // Renderizar los hijos resueltos
458
+ } catch (promise) {
459
+ return fallback // Mostrar el fallback mientras se carga
460
+ }
461
+ };
462
+
463
+ const Lazy = (importFunc) => {
464
+ let Component = null;
465
+ let promise = importFunc().then((module) => {
466
+ Component = module.default || module;
467
+ });
468
+
469
+ return (props) => {
470
+ if (!Component) {
471
+ throw promise
472
+ }
473
+ return createElement(Component, props) // Asegurar que renderiza correctamente el componente cargado
474
+ }
475
+ };
476
+
477
+ var Reconciler = /*#__PURE__*/Object.freeze({
478
+ __proto__: null,
479
+ Lazy: Lazy,
480
+ Suspense: Suspense,
481
+ reconcileChildren: reconcileChildren
482
+ });
483
+
484
+ /**
485
+ * This function updates a function component by setting up a work-in-progress fiber, resetting the
486
+ * hook index, creating an empty hooks array, rendering the component, and reconciling its children.
487
+ * @param fiber - The fiber parameter is an object that represents a node in the fiber tree. It
488
+ * contains information about the component, its props, state, and children. In this function, it is
489
+ * used to update the state of the component and its children.
490
+ */
491
+ const updateFunctionComponent = (fiber) => {
492
+ vars.wipFiber = fiber;
493
+ vars.hookIndex = 0;
494
+ vars.wipFiber.hooks = [];
495
+
496
+ // Validación: Asegurar que fiber.type sea una función válida
497
+ if (typeof fiber.type !== 'function') {
498
+ throw new Error('El tipo de componente debe ser una función válida.')
499
+ }
500
+
501
+ const children = fiber.type(fiber.props);
502
+ let childArr = Array.isArray(children) ? children : [children];
503
+
504
+ reconcileChildren(fiber, childArr);
505
+ };
506
+
507
+ /**
508
+ * This function updates a host component's DOM element and reconciles its children.
509
+ * @param fiber - A fiber is a unit of work in Ryunix that represents a component and its state. It
510
+ * contains information about the component's type, props, and children, as well as pointers to other
511
+ * fibers in the tree.
512
+ */
513
+ const updateHostComponent = (fiber) => {
514
+ if (!fiber.dom) {
515
+ fiber.dom = createDom(fiber);
516
+ }
517
+
518
+ console.log(
519
+ '[updateHostComponent] fiber props children',
520
+ fiber.props?.children || 'undefined',
521
+ );
522
+
523
+ if (fiber.props?.children) {
524
+ reconcileChildren(fiber, fiber.props.children);
525
+ } else {
526
+ console.warn('[updateHostComponent] No children to reconcile');
527
+ }
528
+ };
529
+
530
+ var Components = /*#__PURE__*/Object.freeze({
531
+ __proto__: null,
532
+ updateFunctionComponent: updateFunctionComponent,
533
+ updateHostComponent: updateHostComponent
534
+ });
535
+
536
+ /**
537
+ * This function uses requestIdleCallback to perform work on a fiber tree until it is complete or the
538
+ * browser needs to yield to other tasks.
539
+ * @param deadline - The `deadline` parameter is an object that represents the amount of time the
540
+ * browser has to perform work before it needs to handle other tasks. It has a `timeRemaining()` method
541
+ * that returns the amount of time remaining before the deadline is reached. The `shouldYield` variable
542
+ * is used to determine
543
+ */
544
+ const workLoop = (deadline) => {
545
+ let shouldYield = false;
546
+ while (vars.nextUnitOfWork && !shouldYield) {
547
+ vars.nextUnitOfWork = performUnitOfWork(vars.nextUnitOfWork);
548
+ shouldYield = deadline.timeRemaining() < 1;
549
+ }
550
+
551
+ if (!vars.nextUnitOfWork && vars.wipRoot) {
552
+ commitRoot();
553
+ }
554
+
555
+ const fallbackDeadline = { timeRemaining: () => Infinity };
556
+
557
+ /**
558
+ * Si requestIdleCallback no está disponible, se utiliza un fallback con tiempo infinito para continuar el bucle de trabajo.
559
+ */
560
+ if (typeof requestIdleCallback === 'function') {
561
+ requestIdleCallback(workLoop);
562
+ } else {
563
+ workLoop(fallbackDeadline);
564
+ }
565
+ };
566
+
567
+ requestIdleCallback(workLoop);
568
+
569
+ /**
570
+ * The function performs a unit of work by updating either a function component or a host component and
571
+ * returns the next fiber to be processed.
572
+ * @param fiber - A fiber is a unit of work in Ryunix that represents a component and its state. It
573
+ * contains information about the component's type, props, and children, as well as pointers to its
574
+ * parent, child, and sibling fibers. The `performUnitOfWork` function takes a fiber as a parameter and
575
+ * performs work
576
+ * @returns The function `performUnitOfWork` returns the next fiber to be processed. If the current
577
+ * fiber has a child, it returns the child. Otherwise, it looks for the next sibling of the current
578
+ * fiber. If there are no more siblings, it goes up the tree to the parent and looks for the next
579
+ * sibling of the parent. The function returns `undefined` if there are no more fibers to process.
580
+ */
581
+ const performUnitOfWork = (fiber) => {
582
+ const isFunctionComponent = fiber.type instanceof Function;
583
+ if (isFunctionComponent) {
584
+ updateFunctionComponent(fiber);
585
+ } else {
586
+ updateHostComponent(fiber);
587
+ }
588
+ if (fiber.child) {
589
+ return fiber.child
590
+ }
591
+ let nextFiber = fiber;
592
+ while (nextFiber) {
593
+ if (nextFiber.sibling) {
594
+ return nextFiber.sibling
595
+ }
596
+ nextFiber = nextFiber.parent;
597
+ }
598
+ return undefined
599
+ };
600
+
601
+ var Workers = /*#__PURE__*/Object.freeze({
602
+ __proto__: null,
603
+ performUnitOfWork: performUnitOfWork,
604
+ workLoop: workLoop
605
+ });
606
+
607
+ /**
608
+ * Renders an element into a container using a work-in-progress (WIP) root.
609
+ * @function render
610
+ * @param {Object|HTMLElement} element - The element to be rendered in the container. It can be a Ryunix component (custom element) or a standard DOM element.
611
+ * @param {HTMLElement} container - The container where the element will be rendered. This parameter is optional if `createRoot()` is used beforehand to set up the container.
612
+ * @description The function assigns the `container` to a work-in-progress root and sets up properties for reconciliation, including children and the reference to the current root.
613
+ * It also clears any scheduled deletions and establishes the next unit of work for incremental rendering.
614
+ */
615
+ const render = (element, container) => {
616
+ vars.wipRoot = {
617
+ dom: container,
618
+ props: {
619
+ children: [element],
620
+ },
621
+ alternate: vars.currentRoot,
622
+ };
623
+
624
+ vars.deletions = [];
625
+ vars.nextUnitOfWork = vars.wipRoot;
626
+
627
+ const fallbackDeadline = { timeRemaining: () => Infinity };
628
+
629
+ if (typeof requestIdleCallback === 'function') {
630
+ requestIdleCallback(workLoop);
631
+ } else {
632
+ // Si requestIdleCallback no está disponible, se utiliza un fallback con tiempo infinito.
633
+ workLoop(fallbackDeadline);
634
+ }
635
+
636
+ return vars.wipRoot
637
+ };
638
+
639
+ /**
640
+ * Initializes the application by creating a reference to a DOM element with the specified ID and rendering the main component.
641
+ * @function init
642
+ * @param {Object} MainElement - The main component to render, typically the root component of the application.
643
+ * @param {string} [root='__ryunix'] - The ID of the HTML element that serves as the container for the root element. Defaults to `'__ryunix'` if not provided.
644
+ * @example
645
+ * Ryunix.init(App, "__ryunix"); // Initializes and renders the App component into the <div id="__ryunix"></div> element.
646
+ * @description This function retrieves the container element by its ID and invokes the `render` function to render the main component into it.
647
+ */
648
+ const init = (MainElement, root = '__ryunix') => {
649
+ vars.containerRoot = document.getElementById(root);
650
+
651
+ render(MainElement, vars.containerRoot);
652
+ };
653
+
654
+ /**
655
+ * @description The function creates a state.
656
+ * @param initial - The initial value of the state for the hook.
657
+ * @returns The `useStore` function returns an array with two elements: the current state value and a
658
+ * `setState` function that can be used to update the state.
659
+ */
660
+ const useStore = (initial) => {
661
+ const oldHook =
662
+ vars.wipFiber.alternate &&
663
+ vars.wipFiber.alternate.hooks &&
664
+ vars.wipFiber.alternate.hooks[vars.hookIndex];
665
+
666
+ const hook = {
667
+ state: oldHook ? oldHook.state : initial,
668
+
669
+ queue: oldHook ? [...oldHook.queue] : [],
670
+ };
671
+
672
+ hook.queue.forEach((action) => {
673
+ hook.state =
674
+ typeof action === STRINGS.function ? action(hook.state) : action;
675
+ });
676
+
677
+ hook.queue = [];
678
+
679
+ const setState = (action) => {
680
+ hook.queue.push(action);
681
+
682
+ vars.wipRoot = {
683
+ dom: vars.currentRoot.dom,
684
+
685
+ props: {
686
+ ...vars.currentRoot.props,
687
+ },
688
+
689
+ alternate: vars.currentRoot,
690
+ };
691
+
692
+ vars.nextUnitOfWork = vars.wipRoot;
693
+
694
+ vars.deletions = [];
695
+ };
696
+
697
+ if (vars.wipFiber && vars.wipFiber.hooks) {
698
+ vars.wipFiber.hooks.push(hook);
699
+
700
+ vars.hookIndex++;
701
+ }
702
+
703
+ return [hook.state, setState]
704
+ };
705
+
706
+ /**
707
+ * This is a function that creates a hook for managing side effects in Ryunix components.
708
+ * @param effect - The effect function that will be executed after the component has rendered or when
709
+ * the dependencies have changed. It can perform side effects such as fetching data, updating the DOM,
710
+ * or subscribing to events.
711
+ * @param deps - An array of dependencies that the effect depends on. If any of the dependencies change
712
+ * between renders, the effect will be re-run. If the array is empty, the effect will only run once on
713
+ * mount and never again.
714
+ */
715
+
716
+ const useEffect = (callback, deps) => {
717
+ const oldHook =
718
+ vars.wipFiber.alternate &&
719
+ vars.wipFiber.alternate.hooks &&
720
+ vars.wipFiber.alternate.hooks[vars.hookIndex];
721
+
722
+ const hook = {
723
+ type: RYUNIX_TYPES.RYUNIX_EFFECT,
724
+ deps,
725
+ };
726
+
727
+ if (!oldHook) {
728
+ // invoke callback if this is the first time
729
+ callback();
730
+ } else {
731
+ if (!isEqual(oldHook.deps, hook.deps)) {
732
+ callback();
733
+ }
734
+ }
735
+
736
+ if (vars.wipFiber.hooks) {
737
+ vars.wipFiber.hooks.push(hook);
738
+ vars.hookIndex++;
739
+ }
740
+ };
741
+
742
+ const useRef = (initial) => {
743
+ const oldHook =
744
+ vars.wipFiber.alternate &&
745
+ vars.wipFiber.alternate.hooks &&
746
+ vars.wipFiber.alternate.hooks[vars.hookIndex];
747
+
748
+ const hook = {
749
+ type: RYUNIX_TYPES.RYUNIX_REF,
750
+ value: oldHook ? oldHook.value : { current: initial },
751
+ };
752
+
753
+ if (vars.wipFiber.hooks) {
754
+ vars.wipFiber.hooks.push(hook);
755
+ vars.hookIndex++;
756
+ }
757
+
758
+ return hook.value
759
+ };
760
+
761
+ const useMemo = (comp, deps) => {
762
+ const oldHook =
763
+ vars.wipFiber.alternate &&
764
+ vars.wipFiber.alternate.hooks &&
765
+ vars.wipFiber.alternate.hooks[vars.hookIndex];
766
+
767
+ const hook = {
768
+ type: RYUNIX_TYPES.RYUNIX_MEMO,
769
+ value: null,
770
+ deps,
771
+ };
772
+
773
+ if (oldHook) {
774
+ if (isEqual(oldHook.deps, hook.deps)) {
775
+ hook.value = oldHook.value;
776
+ } else {
777
+ hook.value = comp();
778
+ }
779
+ } else {
780
+ hook.value = comp();
781
+ }
782
+
783
+ if (vars.wipFiber.hooks) {
784
+ vars.wipFiber.hooks.push(hook);
785
+ vars.hookIndex++;
786
+ }
787
+
788
+ return hook.value
789
+ };
790
+
791
+ const useCallback = (callback, deps) => {
792
+ return useMemo(() => callback, deps)
793
+ };
794
+
795
+ /**
796
+ * The `useQuery` function parses the query parameters from the URL and returns them as an object.
797
+ * @returns An object containing key-value pairs of the query parameters from the URLSearchParams in
798
+ * the current window's URL is being returned.
799
+ */
800
+ const useQuery = () => {
801
+ const searchParams = new URLSearchParams(window.location.search);
802
+ const query = {};
803
+ for (let [key, value] of searchParams.entries()) {
804
+ query[key] = value;
805
+ }
806
+ return query
807
+ };
808
+
809
+ /**
810
+ * `useRouter` is a routing function to manage navigation, nested routes, and route pre-loading.
811
+ *
812
+ * This function handles client-side routing, URL updates, and component rendering based on defined routes. It supports:
813
+ * - Dynamic routes (e.g., "/user/:id").
814
+ * - Optional nested routes with an `subRoutes` property in route objects.
815
+ * - Default pre-loading of all routes except the current active route.
816
+ *
817
+ * @param {Array} routes - An array of route objects, each containing:
818
+ * - `path` (string): The URL path to match (supports dynamic segments like "/user/:id").
819
+ * - `component` (function): The component to render when the route matches.
820
+ * - `subRoutes` (optional array): An optional array of nested route objects, defining sub-routes for this route.
821
+ * - `NotFound` (optional function): Component to render for unmatched routes (default 404 behavior).
822
+ *
823
+ * @returns {Object} - An object with:
824
+ * - `Children` (function): Returns the component that matches the current route, passing route parameters and query parameters as props.
825
+ * - `NavLink` (component): A link component to navigate within the application without refreshing the page.
826
+ * - `navigate` (function): Allows programmatically navigating to a specific path.
827
+ *
828
+ * @example
829
+ * // Define nested routes
830
+ * const routes = [
831
+ * {
832
+ * path: "/",
833
+ * component: HomePage,
834
+ * subRoutes: [
835
+ * {
836
+ * path: "/settings",
837
+ * component: SettingsPage,
838
+ * },
839
+ * ],
840
+ * },
841
+ * {
842
+ * path: "/user/:id",
843
+ * component: UserProfile,
844
+ * },
845
+ * {
846
+ * path: "*",
847
+ * NotFound: NotFoundPage,
848
+ * },
849
+ * ];
850
+ *
851
+ * // Use the routing function
852
+ * const { Children, NavLink } = useRouter(routes);
853
+ *
854
+ * // Render the matched component
855
+ * const App = () => (
856
+ * <>
857
+ * <NavLink to="/">Home</NavLink>
858
+ * <NavLink to="/settings">Settings</NavLink>
859
+ * <NavLink to="/user/123">User Profile</NavLink>
860
+ * <Children />
861
+ * </>
862
+ * );
863
+ */
864
+ const useRouter = (routes) => {
865
+ const [location, setLocation] = useStore(window.location.pathname);
866
+
867
+ const findRoute = (routes, path) => {
868
+ const pathname = path.split('?')[0];
869
+
870
+ const notFoundRoute = routes.find((route) => route.NotFound);
871
+ const notFound = notFoundRoute
872
+ ? { route: { component: notFoundRoute.NotFound }, params: {} }
873
+ : { route: { component: null }, params: {} };
874
+
875
+ for (const route of routes) {
876
+ if (route.subRoutes) {
877
+ const childRoute = findRoute(route.subRoutes, path);
878
+ if (childRoute) return childRoute
879
+ }
880
+
881
+ if (route.path === '*') {
882
+ return notFound
883
+ }
884
+
885
+ if (!route.path || typeof route.path !== 'string') {
886
+ console.warn('Invalid route detected:', route);
887
+ console.info(
888
+ "if you are using { NotFound: NotFound } please add { path: '*', NotFound: NotFound }",
889
+ );
890
+ continue
891
+ }
892
+
893
+ const keys = [];
894
+ const pattern = new RegExp(
895
+ `^${route.path.replace(/:\w+/g, (match) => {
896
+ keys.push(match.substring(1));
897
+ return '([^/]+)'
898
+ })}$`,
899
+ );
900
+
901
+ const match = pathname.match(pattern);
902
+ if (match) {
903
+ const params = keys.reduce((acc, key, index) => {
904
+ acc[key] = match[index + 1];
905
+ return acc
906
+ }, {});
907
+
908
+ return { route, params }
909
+ }
910
+ }
911
+
912
+ return notFound
913
+ };
914
+
915
+ const navigate = (path) => {
916
+ window.history.pushState({}, '', path);
917
+ updateRoute(path);
918
+ };
919
+
920
+ const updateRoute = (path) => {
921
+ const cleanedPath = path.split('?')[0];
922
+ setLocation(cleanedPath);
923
+ };
924
+
925
+ useEffect(() => {
926
+ const onPopState = () => updateRoute(window.location.pathname);
927
+ window.addEventListener('popstate', onPopState);
928
+
929
+ return () => window.removeEventListener('popstate', onPopState)
930
+ }, []);
931
+
932
+ const currentRouteData = findRoute(routes, location) || {};
933
+
934
+ const Children = () => {
935
+ const query = useQuery();
936
+ const { route } = currentRouteData;
937
+
938
+ if (
939
+ !route ||
940
+ !route.component ||
941
+ typeof route.component !== STRINGS.function
942
+ ) {
943
+ console.error(
944
+ 'Component not found for current path or the component is not a valid function:',
945
+ currentRouteData,
946
+ );
947
+ return null
948
+ }
949
+
950
+ return route.component({
951
+ params: currentRouteData.params || {},
952
+ query,
953
+ })
954
+ };
955
+
956
+ const NavLink = ({ to, ...props }) => {
957
+ const handleClick = (e) => {
958
+ e.preventDefault();
959
+ navigate(to);
960
+ };
961
+ return createElement(
962
+ 'a',
963
+ { href: to, onClick: handleClick, ...props },
964
+ props.children,
965
+ )
966
+ };
967
+
968
+ return { Children, NavLink, navigate }
969
+ };
970
+
971
+ const createContext = (defaultValue) => {
972
+ const context = {
973
+ value: defaultValue,
974
+ subscribers: [],
975
+ Provider: ({ value, children }) => {
976
+ context.value = value;
977
+ context.subscribers.forEach((subscriber) => subscriber(value));
978
+ return children
979
+ },
980
+ Consumer: ({ children }) => {
981
+ const [currentValue, setCurrentValue] = useStore(context.value);
982
+ context.subscribers.push(setCurrentValue);
983
+ return children(currentValue)
984
+ },
985
+ };
986
+ return context
987
+ };
988
+
989
+ var Ryunix = {
990
+ Dom,
991
+ Workers,
992
+ Reconciler,
993
+ Components,
994
+ Commits,
995
+ createElement,
996
+ Fragment,
997
+ init,
998
+ render,
999
+ };
1000
+
1001
+ window.Ryunix = Ryunix;
1002
+
1003
+ exports.createContext = createContext;
1004
+ exports.default = Ryunix;
1005
+ exports.useCallback = useCallback;
1006
+ exports.useEffect = useEffect;
1007
+ exports.useMemo = useMemo;
1008
+ exports.useQuery = useQuery;
1009
+ exports.useRef = useRef;
1010
+ exports.useRouter = useRouter;
1011
+ exports.useStore = useStore;
1012
+
1013
+ Object.defineProperty(exports, '__esModule', { value: true });
1014
+
1015
+ }));