@unsetsoft/ryunixjs 1.1.5 → 1.1.6

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