@unsetsoft/ryunixjs 1.1.5-nightly.78 → 1.1.5-nightly.80

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