@unsetsoft/ryunixjs 1.1.5 → 1.1.6-canary.10

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