@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/src/lib/hooks.js DELETED
@@ -1,288 +0,0 @@
1
- import { RYUNIX_TYPES, STRINGS, vars } from '../utils/index'
2
- import { isEqual } from 'lodash'
3
- import { createElement } from './createElement'
4
- /**
5
- * @description The function creates a state.
6
- * @param initial - The initial value of the state for the hook.
7
- * @returns The `useStore` function returns an array with two elements: the current state value and a
8
- * `setState` function that can be used to update the state.
9
- */
10
- const useStore = (initial) => {
11
- const oldHook =
12
- vars.wipFiber.alternate &&
13
- vars.wipFiber.alternate.hooks &&
14
- vars.wipFiber.alternate.hooks[vars.hookIndex]
15
- const hook = {
16
- state: oldHook ? oldHook.state : initial,
17
- queue: oldHook ? [...oldHook.queue] : [],
18
- }
19
-
20
- hook.queue.forEach((action) => {
21
- hook.state =
22
- typeof action === STRINGS.function ? action(hook.state) : action
23
- })
24
-
25
- hook.queue = []
26
-
27
- const setState = (action) => {
28
- hook.queue.push(action)
29
-
30
- vars.wipRoot = {
31
- dom: vars.currentRoot.dom,
32
- props: vars.currentRoot.props,
33
- alternate: vars.currentRoot,
34
- }
35
- vars.nextUnitOfWork = vars.wipRoot
36
- vars.deletions = []
37
- }
38
-
39
- if (vars.wipFiber && vars.wipFiber.hooks) {
40
- vars.wipFiber.hooks.push(hook)
41
- vars.hookIndex++
42
- }
43
-
44
- return [hook.state, setState]
45
- }
46
-
47
- /**
48
- * This is a function that creates a hook for managing side effects in Ryunix components.
49
- * @param effect - The effect function that will be executed after the component has rendered or when
50
- * the dependencies have changed. It can perform side effects such as fetching data, updating the DOM,
51
- * or subscribing to events.
52
- * @param deps - An array of dependencies that the effect depends on. If any of the dependencies change
53
- * between renders, the effect will be re-run. If the array is empty, the effect will only run once on
54
- * mount and never again.
55
- */
56
-
57
- const useEffect = (callback, deps) => {
58
- const oldHook =
59
- vars.wipFiber.alternate &&
60
- vars.wipFiber.alternate.hooks &&
61
- vars.wipFiber.alternate.hooks[vars.hookIndex]
62
-
63
- const hook = {
64
- type: RYUNIX_TYPES.RYUNIX_EFFECT,
65
- deps,
66
- }
67
-
68
- if (!oldHook) {
69
- // invoke callback if this is the first time
70
- callback()
71
- } else {
72
- if (!isEqual(oldHook.deps, hook.deps)) {
73
- callback()
74
- }
75
- }
76
-
77
- if (vars.wipFiber.hooks) {
78
- vars.wipFiber.hooks.push(hook)
79
- vars.hookIndex++
80
- }
81
- }
82
-
83
- const useRef = (initial) => {
84
- const oldHook =
85
- vars.wipFiber.alternate &&
86
- vars.wipFiber.alternate.hooks &&
87
- vars.wipFiber.alternate.hooks[vars.hookIndex]
88
-
89
- const hook = {
90
- type: RYUNIX_TYPES.RYUNIX_REF,
91
- value: oldHook ? oldHook.value : { current: initial },
92
- }
93
-
94
- if (vars.wipFiber.hooks) {
95
- vars.wipFiber.hooks.push(hook)
96
- vars.hookIndex++
97
- }
98
-
99
- return hook.value
100
- }
101
-
102
- const useMemo = (comp, deps) => {
103
- const oldHook =
104
- vars.wipFiber.alternate &&
105
- vars.wipFiber.alternate.hooks &&
106
- vars.wipFiber.alternate.hooks[vars.hookIndex]
107
-
108
- const hook = {
109
- type: RYUNIX_TYPES.RYUNIX_MEMO,
110
- value: null,
111
- deps,
112
- }
113
-
114
- if (oldHook) {
115
- if (isEqual(oldHook.deps, hook.deps)) {
116
- hook.value = oldHook.value
117
- } else {
118
- hook.value = comp()
119
- }
120
- } else {
121
- hook.value = comp()
122
- }
123
-
124
- if (vars.wipFiber.hooks) {
125
- vars.wipFiber.hooks.push(hook)
126
- vars.hookIndex++
127
- }
128
-
129
- return hook.value
130
- }
131
-
132
- const useCallback = (callback, deps) => {
133
- return useMemo(() => callback, deps)
134
- }
135
-
136
- /**
137
- * The `useQuery` function parses the query parameters from the URL and returns them as an object.
138
- * @returns An object containing key-value pairs of the query parameters from the URLSearchParams in
139
- * the current window's URL is being returned.
140
- */
141
- const useQuery = () => {
142
- const searchParams = new URLSearchParams(window.location.search)
143
- const query = {}
144
- for (let [key, value] of searchParams.entries()) {
145
- query[key] = value
146
- }
147
- return query
148
- }
149
-
150
- /**
151
- * useRouter is a routing function to manage navigation and route matching.
152
- *
153
- * This function handles client-side routing, URL updates, and component rendering based on defined routes.
154
- * It supports dynamic routes (e.g., "/user/:id") and allows navigation using links.
155
- *
156
- * @param {Array} routes - An array of route objects, each containing:
157
- * - `path` (string): The URL path to match (supports dynamic segments like "/user/:id").
158
- * - `component` (function): The component to render when the route matches.
159
- * - `NotFound` (optional function): Component to render for unmatched routes (default 404 behavior).
160
- *
161
- * @returns {Object} - An object with:
162
- * - `Children` (function): Returns the component that matches the current route, passing route parameters and query parameters as props.
163
- * - `NavLink` (component): A link component to navigate within the application without refreshing the page.
164
- *
165
- * @example
166
- * // Define routes
167
- * const routes = [
168
- * {
169
- * path: "/",
170
- * component: HomePage,
171
- * },
172
- * {
173
- * path: "/user/:id",
174
- * component: UserProfile,
175
- * },
176
- * {
177
- * path: "*",
178
- * NotFound: NotFoundPage,
179
- * },
180
- * ];
181
- *
182
- * // Use the routing function
183
- * const { Children, NavLink } = useRouter(routes);
184
- *
185
- * // Render the matched component
186
- * const App = () => (
187
- * <div>
188
- * <NavLink to="/">Home</NavLink>
189
- * <NavLink to="/user/123">User Profile</NavLink>
190
- * <Children />
191
- * </div>
192
- * );
193
- *
194
- * // Example: UserProfile Component that receives route parameters
195
- * const UserProfile = ({ params, query }) => {
196
- * return (
197
- * <div>
198
- * <h1>User ID: {params.id}</h1>
199
- * <p>Query Parameters: {JSON.stringify(query)}</p>
200
- * </div>
201
- * );
202
- * };
203
- */
204
-
205
- const useRouter = (routes) => {
206
- const [location, setLocation] = useStore(window.location.pathname)
207
-
208
- const navigate = (path) => {
209
- window.history.pushState({}, '', path)
210
- updateRoute(path)
211
- }
212
-
213
- const updateRoute = (path) => {
214
- setLocation(path.split('?')[0])
215
- }
216
-
217
- useEffect(() => {
218
- const onPopState = () => updateRoute(window.location.pathname)
219
- window.addEventListener('popstate', onPopState)
220
- return () => window.removeEventListener('popstate', onPopState)
221
- }, [])
222
-
223
- const findCurrentRoute = (routes, path) => {
224
- const pathname = path.split('?')[0]
225
-
226
- for (const { path: routePath, component } of routes) {
227
- if (!routePath) continue
228
-
229
- const keys = []
230
- const pattern = new RegExp(
231
- `^${routePath.replace(/:\w+/g, (match) => {
232
- keys.push(match.substring(1)) // Extract only the name without ":" and add to keys
233
- return '([^/]+)'
234
- })}$`,
235
- )
236
-
237
- const match = pathname.match(pattern)
238
- if (match) {
239
- const params = keys.reduce((acc, key, index) => {
240
- acc[key] = match[index + 1] // Match and assign the correct parameter value
241
- return acc
242
- }, {})
243
- return { route: { component }, params }
244
- }
245
- }
246
-
247
- // Return NotFound component if no match is found
248
- const notFoundRoute = routes.find((route) => route.NotFound)
249
- return notFoundRoute
250
- ? { route: { component: notFoundRoute.NotFound }, params: {} }
251
- : { route: { component: null }, params: {} }
252
- }
253
-
254
- const currentRouteData = findCurrentRoute(routes, location)
255
- const Children = () => {
256
- const query = useQuery()
257
- return currentRouteData.route.component
258
- ? currentRouteData.route.component({
259
- params: currentRouteData.params,
260
- query,
261
- })
262
- : null
263
- }
264
-
265
- const NavLink = ({ to, ...props }) => {
266
- const handleClick = (e) => {
267
- e.preventDefault()
268
- navigate(to)
269
- }
270
- return createElement(
271
- 'a',
272
- { href: to, onClick: handleClick, ...props },
273
- props.children,
274
- )
275
- }
276
-
277
- return { Children, NavLink, navigate }
278
- }
279
-
280
- export {
281
- useStore,
282
- useEffect,
283
- useQuery,
284
- useRef,
285
- useMemo,
286
- useCallback,
287
- useRouter,
288
- }
package/src/lib/index.js DELETED
@@ -1,39 +0,0 @@
1
- import { createElement, cloneElement, Fragment } from './createElement'
2
- import { render, init } from './render'
3
- import {
4
- useStore,
5
- useEffect,
6
- useQuery,
7
- useRef,
8
- useMemo,
9
- useCallback,
10
- useRouter,
11
- } from './hooks'
12
- import * as Dom from './dom'
13
- import * as Workers from './workers'
14
- import * as Reconciler from './reconciler'
15
- import * as Components from './components'
16
- import * as Commits from './commits'
17
-
18
- export {
19
- useStore,
20
- useEffect,
21
- useQuery,
22
- useRef,
23
- useMemo,
24
- useCallback,
25
- useRouter,
26
- Fragment,
27
- }
28
-
29
- export default {
30
- createElement,
31
- render,
32
- init,
33
- Fragment,
34
- Dom,
35
- Workers,
36
- Reconciler,
37
- Components,
38
- Commits,
39
- }
@@ -1,69 +0,0 @@
1
- import { EFFECT_TAGS, vars } from '../utils/index'
2
-
3
- /**
4
- * This function reconciles the children of a fiber node with a new set of elements, creating new
5
- * fibers for new elements, updating existing fibers for elements with the same type, and marking old
6
- * fibers for deletion if they are not present in the new set of elements.
7
- * @param wipFiber - A work-in-progress fiber object representing a component or element in the virtual
8
- * DOM tree.
9
- * @param elements - an array of elements representing the new children to be rendered in the current
10
- * fiber's subtree
11
- */
12
- const reconcileChildren = (wipFiber, elements) => {
13
- let index = 0
14
- let oldFiber = wipFiber.alternate && wipFiber.alternate.child
15
- let prevSibling = null
16
-
17
- const oldFibersMap = new Map()
18
- while (oldFiber) {
19
- const oldKey = oldFiber.props.key || oldFiber.type
20
- oldFibersMap.set(oldKey, oldFiber)
21
- oldFiber = oldFiber.sibling
22
- }
23
-
24
- while (index < elements.length) {
25
- const element = elements[index]
26
- const key = element.props.key || element.type
27
- const oldFiber = oldFibersMap.get(key)
28
-
29
- let newFiber
30
- const sameType = oldFiber && element && element.type === oldFiber.type
31
-
32
- if (sameType) {
33
- newFiber = {
34
- type: oldFiber.type,
35
- props: element.props,
36
- dom: oldFiber.dom,
37
- parent: wipFiber,
38
- alternate: oldFiber,
39
- effectTag: EFFECT_TAGS.UPDATE,
40
- }
41
- oldFibersMap.delete(key)
42
- } else if (element) {
43
- newFiber = {
44
- type: element.type,
45
- props: element.props,
46
- dom: undefined,
47
- parent: wipFiber,
48
- alternate: undefined,
49
- effectTag: EFFECT_TAGS.PLACEMENT,
50
- }
51
- }
52
-
53
- oldFibersMap.forEach((oldFiber) => {
54
- oldFiber.effectTag = EFFECT_TAGS.DELETION
55
- vars.deletions.push(oldFiber)
56
- })
57
-
58
- if (index === 0) {
59
- wipFiber.child = newFiber
60
- } else if (prevSibling) {
61
- prevSibling.sibling = newFiber
62
- }
63
-
64
- prevSibling = newFiber
65
- index++
66
- }
67
- }
68
-
69
- export { reconcileChildren }
package/src/lib/render.js DELETED
@@ -1,45 +0,0 @@
1
- import { vars } from '../utils/index'
2
-
3
- const clearContainer = (container) => {
4
- while (container.firstChild) {
5
- container.removeChild(container.firstChild)
6
- }
7
- }
8
-
9
- /**
10
- * Renders an element into a container using a work-in-progress (WIP) root.
11
- * @function render
12
- * @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.
13
- * @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.
14
- * @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.
15
- * It also clears any scheduled deletions and establishes the next unit of work for incremental rendering.
16
- */
17
- const render = (element, container) => {
18
- vars.wipRoot = {
19
- dom: vars.containerRoot || container,
20
- props: {
21
- children: [element],
22
- },
23
- alternate: vars.currentRoot,
24
- }
25
-
26
- vars.deletions = []
27
- vars.nextUnitOfWork = vars.wipRoot
28
- }
29
-
30
- /**
31
- * Initializes the application by creating a reference to a DOM element with the specified ID and rendering the main component.
32
- * @function init
33
- * @param {Object} MainElement - The main component to render, typically the root component of the application.
34
- * @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.
35
- * @example
36
- * Ryunix.init(App, "__ryunix"); // Initializes and renders the App component into the <div id="__ryunix"></div> element.
37
- * @description This function retrieves the container element by its ID and invokes the `render` function to render the main component into it.
38
- */
39
- const init = (MainElement, root = '__ryunix') => {
40
- vars.containerRoot = document.getElementById(root)
41
-
42
- render(MainElement, vars.containerRoot)
43
- }
44
-
45
- export { render, init }
@@ -1,61 +0,0 @@
1
- import { commitRoot } from './commits'
2
- import { updateFunctionComponent, updateHostComponent } from './components'
3
- import { vars } from '../utils/index'
4
-
5
- /**
6
- * This function uses requestIdleCallback to perform work on a fiber tree until it is complete or the
7
- * browser needs to yield to other tasks.
8
- * @param deadline - The `deadline` parameter is an object that represents the amount of time the
9
- * browser has to perform work before it needs to handle other tasks. It has a `timeRemaining()` method
10
- * that returns the amount of time remaining before the deadline is reached. The `shouldYield` variable
11
- * is used to determine
12
- */
13
- const workLoop = (deadline) => {
14
- let shouldYield = false
15
- while (vars.nextUnitOfWork && !shouldYield) {
16
- vars.nextUnitOfWork = performUnitOfWork(vars.nextUnitOfWork)
17
- shouldYield = deadline.timeRemaining() < 1
18
- }
19
-
20
- if (!vars.nextUnitOfWork && vars.wipRoot) {
21
- commitRoot()
22
- }
23
-
24
- requestIdleCallback(workLoop)
25
- }
26
-
27
- requestIdleCallback(workLoop)
28
-
29
- /**
30
- * The function performs a unit of work by updating either a function component or a host component and
31
- * returns the next fiber to be processed.
32
- * @param fiber - A fiber is a unit of work in Ryunix that represents a component and its state. It
33
- * contains information about the component's type, props, and children, as well as pointers to its
34
- * parent, child, and sibling fibers. The `performUnitOfWork` function takes a fiber as a parameter and
35
- * performs work
36
- * @returns The function `performUnitOfWork` returns the next fiber to be processed. If the current
37
- * fiber has a child, it returns the child. Otherwise, it looks for the next sibling of the current
38
- * fiber. If there are no more siblings, it goes up the tree to the parent and looks for the next
39
- * sibling of the parent. The function returns `undefined` if there are no more fibers to process.
40
- */
41
- const performUnitOfWork = (fiber) => {
42
- const isFunctionComponent = fiber.type instanceof Function
43
- if (isFunctionComponent) {
44
- updateFunctionComponent(fiber)
45
- } else {
46
- updateHostComponent(fiber)
47
- }
48
- if (fiber.child) {
49
- return fiber.child
50
- }
51
- let nextFiber = fiber
52
- while (nextFiber) {
53
- if (nextFiber.sibling) {
54
- return nextFiber.sibling
55
- }
56
- nextFiber = nextFiber.parent
57
- }
58
- return undefined
59
- }
60
-
61
- export { performUnitOfWork, workLoop }
package/src/main.js DELETED
@@ -1,15 +0,0 @@
1
- import Ryunix from './lib/index.js'
2
- export {
3
- useStore,
4
- useEffect,
5
- useQuery,
6
- useRef,
7
- useMemo,
8
- useCallback,
9
- useRouter,
10
- Fragment,
11
- } from './lib/index.js'
12
-
13
- window.Ryunix = Ryunix
14
-
15
- export default Ryunix
@@ -1,42 +0,0 @@
1
- const vars = {
2
- containerRoot: undefined,
3
- nextUnitOfWork: undefined,
4
- currentRoot: undefined,
5
- wipRoot: undefined,
6
- deletions: undefined,
7
- wipFiber: undefined,
8
- hookIndex: undefined,
9
- }
10
-
11
- const reg = /[A-Z]/g
12
-
13
- const RYUNIX_TYPES = Object.freeze({
14
- TEXT_ELEMENT: Symbol('text.element'),
15
- Ryunix_ELEMENT: Symbol('ryunix.element'),
16
- RYUNIX_EFFECT: Symbol('ryunix.effect'),
17
- RYUNIX_MEMO: Symbol('ryunix.memo'),
18
- RYUNIX_URL_QUERY: Symbol('ryunix.urlQuery'),
19
- RYUNIX_REF: Symbol('ryunix.ref'),
20
- })
21
-
22
- const STRINGS = Object.freeze({
23
- object: 'object',
24
- function: 'function',
25
- style: 'ryunix-style',
26
- className: 'ryunix-class',
27
- children: 'children',
28
- boolean: 'boolean',
29
- })
30
-
31
- const OLD_STRINGS = Object.freeze({
32
- style: 'style',
33
- className: 'className',
34
- })
35
-
36
- const EFFECT_TAGS = Object.freeze({
37
- PLACEMENT: Symbol(),
38
- UPDATE: Symbol(),
39
- DELETION: Symbol(),
40
- })
41
-
42
- export { vars, reg, RYUNIX_TYPES, EFFECT_TAGS, STRINGS, OLD_STRINGS }