@unsetsoft/ryunixjs 0.2.28 → 0.2.29-nightly.1

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/lib/dom.js DELETED
@@ -1,592 +0,0 @@
1
- let containerRoot = null;
2
- let nextUnitOfWork = null;
3
- let currentRoot = null;
4
- let wipRoot = null;
5
- let deletions = null;
6
- let wipFiber = null;
7
- let hookIndex = null;
8
-
9
- const RYUNIX_TYPES = {
10
- TEXT_ELEMENT: Symbol("text.element"),
11
- RYUNIX_EFFECT: Symbol("ryunix.effect"),
12
- RYUNIX_CONTEXT: Symbol("ryunix.context"),
13
- };
14
-
15
- const STRINGS = {
16
- object: "object",
17
- function: "function",
18
- style: "style",
19
- className: "className",
20
- children: "children",
21
- };
22
-
23
- const EFFECT_TAGS = {
24
- PLACEMENT: Symbol(),
25
- UPDATE: Symbol(),
26
- DELETION: Symbol(),
27
- };
28
-
29
- const isEvent = (key) => key.startsWith("on");
30
- const isProperty = (key) => key !== STRINGS.children && !isEvent(key);
31
- const isNew = (prev, next) => (key) => prev[key] !== next[key];
32
- const isGone = (next) => (key) => !(key in next);
33
- const reg = /[A-Z]/g;
34
- const hasDepsChanged = (prevDeps, nextDeps) =>
35
- !prevDeps ||
36
- !nextDeps ||
37
- prevDeps.length !== nextDeps.length ||
38
- prevDeps.some((dep, index) => dep !== nextDeps[index]);
39
-
40
- /**
41
- * The function creates a new element with the given type, props, and children.
42
- * @param type - The type of the element to be created, such as "div", "span", "h1", etc.
43
- * @param props - The `props` parameter is an object that contains the properties or attributes of the
44
- * element being created. These properties can include things like `className`, `id`, `style`, and any
45
- * other custom attributes that the user wants to add to the element. The `props` object is spread
46
- * using the spread
47
- * @param children - The `children` parameter is a rest parameter that allows the function to accept
48
- * any number of arguments after the `props` parameter. These arguments will be treated as children
49
- * elements of the created element. The `map` function is used to iterate over each child and create a
50
- * new element if it is not
51
- * @returns A JavaScript object with a `type` property and a `props` property. The `type` property is
52
- * set to the `type` argument passed into the function, and the `props` property is an object that
53
- * includes any additional properties passed in the `props` argument, as well as a `children` property
54
- * that is an array of any child elements passed in the `...children` argument
55
- */
56
- function createElement(type, props, ...children) {
57
- return {
58
- type,
59
- props: {
60
- ...props,
61
- children: children
62
- .flat()
63
- .map((child) =>
64
- typeof child === STRINGS.object ? child : createTextElement(child)
65
- ),
66
- },
67
- };
68
- }
69
-
70
- /**
71
- * The function creates a text element with a given text value.
72
- * @param text - The text content that will be used to create a new text element.
73
- * @returns A JavaScript object with a `type` property set to `"TEXT_ELEMENT"` and a `props` property
74
- * that contains a `nodeValue` property set to the `text` parameter and an empty `children` array.
75
- */
76
- function createTextElement(text) {
77
- return {
78
- type: RYUNIX_TYPES.TEXT_ELEMENT,
79
- props: {
80
- nodeValue: text,
81
- children: [],
82
- },
83
- };
84
- }
85
-
86
- /**
87
- * The function creates a new DOM element based on the given fiber object and updates its properties.
88
- * @param fiber - The fiber parameter is an object that represents a node in the fiber tree. It
89
- * contains information about the element type, props, and children of the node.
90
- * @returns The `createDom` function returns a newly created DOM element based on the `fiber` object
91
- * passed as an argument. If the `fiber` object represents a text element, a text node is created using
92
- * `document.createTextNode("")`. Otherwise, a new element is created using
93
- * `document.createElement(fiber.type)`. The function then calls the `updateDom` function to update the
94
- * properties of the newly created
95
- */
96
- function createDom(fiber) {
97
- const dom =
98
- fiber.type == RYUNIX_TYPES.TEXT_ELEMENT
99
- ? document.createTextNode("")
100
- : document.createElement(fiber.type);
101
-
102
- updateDom(dom, {}, fiber.props);
103
-
104
- return dom;
105
- }
106
-
107
- /**
108
- * The function updates the DOM by removing old event listeners and properties, and adding new ones
109
- * based on the previous and next props.
110
- * @param dom - The DOM element that needs to be updated with new props.
111
- * @param prevProps - An object representing the previous props (properties) of a DOM element.
112
- * @param nextProps - An object containing the new props that need to be updated in the DOM.
113
- */
114
- function updateDom(dom, prevProps, nextProps) {
115
- Object.keys(prevProps)
116
- .filter(isEvent)
117
- .filter((key) => isGone(nextProps)(key) || isNew(prevProps, nextProps)(key))
118
- .forEach((name) => {
119
- const eventType = name.toLowerCase().substring(2);
120
- dom.removeEventListener(eventType, prevProps[name]);
121
- });
122
-
123
- Object.keys(prevProps)
124
- .filter(isProperty)
125
- .filter(isGone(nextProps))
126
- .forEach((name) => {
127
- dom[name] = "";
128
- });
129
-
130
- Object.keys(nextProps)
131
- .filter(isProperty)
132
- .filter(isNew(prevProps, nextProps))
133
- .forEach((name) => {
134
- if (name === STRINGS.style) {
135
- DomStyle(dom, nextProps.style);
136
- } else if (name === STRINGS.className) {
137
- if (nextProps.className === "") {
138
- throw new Error("className cannot be empty.");
139
- }
140
- prevProps.className &&
141
- dom.classList.remove(...prevProps.className.split(/\s+/));
142
- dom.classList.add(...nextProps.className.split(/\s+/));
143
- } else {
144
- dom[name] = nextProps[name];
145
- }
146
- });
147
-
148
- Object.keys(nextProps)
149
- .filter(isEvent)
150
- .filter(isNew(prevProps, nextProps))
151
- .forEach((name) => {
152
- const eventType = name.toLowerCase().substring(2);
153
- dom.addEventListener(eventType, nextProps[name]);
154
- });
155
- }
156
-
157
- function DomStyle(dom, style) {
158
- dom.style = Object.keys(style).reduce((acc, styleName) => {
159
- const key = styleName.replace(reg, function (v) {
160
- return "-" + v.toLowerCase();
161
- });
162
- acc += `${key}: ${style[styleName]};`;
163
- return acc;
164
- }, "");
165
- }
166
-
167
- /**
168
- * The function commits changes made to the virtual DOM to the actual DOM.
169
- */
170
- function commitRoot() {
171
- deletions.forEach(commitWork);
172
- commitWork(wipRoot.child);
173
- currentRoot = wipRoot;
174
- wipRoot = null;
175
- }
176
-
177
- /**
178
- * The function cancels all effect hooks in a given fiber.
179
- * @param fiber - The "fiber" parameter is likely referring to a data structure used in React.js to
180
- * represent a component and its state. It contains information about the component's props, state, and
181
- * children, as well as metadata used by React to manage updates and rendering. The function
182
- * "cancelEffects" is likely intended
183
- */
184
- function cancelEffects(fiber) {
185
- if (fiber.hooks) {
186
- fiber.hooks
187
- .filter((hook) => hook.tag === RYUNIX_TYPES.RYUNIX_EFFECT && hook.cancel)
188
- .forEach((effectHook) => {
189
- effectHook.cancel();
190
- });
191
- }
192
- }
193
-
194
- /**
195
- * The function runs all effect hooks in a given fiber.
196
- * @param fiber - The "fiber" parameter is likely referring to a data structure used in the
197
- * implementation of a fiber-based reconciliation algorithm, such as the one used in React. A fiber
198
- * represents a unit of work that needs to be performed by the reconciliation algorithm, and it
199
- * contains information about a component and its children, as
200
- */
201
- function runEffects(fiber) {
202
- if (fiber.hooks) {
203
- fiber.hooks
204
- .filter((hook) => hook.tag === RYUNIX_TYPES.RYUNIX_EFFECT && hook.effect)
205
- .forEach((effectHook) => {
206
- effectHook.cancel = effectHook.effect();
207
- });
208
- }
209
- }
210
-
211
- /**
212
- * The function commits changes made to the DOM based on the effect tag of the fiber.
213
- * @param fiber - A fiber is a unit of work in Ryunix's reconciliation process. It represents a
214
- * component and its state at a particular point in time. The `commitWork` function takes a fiber as a
215
- * parameter to commit the changes made during the reconciliation process to the actual DOM.
216
- * @returns The function does not return anything, it performs side effects by manipulating the DOM.
217
- */
218
- function commitWork(fiber) {
219
- if (!fiber) {
220
- return;
221
- }
222
-
223
- let domParentFiber = fiber.parent;
224
- while (!domParentFiber.dom) {
225
- domParentFiber = domParentFiber.parent;
226
- }
227
- const domParent = domParentFiber.dom;
228
-
229
- if (fiber.effectTag === EFFECT_TAGS.PLACEMENT) {
230
- if (fiber.dom != null) {
231
- domParent.appendChild(fiber.dom);
232
- }
233
- runEffects(fiber);
234
- } else if (fiber.effectTag === EFFECT_TAGS.UPDATE) {
235
- cancelEffects(fiber);
236
- if (fiber.dom != null) {
237
- updateDom(fiber.dom, fiber.alternate.props, fiber.props);
238
- }
239
- runEffects(fiber);
240
- } else if (fiber.effectTag === EFFECT_TAGS.DELETION) {
241
- cancelEffects(fiber);
242
- commitDeletion(fiber, domParent);
243
- return;
244
- }
245
-
246
- commitWork(fiber.child);
247
- commitWork(fiber.sibling);
248
- }
249
-
250
- /**
251
- * The function removes a fiber's corresponding DOM node from its parent node or recursively removes
252
- * its child's DOM node until it finds a node to remove.
253
- * @param fiber - a fiber node in a fiber tree, which represents a component or an element in the Ryunix
254
- * application.
255
- * @param domParent - The parent DOM element from which the fiber's DOM element needs to be removed.
256
- */
257
- function commitDeletion(fiber, domParent) {
258
- if (fiber.dom) {
259
- domParent.removeChild(fiber.dom);
260
- } else {
261
- commitDeletion(fiber.child, domParent);
262
- }
263
- }
264
-
265
- /**
266
- * @deprecated use Ryunix.init(root) instead.
267
- *
268
- * @description The function creates a root container for a web application.
269
- * @example Ryunix.createRoot(document.getElementById("root")) -> <div id="root" />
270
- * @param root - The parameter `root` is likely referring to an HTML element that will serve as the
271
- * root or container for a web application or component. The `createRoot` function takes this element
272
- * as an argument and assigns it to a variable called `containerRoot`. This variable can then be used
273
- * to manipulate the contents
274
- *
275
- */
276
- function createRoot(root) {
277
- containerRoot = root;
278
- }
279
-
280
- /**
281
- * @description The function creates a reference to a DOM element with the specified ID. This will be used to initialize the app.
282
- * @example Ryunix.init("root") -> <div id="root" />
283
- * @param root - The parameter "root" is the id of the HTML element that will serve as the container
284
- * for the root element.
285
- */
286
- function init(root) {
287
- containerRoot = document.getElementById(root);
288
- }
289
-
290
- /**
291
- * The function renders an element into a container using a work-in-progress root.
292
- * @param element - The element parameter is the component or element that needs to be rendered in the
293
- * container. It could be a Ryunix component or a DOM element.
294
- * @param container - The container parameter is the DOM element where the rendered element will be
295
- * appended to. this parameter is optional if you use createRoot().
296
- */
297
- function render(element, container) {
298
- wipRoot = {
299
- dom: containerRoot || container,
300
- props: {
301
- children: [element],
302
- },
303
- alternate: currentRoot,
304
- };
305
- deletions = [];
306
- nextUnitOfWork = wipRoot;
307
- }
308
-
309
- /**
310
- * This function uses requestIdleCallback to perform work on a fiber tree until it is complete or the
311
- * browser needs to yield to other tasks.
312
- * @param deadline - The `deadline` parameter is an object that represents the amount of time the
313
- * browser has to perform work before it needs to handle other tasks. It has a `timeRemaining()` method
314
- * that returns the amount of time remaining before the deadline is reached. The `shouldYield` variable
315
- * is used to determine
316
- */
317
- function workLoop(deadline) {
318
- let shouldYield = false;
319
- while (nextUnitOfWork && !shouldYield) {
320
- nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
321
- shouldYield = deadline.timeRemaining() < 1;
322
- }
323
-
324
- if (!nextUnitOfWork && wipRoot) {
325
- commitRoot();
326
- }
327
-
328
- requestIdleCallback(workLoop);
329
- }
330
-
331
- requestIdleCallback(workLoop);
332
-
333
- /**
334
- * The function performs a unit of work by updating either a function component or a host component and
335
- * returns the next fiber to be processed.
336
- * @param fiber - A fiber is a unit of work in Ryunix that represents a component and its state. It
337
- * contains information about the component's type, props, and children, as well as pointers to its
338
- * parent, child, and sibling fibers. The `performUnitOfWork` function takes a fiber as a parameter and
339
- * performs work
340
- * @returns The function `performUnitOfWork` returns the next fiber to be processed. If the current
341
- * fiber has a child, it returns the child. Otherwise, it looks for the next sibling of the current
342
- * fiber. If there are no more siblings, it goes up the tree to the parent and looks for the next
343
- * sibling of the parent. The function returns `null` if there are no more fibers to process.
344
- */
345
- function performUnitOfWork(fiber) {
346
- const isFunctionComponent = fiber.type instanceof Function;
347
- if (isFunctionComponent) {
348
- updateFunctionComponent(fiber);
349
- } else {
350
- updateHostComponent(fiber);
351
- }
352
- if (fiber.child) {
353
- return fiber.child;
354
- }
355
- let nextFiber = fiber;
356
- while (nextFiber) {
357
- if (nextFiber.sibling) {
358
- return nextFiber.sibling;
359
- }
360
- nextFiber = nextFiber.parent;
361
- }
362
- }
363
-
364
- /**
365
- * This function updates a function component by setting up a work-in-progress fiber, resetting the
366
- * hook index, creating an empty hooks array, rendering the component, and reconciling its children.
367
- * @param fiber - The fiber parameter is an object that represents a node in the fiber tree. It
368
- * contains information about the component, its props, state, and children. In this function, it is
369
- * used to update the state of the component and its children.
370
- */
371
- function updateFunctionComponent(fiber) {
372
- wipFiber = fiber;
373
- hookIndex = 0;
374
- wipFiber.hooks = [];
375
- const children = [fiber.type(fiber.props)];
376
- reconcileChildren(fiber, children);
377
- }
378
-
379
- /**
380
- * This function updates a host component's DOM element and reconciles its children.
381
- * @param fiber - A fiber is a unit of work in Ryunix that represents a component and its state. It
382
- * contains information about the component's type, props, and children, as well as pointers to other
383
- * fibers in the tree.
384
- */
385
- function updateHostComponent(fiber) {
386
- if (!fiber.dom) {
387
- fiber.dom = createDom(fiber);
388
- }
389
- reconcileChildren(fiber, fiber.props.children.flat());
390
- }
391
-
392
- /**
393
- * This function reconciles the children of a fiber node with a new set of elements, creating new
394
- * fibers for new elements, updating existing fibers for elements with the same type, and marking old
395
- * fibers for deletion if they are not present in the new set of elements.
396
- * @param wipFiber - A work-in-progress fiber object representing a component or element in the virtual
397
- * DOM tree.
398
- * @param elements - an array of elements representing the new children to be rendered in the current
399
- * fiber's subtree
400
- */
401
- function reconcileChildren(wipFiber, elements) {
402
- let index = 0;
403
- let oldFiber = wipFiber.alternate && wipFiber.alternate.child;
404
- let prevSibling = null;
405
-
406
- while (index < elements.length || oldFiber != null) {
407
- const element = elements[index];
408
- let newFiber = null;
409
-
410
- const sameType = oldFiber && element && element.type == oldFiber.type;
411
-
412
- if (sameType) {
413
- newFiber = {
414
- type: oldFiber.type,
415
- props: element.props,
416
- dom: oldFiber.dom,
417
- parent: wipFiber,
418
- alternate: oldFiber,
419
- effectTag: EFFECT_TAGS.UPDATE,
420
- };
421
- }
422
- if (element && !sameType) {
423
- newFiber = {
424
- type: element.type,
425
- props: element.props,
426
- dom: null,
427
- parent: wipFiber,
428
- alternate: null,
429
- effectTag: EFFECT_TAGS.PLACEMENT,
430
- };
431
- }
432
- if (oldFiber && !sameType) {
433
- oldFiber.effectTag = EFFECT_TAGS.DELETION;
434
- deletions.push(oldFiber);
435
- }
436
-
437
- if (oldFiber) {
438
- oldFiber = oldFiber.sibling;
439
- }
440
-
441
- if (index === 0) {
442
- wipFiber.child = newFiber;
443
- } else if (element) {
444
- prevSibling.sibling = newFiber;
445
- }
446
-
447
- prevSibling = newFiber;
448
- index++;
449
- }
450
- }
451
-
452
- /**
453
- * The function createContext creates a context object with a default value and methods to set and get
454
- * the context value.
455
- * @param defaultValue - The `defaultValue` parameter is the initial value that will be assigned to the
456
- * `contextValue` variable if no value is provided when creating the context.
457
- * @returns a context object.
458
- */
459
- function createContext(defaultValue) {
460
- let contextValue = defaultValue || null;
461
-
462
- const context = {
463
- tag: RYUNIX_TYPES.RYUNIX_CONTEXT,
464
- Value: contextValue,
465
- Provider: null,
466
- };
467
-
468
- context.Provider = (value) => (context.Value = value);
469
-
470
- return context;
471
- }
472
-
473
- function Fragments(props) {
474
- if (props.style) {
475
- throw new Error("The style attribute is not supported");
476
- }
477
- if (props.className === "") {
478
- throw new Error("className cannot be empty.");
479
- }
480
- return createElement("div", props, props.children);
481
- }
482
-
483
- // Hooks
484
-
485
- /**
486
- * The function `useContext` is used to read and subscribe to context from your component.
487
- * @param ref - The `ref` parameter is a reference to a context object.
488
- * @returns The `Value` property of the `hook` object is being returned.
489
- */
490
- function useContext(ref) {
491
- hookIndex++;
492
-
493
- const oldHook =
494
- wipFiber.alternate &&
495
- wipFiber.alternate.hooks &&
496
- wipFiber.alternate.hooks[hookIndex];
497
-
498
- const hasOld = oldHook ? oldHook : undefined;
499
- const Context = hasOld ? hasOld : ref;
500
- const hook = {
501
- ...Context,
502
- };
503
-
504
- wipFiber.hooks.push(hook);
505
-
506
- return hook.Value;
507
- }
508
-
509
- /**
510
- * @description The function creates a state.
511
- * @param initial - The initial value of the state for the hook.
512
- * @returns The `useStore` function returns an array with two elements: the current state value and a
513
- * `setState` function that can be used to update the state.
514
- */
515
- function useStore(initial) {
516
- const oldHook =
517
- wipFiber.alternate &&
518
- wipFiber.alternate.hooks &&
519
- wipFiber.alternate.hooks[hookIndex];
520
- const hook = {
521
- state: oldHook ? oldHook.state : initial,
522
- queue: [],
523
- };
524
-
525
- const actions = oldHook ? oldHook.queue : [];
526
- actions.forEach((action) => {
527
- hook.state =
528
- typeof action === STRINGS.function ? action(hook.state) : action;
529
- });
530
-
531
- /**
532
- * The function `setState` updates the state of a component in Ryunix by adding an action to a queue
533
- * and setting up a new work-in-progress root.
534
- * @param action - The `action` parameter is an object that represents a state update to be performed
535
- * on a component. It contains information about the type of update to be performed and any new data
536
- * that needs to be applied to the component's state.
537
- */
538
- const setState = (action) => {
539
- hook.queue.push(action);
540
- wipRoot = {
541
- dom: currentRoot.dom,
542
- props: currentRoot.props,
543
- alternate: currentRoot,
544
- };
545
- nextUnitOfWork = wipRoot;
546
- deletions = [];
547
- };
548
-
549
- wipFiber.hooks.push(hook);
550
- hookIndex++;
551
- return [hook.state, setState];
552
- }
553
-
554
- /**
555
- * This is a function that creates a hook for managing side effects in Ryunix components.
556
- * @param effect - The effect function that will be executed after the component has rendered or when
557
- * the dependencies have changed. It can perform side effects such as fetching data, updating the DOM,
558
- * or subscribing to events.
559
- * @param deps - An array of dependencies that the effect depends on. If any of the dependencies change
560
- * between renders, the effect will be re-run. If the array is empty, the effect will only run once on
561
- * mount and never again.
562
- */
563
- function useEffect(effect, deps) {
564
- const oldHook =
565
- wipFiber.alternate &&
566
- wipFiber.alternate.hooks &&
567
- wipFiber.alternate.hooks[hookIndex];
568
-
569
- const hasChanged = hasDepsChanged(oldHook ? oldHook.deps : undefined, deps);
570
-
571
- const hook = {
572
- tag: RYUNIX_TYPES.RYUNIX_EFFECT,
573
- effect: hasChanged ? effect : null,
574
- cancel: hasChanged && oldHook && oldHook.cancel,
575
- deps,
576
- };
577
-
578
- wipFiber.hooks.push(hook);
579
- hookIndex++;
580
- }
581
-
582
- // export
583
-
584
- export { useStore, useEffect, createContext, useContext, Fragments };
585
-
586
- export default {
587
- createElement,
588
- render,
589
- createRoot,
590
- init,
591
- Fragments,
592
- };