@koniwa/core 0.0.0-stage → 0.2.0
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/LICENSE +21 -0
- package/README.md +216 -2
- package/dist/core/current-component.d.ts +7 -0
- package/dist/core/current-component.js +21 -0
- package/dist/core/dom.d.ts +3 -0
- package/dist/core/dom.js +74 -0
- package/dist/core/instance.d.ts +23 -0
- package/dist/core/instance.js +37 -0
- package/dist/core/placement.d.ts +4 -0
- package/dist/core/placement.js +24 -0
- package/dist/core/reconcile.d.ts +7 -0
- package/dist/core/reconcile.js +101 -0
- package/dist/core/scheduler.d.ts +2 -0
- package/dist/core/scheduler.js +39 -0
- package/dist/hooks.d.ts +5 -0
- package/dist/hooks.js +45 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3 -0
- package/dist/jsx-dev-runtime.d.ts +2 -0
- package/dist/jsx-dev-runtime.js +1 -0
- package/dist/jsx-runtime.d.ts +6 -0
- package/dist/jsx-runtime.js +11 -0
- package/dist/jsx.d.ts +10 -0
- package/dist/jsx.js +1 -0
- package/dist/render.d.ts +3 -0
- package/dist/render.js +16 -0
- package/dist/types.d.ts +12 -0
- package/dist/types.js +1 -0
- package/dist/virtual-node.d.ts +5 -0
- package/dist/virtual-node.js +6 -0
- package/package.json +53 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Trần Thành Phương Đăng
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,217 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="assets/logo.svg" width="112" alt="koniwa logo: a bonsai tree in a small pot">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">koniwa 小庭</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">A tiny JSX renderer that turns JSX straight into real DOM nodes.</p>
|
|
8
|
+
|
|
9
|
+
- **React-style hooks.** `useState`, `useEffect`, `useMemo` and `useCallback`. When state
|
|
10
|
+
changes, only that component re-renders, and the DOM is patched in place, so inputs keep
|
|
11
|
+
their focus.
|
|
12
|
+
- **No dependencies.** About 500 lines of TypeScript.
|
|
13
|
+
- **Works with any JSX compiler** through the automatic runtime (`jsxImportSource`) or the
|
|
14
|
+
classic `createVirtualNode` factory.
|
|
15
|
+
|
|
16
|
+
It is a good fit for mostly static pages (portfolios, landing pages, CVs) where you want to
|
|
17
|
+
write markup as components, with a bit of interactivity, but don't need React. If you know
|
|
18
|
+
React, you already know most of koniwa (see [Coming from React](#coming-from-react)).
|
|
19
|
+
|
|
20
|
+
## The name
|
|
21
|
+
|
|
22
|
+
_Koniwa_ (小庭) means "small garden": the little garden inside a traditional Japanese
|
|
23
|
+
house, the part guests actually see. A small garden is small but curated, and every stone,
|
|
24
|
+
plant and lantern has its place. That is the idea here: a handful of pages built from
|
|
25
|
+
components and laid out with care, for school projects, GitHub pages and personal sites of
|
|
26
|
+
about ten pages or fewer.
|
|
27
|
+
|
|
28
|
+
Koniwa is one part of a bigger house:
|
|
29
|
+
|
|
30
|
+
- [**watari**](https://github.com/dangttp97/watari) (渡り), from _watari-rōka_, the covered
|
|
31
|
+
corridor that connects the rooms. It fetches data and carries it where it is needed.
|
|
32
|
+
- **jubako** (重箱), the stacked lunch boxes kept in the kitchen. It stores things in layers.
|
|
33
|
+
- **koniwa** (小庭), the garden. It puts everything on display.
|
|
34
|
+
|
|
35
|
+
_Jubako keeps things, watari carries them, koniwa shows them._
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install @koniwa/core
|
|
41
|
+
# or
|
|
42
|
+
yarn add @koniwa/core
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Setup
|
|
46
|
+
|
|
47
|
+
### TypeScript
|
|
48
|
+
|
|
49
|
+
```jsonc
|
|
50
|
+
// tsconfig.json
|
|
51
|
+
{
|
|
52
|
+
"compilerOptions": {
|
|
53
|
+
"jsx": "react-jsx",
|
|
54
|
+
"jsxImportSource": "@koniwa/core",
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Vite
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
// vite.config.ts
|
|
63
|
+
import { defineConfig } from "vite";
|
|
64
|
+
|
|
65
|
+
export default defineConfig({
|
|
66
|
+
oxc: {
|
|
67
|
+
jsx: { runtime: "automatic", importSource: "@koniwa/core" },
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
With the automatic runtime the compiler imports what it needs, so components never import
|
|
73
|
+
`createVirtualNode` themselves.
|
|
74
|
+
|
|
75
|
+
## Usage
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
import { mount, useEffect, useState } from "@koniwa/core";
|
|
79
|
+
|
|
80
|
+
const Greeting = ({ name }: { name: string }) => <h1>Hello, {name}!</h1>;
|
|
81
|
+
|
|
82
|
+
const Counter = () => {
|
|
83
|
+
const [count, setCount] = useState(0);
|
|
84
|
+
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
document.title = `Clicked ${count} times`;
|
|
87
|
+
}, [count]);
|
|
88
|
+
|
|
89
|
+
return (
|
|
90
|
+
<button onClick={() => setCount((c) => c + 1)}>
|
|
91
|
+
Clicked {count} times
|
|
92
|
+
</button>
|
|
93
|
+
);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const App = () => (
|
|
97
|
+
<>
|
|
98
|
+
<Greeting name="Ken Musashi" />
|
|
99
|
+
<Counter />
|
|
100
|
+
</>
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
mount(<App />, document.getElementById("root")!);
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Coming from React
|
|
107
|
+
|
|
108
|
+
The parts you write every day work the same way:
|
|
109
|
+
|
|
110
|
+
| React | koniwa |
|
|
111
|
+
| ------------------------------------------------- | -------------------------------------------- |
|
|
112
|
+
| Function components with `props`, `children` | Same |
|
|
113
|
+
| `<>...</>` / `Fragment` | Same |
|
|
114
|
+
| `className`, `htmlFor`, `style={{ ... }}` | Same |
|
|
115
|
+
| `onClick`, `onInput`, `onSubmit`, … | Same names, attached with `addEventListener` |
|
|
116
|
+
| `"jsxImportSource": "react"` | `"jsxImportSource": "@koniwa/core"` |
|
|
117
|
+
| `React.createElement(type, props, ...kids)` | `createVirtualNode(type, props, ...kids)` |
|
|
118
|
+
| `createRoot(root).render(<App />)` | `mount(<App />, root)` |
|
|
119
|
+
| `useState`, `useEffect`, `useMemo`, `useCallback` | Same names and signatures |
|
|
120
|
+
| `key` on list items | Same: keyed items are moved, not recreated |
|
|
121
|
+
| Controlled inputs (`value`, `checked`) | Same |
|
|
122
|
+
|
|
123
|
+
What is different:
|
|
124
|
+
|
|
125
|
+
- **Events are native DOM events**, not React's synthetic events. `onChange` fires on the
|
|
126
|
+
browser's `change` event (when an input loses focus); use `onInput` for every keystroke.
|
|
127
|
+
- **Effects run right after the DOM is updated**, before the browser paints (like React's
|
|
128
|
+
`useLayoutEffect`), not later.
|
|
129
|
+
- **`mount` replaces, it does not patch.** Calling `mount` again throws away the old tree (and
|
|
130
|
+
its state) and builds a new one. Use state to update parts of a page.
|
|
131
|
+
- **Numbers in `style` get no unit.** Write `{ width: "10px" }`, not `{ width: 10 }`.
|
|
132
|
+
- **No class components** and no `dangerouslySetInnerHTML`. `useRef`, `useContext` and
|
|
133
|
+
`useImperativeHandle` are not there yet (see [Roadmap](#roadmap)).
|
|
134
|
+
|
|
135
|
+
## API
|
|
136
|
+
|
|
137
|
+
| Export | Description |
|
|
138
|
+
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
139
|
+
| `render(child, container)` | Builds DOM from `child` and **appends** it to `container`. Accepts a VirtualNode, a string or number, an array, or a component function (`render(App, root)`). |
|
|
140
|
+
| `mount(child, container)` | Removes what was rendered in `container` before (running effect cleanups), clears it, then renders into it. |
|
|
141
|
+
| `useState(initial)` | `[value, setValue]`. `setValue(next)` or `setValue((prev) => next)`; updates in the same tick are batched into one render. |
|
|
142
|
+
| `useEffect(effect, deps?)` | Runs `effect` after the DOM is updated, again when `deps` change (every render without `deps`). Return a function to clean up. |
|
|
143
|
+
| `useMemo(factory, deps)` | Returns the cached result of `factory` until `deps` change. |
|
|
144
|
+
| `useCallback(callback, deps)` | Returns the same function until `deps` change. |
|
|
145
|
+
| `createVirtualNode(type, props, ...children)` | Classic JSX factory. Returns a VirtualNode `{ type, props, children }`. |
|
|
146
|
+
| `Fragment` | `<>...</>`: renders children without a wrapper element. |
|
|
147
|
+
| `@koniwa/core/jsx-runtime` | Automatic runtime (`jsx`, `jsxs`, `Fragment`) used by the compiler. |
|
|
148
|
+
|
|
149
|
+
Types: `Child`, `Component`, `Props`, `VirtualNode`, `JSX`, `Dispatch`, `SetStateAction`,
|
|
150
|
+
`DependencyList`, `EffectCallback`.
|
|
151
|
+
|
|
152
|
+
### How props are applied
|
|
153
|
+
|
|
154
|
+
| Prop | Result |
|
|
155
|
+
| ----------------------------------- | ----------------------------------- |
|
|
156
|
+
| `className` / `class` | `class` attribute |
|
|
157
|
+
| `htmlFor` | `for` attribute |
|
|
158
|
+
| `onClick`, `onInput`, … (functions) | `addEventListener("click", …)` |
|
|
159
|
+
| `style={{ color: "red" }}` | assigned to `element.style` |
|
|
160
|
+
| `value`, `checked`, `selected` | set as DOM properties |
|
|
161
|
+
| `true` | empty attribute (`hidden=""`) |
|
|
162
|
+
| `false`, `null`, `undefined` | attribute is not set (or removed) |
|
|
163
|
+
| `key` | used to match list items |
|
|
164
|
+
| anything else | `setAttribute(name, String(value))` |
|
|
165
|
+
|
|
166
|
+
`<svg>` and its children are created in the SVG namespace; children of `<foreignObject>` go back
|
|
167
|
+
to HTML.
|
|
168
|
+
|
|
169
|
+
## Limitations
|
|
170
|
+
|
|
171
|
+
- **Simple diffing.** Children are matched by position, or by `key` when given. Without keys,
|
|
172
|
+
inserting at the top of a list re-renders every item below it.
|
|
173
|
+
- **`render` appends.** Calling `render` again on the same container adds a second tree. Use
|
|
174
|
+
`mount` to replace the content.
|
|
175
|
+
- **No context or refs** yet (see [Roadmap](#roadmap)).
|
|
176
|
+
- **Loose attribute types.** Intrinsic elements accept any attribute; there is no per-element
|
|
177
|
+
type checking like `@types/react` provides.
|
|
178
|
+
- **Custom CSS properties in `style` objects** (`{ "--size": "10px" }`) are not applied; set
|
|
179
|
+
them with CSS classes instead.
|
|
180
|
+
|
|
181
|
+
## Roadmap
|
|
182
|
+
|
|
183
|
+
React-style hooks, with the same names and call signatures as React, so code and habits
|
|
184
|
+
carry over:
|
|
185
|
+
|
|
186
|
+
| Hook | What it is for | Status |
|
|
187
|
+
| --------------------- | ----------------------------------------------------------- | --------- |
|
|
188
|
+
| `useState` | Local state; changing it re-renders the component | Available |
|
|
189
|
+
| `useEffect` | Run code after render, with cleanup | Available |
|
|
190
|
+
| `useMemo` | Cache a computed value until its dependencies change | Available |
|
|
191
|
+
| `useCallback` | Keep the same function between renders | Available |
|
|
192
|
+
| `useRef` | Hold a DOM element or a value across renders | Planned |
|
|
193
|
+
| `useContext` | Read a value from a `createContext` provider up the tree | Planned |
|
|
194
|
+
| `useImperativeHandle` | Expose methods from a component to its parent through `ref` | Planned |
|
|
195
|
+
|
|
196
|
+
Planned hooks may change while they are built.
|
|
197
|
+
|
|
198
|
+
Out of scope, on purpose: server-side rendering, client-side routing (SPA), server
|
|
199
|
+
components, Suspense and concurrent rendering. koniwa stays a small tool for static sites of
|
|
200
|
+
about ten pages-ish.
|
|
201
|
+
|
|
202
|
+
## Development
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
yarn install
|
|
206
|
+
yarn test # Vitest + happy-dom
|
|
207
|
+
yarn typecheck
|
|
208
|
+
yarn build # emits dist/
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
On Windows, run the tests from a path with an uppercase drive letter (`C:\...`). VS Code
|
|
212
|
+
terminals can start in `c:\...`, which makes Vitest load itself twice and fail with
|
|
213
|
+
`Cannot read properties of undefined (reading 'config')`.
|
|
214
|
+
|
|
215
|
+
## License
|
|
216
|
+
|
|
217
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
let current = null;
|
|
2
|
+
export const callComponent = (instance) => {
|
|
3
|
+
const { type, props, children } = instance.item;
|
|
4
|
+
const previous = current;
|
|
5
|
+
current = { instance, hookIndex: 0 };
|
|
6
|
+
try {
|
|
7
|
+
return type({ ...props, children });
|
|
8
|
+
}
|
|
9
|
+
finally {
|
|
10
|
+
current = previous;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
export const useHookSlot = (create) => {
|
|
14
|
+
if (!current) {
|
|
15
|
+
throw new Error("Hooks can only be called inside a component.");
|
|
16
|
+
}
|
|
17
|
+
const { instance } = current;
|
|
18
|
+
const index = current.hookIndex++;
|
|
19
|
+
instance.hooks[index] ??= create();
|
|
20
|
+
return { hook: instance.hooks[index], instance };
|
|
21
|
+
};
|
package/dist/core/dom.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
|
|
2
|
+
// Set as DOM properties, after the other props, so `type` and <option>s exist first.
|
|
3
|
+
const DOM_PROPERTIES = ["value", "checked", "selected"];
|
|
4
|
+
export const createDomElement = (tag, isSvg) => isSvg
|
|
5
|
+
? document.createElementNS(SVG_NAMESPACE, tag)
|
|
6
|
+
: document.createElement(tag);
|
|
7
|
+
export const updateProps = (element, oldProps, newProps) => {
|
|
8
|
+
const names = new Set([...Object.keys(oldProps), ...Object.keys(newProps)]);
|
|
9
|
+
for (const name of names) {
|
|
10
|
+
if (!DOM_PROPERTIES.includes(name)) {
|
|
11
|
+
setProp(element, name, oldProps[name], newProps[name]);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
for (const name of DOM_PROPERTIES) {
|
|
15
|
+
if (names.has(name))
|
|
16
|
+
setDomProperty(element, name, newProps[name]);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const setProp = (element, name, oldValue, value) => {
|
|
20
|
+
if (name === "key" || name === "children" || oldValue === value)
|
|
21
|
+
return;
|
|
22
|
+
const isEvent = name.startsWith("on") &&
|
|
23
|
+
(typeof value === "function" || typeof oldValue === "function");
|
|
24
|
+
if (isEvent) {
|
|
25
|
+
const eventName = name.slice(2).toLowerCase();
|
|
26
|
+
if (typeof oldValue === "function") {
|
|
27
|
+
element.removeEventListener(eventName, oldValue);
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "function") {
|
|
30
|
+
element.addEventListener(eventName, value);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else if (name === "style" && typeof value === "object" && value) {
|
|
34
|
+
updateStyle(element, oldValue, value);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
setAttribute(element, toAttributeName(name), value);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const updateStyle = (element, oldValue, value) => {
|
|
41
|
+
if (typeof oldValue === "object" && oldValue) {
|
|
42
|
+
for (const key of Object.keys(oldValue)) {
|
|
43
|
+
if (!(key in value))
|
|
44
|
+
element.style.setProperty(toCssName(key), "");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
Object.assign(element.style, value);
|
|
48
|
+
};
|
|
49
|
+
const setDomProperty = (element, name, value) => {
|
|
50
|
+
if (!(name in element)) {
|
|
51
|
+
setAttribute(element, name, value);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const target = element;
|
|
55
|
+
const next = value ?? (name === "value" ? "" : false);
|
|
56
|
+
if (target[name] !== next)
|
|
57
|
+
target[name] = next;
|
|
58
|
+
};
|
|
59
|
+
const setAttribute = (element, name, value) => {
|
|
60
|
+
if (value == null || value === false) {
|
|
61
|
+
element.removeAttribute(name);
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
element.setAttribute(name, value === true ? "" : String(value));
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const toAttributeName = (propName) => {
|
|
68
|
+
if (propName === "className")
|
|
69
|
+
return "class";
|
|
70
|
+
if (propName === "htmlFor")
|
|
71
|
+
return "for";
|
|
72
|
+
return propName;
|
|
73
|
+
};
|
|
74
|
+
const toCssName = (key) => key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Child, VirtualNode } from "../types.js";
|
|
2
|
+
export type RenderItem = VirtualNode | string | null;
|
|
3
|
+
export type ElementItem = VirtualNode & {
|
|
4
|
+
type: string;
|
|
5
|
+
};
|
|
6
|
+
export interface Instance {
|
|
7
|
+
item: RenderItem;
|
|
8
|
+
parent: Instance | null;
|
|
9
|
+
parentDom: Node;
|
|
10
|
+
insideSvg: boolean;
|
|
11
|
+
domNode: Node | null;
|
|
12
|
+
children: Instance[];
|
|
13
|
+
hooks: unknown[];
|
|
14
|
+
pendingEffects: Array<() => void>;
|
|
15
|
+
needsRender: boolean;
|
|
16
|
+
unmounted: boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare const createInstance: (item: RenderItem, parent: Instance | null, parentDom: Node, insideSvg: boolean) => Instance;
|
|
19
|
+
export declare const toRenderItems: (child: Child) => RenderItem[];
|
|
20
|
+
export declare const isElementItem: (item: RenderItem) => item is ElementItem;
|
|
21
|
+
export declare const keyOf: (item: RenderItem) => unknown;
|
|
22
|
+
export declare const canReuse: (old: RenderItem, item: RenderItem) => boolean;
|
|
23
|
+
export declare const childrenInsideSvg: (instance: Instance) => boolean;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const createInstance = (item, parent, parentDom, insideSvg) => ({
|
|
2
|
+
item,
|
|
3
|
+
parent,
|
|
4
|
+
parentDom,
|
|
5
|
+
insideSvg,
|
|
6
|
+
domNode: null,
|
|
7
|
+
children: [],
|
|
8
|
+
hooks: [],
|
|
9
|
+
pendingEffects: [],
|
|
10
|
+
needsRender: false,
|
|
11
|
+
unmounted: false,
|
|
12
|
+
});
|
|
13
|
+
export const toRenderItems = (child) => {
|
|
14
|
+
if (Array.isArray(child))
|
|
15
|
+
return child.flatMap(toRenderItems);
|
|
16
|
+
if (child == null || typeof child === "boolean")
|
|
17
|
+
return [null];
|
|
18
|
+
if (typeof child === "object")
|
|
19
|
+
return [child];
|
|
20
|
+
return [String(child)];
|
|
21
|
+
};
|
|
22
|
+
export const isElementItem = (item) => typeof item === "object" && item !== null && typeof item.type === "string";
|
|
23
|
+
export const keyOf = (item) => typeof item === "object" && item !== null ? item.props.key : undefined;
|
|
24
|
+
export const canReuse = (old, item) => {
|
|
25
|
+
if (old === null || item === null)
|
|
26
|
+
return old === item;
|
|
27
|
+
if (typeof old === "string" || typeof item === "string") {
|
|
28
|
+
return typeof old === typeof item;
|
|
29
|
+
}
|
|
30
|
+
return old.type === item.type && old.props.key === item.props.key;
|
|
31
|
+
};
|
|
32
|
+
export const childrenInsideSvg = (instance) => {
|
|
33
|
+
if (!isElementItem(instance.item))
|
|
34
|
+
return instance.insideSvg;
|
|
35
|
+
const tag = instance.item.type;
|
|
36
|
+
return (instance.insideSvg || tag === "svg") && tag !== "foreignObject";
|
|
37
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Instance } from "./instance.js";
|
|
2
|
+
export declare const domNodesOf: (instance: Instance) => Node[];
|
|
3
|
+
export declare const placeDomNodes: (parentDom: Node, instances: Instance[], before: Node | null) => void;
|
|
4
|
+
export declare const nextDomSibling: (instance: Instance) => Node | null;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export const domNodesOf = (instance) => instance.domNode ? [instance.domNode] : instance.children.flatMap(domNodesOf);
|
|
2
|
+
export const placeDomNodes = (parentDom, instances, before) => {
|
|
3
|
+
const nodes = instances.flatMap(domNodesOf);
|
|
4
|
+
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
5
|
+
const node = nodes[i];
|
|
6
|
+
if (node.parentNode !== parentDom || node.nextSibling !== before) {
|
|
7
|
+
parentDom.insertBefore(node, before);
|
|
8
|
+
}
|
|
9
|
+
before = node;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
export const nextDomSibling = (instance) => {
|
|
13
|
+
for (let child = instance; child.parent; child = child.parent) {
|
|
14
|
+
const siblings = child.parent.children;
|
|
15
|
+
for (const sibling of siblings.slice(siblings.indexOf(child) + 1)) {
|
|
16
|
+
const [first] = domNodesOf(sibling);
|
|
17
|
+
if (first)
|
|
18
|
+
return first;
|
|
19
|
+
}
|
|
20
|
+
if (child.parent.domNode)
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Child } from "../types.js";
|
|
2
|
+
import { type Instance } from "./instance.js";
|
|
3
|
+
export declare const createRoot: (container: Node) => Instance;
|
|
4
|
+
export declare const renderRoot: (root: Instance, child: Child) => void;
|
|
5
|
+
export declare const rerenderComponent: (instance: Instance) => void;
|
|
6
|
+
export declare const runQueuedEffects: () => void;
|
|
7
|
+
export declare const unmount: (instance: Instance) => void;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { callComponent } from "./current-component.js";
|
|
2
|
+
import { createDomElement, updateProps } from "./dom.js";
|
|
3
|
+
import { canReuse, childrenInsideSvg, createInstance, isElementItem, keyOf, toRenderItems, } from "./instance.js";
|
|
4
|
+
import { domNodesOf, nextDomSibling, placeDomNodes } from "./placement.js";
|
|
5
|
+
let queuedEffects = [];
|
|
6
|
+
export const createRoot = (container) => createInstance(null, null, container, false);
|
|
7
|
+
export const renderRoot = (root, child) => {
|
|
8
|
+
root.children = reconcileChildren(root, toRenderItems(child));
|
|
9
|
+
placeDomNodes(root.parentDom, root.children, null);
|
|
10
|
+
runQueuedEffects();
|
|
11
|
+
};
|
|
12
|
+
export const rerenderComponent = (instance) => {
|
|
13
|
+
const before = nextDomSibling(instance) ?? domNodesOf(instance).at(-1)?.nextSibling;
|
|
14
|
+
renderComponent(instance);
|
|
15
|
+
placeDomNodes(instance.parentDom, [instance], before ?? null);
|
|
16
|
+
};
|
|
17
|
+
export const runQueuedEffects = () => {
|
|
18
|
+
const effects = queuedEffects;
|
|
19
|
+
queuedEffects = [];
|
|
20
|
+
effects.forEach((run) => run());
|
|
21
|
+
};
|
|
22
|
+
export const unmount = (instance) => {
|
|
23
|
+
instance.unmounted = true;
|
|
24
|
+
instance.children.forEach(unmount);
|
|
25
|
+
for (const hook of instance.hooks) {
|
|
26
|
+
hook.cleanup?.();
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const reconcileChildren = (parent, items) => {
|
|
30
|
+
const oldChildren = parent.children;
|
|
31
|
+
const oldByKey = new Map();
|
|
32
|
+
for (const old of oldChildren) {
|
|
33
|
+
const key = keyOf(old.item);
|
|
34
|
+
if (key != null)
|
|
35
|
+
oldByKey.set(key, old);
|
|
36
|
+
}
|
|
37
|
+
const reused = new Set();
|
|
38
|
+
const children = items.map((item, index) => {
|
|
39
|
+
const key = keyOf(item);
|
|
40
|
+
const old = key != null ? oldByKey.get(key) : oldChildren[index];
|
|
41
|
+
if (old && !reused.has(old) && canReuse(old.item, item)) {
|
|
42
|
+
reused.add(old);
|
|
43
|
+
updateChild(old, item);
|
|
44
|
+
return old;
|
|
45
|
+
}
|
|
46
|
+
return mountChild(item, parent);
|
|
47
|
+
});
|
|
48
|
+
for (const old of oldChildren) {
|
|
49
|
+
if (!reused.has(old))
|
|
50
|
+
removeChild(old);
|
|
51
|
+
}
|
|
52
|
+
return children;
|
|
53
|
+
};
|
|
54
|
+
const mountChild = (item, parent) => {
|
|
55
|
+
const instance = createInstance(item, parent, parent.domNode ?? parent.parentDom, childrenInsideSvg(parent));
|
|
56
|
+
if (typeof item === "string") {
|
|
57
|
+
instance.domNode = document.createTextNode(item);
|
|
58
|
+
}
|
|
59
|
+
else if (isElementItem(item)) {
|
|
60
|
+
const isSvg = instance.insideSvg || item.type === "svg";
|
|
61
|
+
instance.domNode = createDomElement(item.type, isSvg);
|
|
62
|
+
renderElement(instance, {});
|
|
63
|
+
}
|
|
64
|
+
else if (item) {
|
|
65
|
+
renderComponent(instance);
|
|
66
|
+
}
|
|
67
|
+
return instance;
|
|
68
|
+
};
|
|
69
|
+
const updateChild = (instance, item) => {
|
|
70
|
+
const old = instance.item;
|
|
71
|
+
instance.item = item;
|
|
72
|
+
if (typeof item === "string") {
|
|
73
|
+
if (item !== old)
|
|
74
|
+
instance.domNode.data = item;
|
|
75
|
+
}
|
|
76
|
+
else if (isElementItem(item)) {
|
|
77
|
+
renderElement(instance, old.props);
|
|
78
|
+
}
|
|
79
|
+
else if (item) {
|
|
80
|
+
renderComponent(instance);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const removeChild = (instance) => {
|
|
84
|
+
for (const node of domNodesOf(instance))
|
|
85
|
+
node.remove();
|
|
86
|
+
unmount(instance);
|
|
87
|
+
};
|
|
88
|
+
const renderElement = (instance, oldProps) => {
|
|
89
|
+
const { props, children } = instance.item;
|
|
90
|
+
const element = instance.domNode;
|
|
91
|
+
instance.children = reconcileChildren(instance, toRenderItems(children));
|
|
92
|
+
placeDomNodes(element, instance.children, null);
|
|
93
|
+
updateProps(element, oldProps, props);
|
|
94
|
+
};
|
|
95
|
+
const renderComponent = (instance) => {
|
|
96
|
+
instance.needsRender = false;
|
|
97
|
+
const output = callComponent(instance);
|
|
98
|
+
instance.children = reconcileChildren(instance, toRenderItems(output));
|
|
99
|
+
queuedEffects.push(...instance.pendingEffects);
|
|
100
|
+
instance.pendingEffects = [];
|
|
101
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { rerenderComponent, runQueuedEffects } from "./reconcile.js";
|
|
2
|
+
const MAX_RENDERS_PER_FLUSH = 1000;
|
|
3
|
+
const waiting = new Set();
|
|
4
|
+
let flushScheduled = false;
|
|
5
|
+
export const scheduleRender = (instance) => {
|
|
6
|
+
if (instance.unmounted)
|
|
7
|
+
return;
|
|
8
|
+
instance.needsRender = true;
|
|
9
|
+
waiting.add(instance);
|
|
10
|
+
if (!flushScheduled) {
|
|
11
|
+
flushScheduled = true;
|
|
12
|
+
queueMicrotask(flush);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
const flush = () => {
|
|
16
|
+
flushScheduled = false;
|
|
17
|
+
for (let renders = 0; waiting.size > 0; renders++) {
|
|
18
|
+
if (renders === MAX_RENDERS_PER_FLUSH) {
|
|
19
|
+
waiting.clear();
|
|
20
|
+
throw new Error("Too many re-renders. A component keeps setting state while rendering.");
|
|
21
|
+
}
|
|
22
|
+
const instance = takeShallowest(waiting);
|
|
23
|
+
if (instance.needsRender && !instance.unmounted) {
|
|
24
|
+
rerenderComponent(instance);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
runQueuedEffects();
|
|
28
|
+
};
|
|
29
|
+
const takeShallowest = (instances) => {
|
|
30
|
+
const shallowest = [...instances].reduce((a, b) => depthOf(b) < depthOf(a) ? b : a);
|
|
31
|
+
instances.delete(shallowest);
|
|
32
|
+
return shallowest;
|
|
33
|
+
};
|
|
34
|
+
const depthOf = (instance) => {
|
|
35
|
+
let depth = 0;
|
|
36
|
+
for (let p = instance.parent; p; p = p.parent)
|
|
37
|
+
depth++;
|
|
38
|
+
return depth;
|
|
39
|
+
};
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { DependencyList, Dispatch, EffectCallback, SetStateAction } from "./types.js";
|
|
2
|
+
export declare const useState: <S>(initialState: S | (() => S)) => [S, Dispatch<SetStateAction<S>>];
|
|
3
|
+
export declare const useEffect: (effect: EffectCallback, deps?: DependencyList) => void;
|
|
4
|
+
export declare const useMemo: <T>(factory: () => T, deps: DependencyList) => T;
|
|
5
|
+
export declare const useCallback: <T extends (...args: any[]) => unknown>(callback: T, deps: DependencyList) => T;
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { useHookSlot } from "./core/current-component.js";
|
|
2
|
+
import { scheduleRender } from "./core/scheduler.js";
|
|
3
|
+
export const useState = (initialState) => {
|
|
4
|
+
const { hook, instance } = useHookSlot(() => ({
|
|
5
|
+
value: typeof initialState === "function"
|
|
6
|
+
? initialState()
|
|
7
|
+
: initialState,
|
|
8
|
+
}));
|
|
9
|
+
const setValue = (hook.setValue ??= (action) => {
|
|
10
|
+
const next = typeof action === "function"
|
|
11
|
+
? action(hook.value)
|
|
12
|
+
: action;
|
|
13
|
+
if (Object.is(next, hook.value))
|
|
14
|
+
return;
|
|
15
|
+
hook.value = next;
|
|
16
|
+
scheduleRender(instance);
|
|
17
|
+
});
|
|
18
|
+
return [hook.value, setValue];
|
|
19
|
+
};
|
|
20
|
+
export const useEffect = (effect, deps) => {
|
|
21
|
+
const { hook, instance } = useHookSlot(() => ({}));
|
|
22
|
+
if (!depsChanged(hook.deps, deps))
|
|
23
|
+
return;
|
|
24
|
+
hook.deps = deps;
|
|
25
|
+
instance.pendingEffects.push(() => {
|
|
26
|
+
if (instance.unmounted)
|
|
27
|
+
return;
|
|
28
|
+
hook.cleanup?.();
|
|
29
|
+
const cleanup = effect();
|
|
30
|
+
hook.cleanup = typeof cleanup === "function" ? cleanup : undefined;
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
export const useMemo = (factory, deps) => {
|
|
34
|
+
const { hook } = useHookSlot(() => ({}));
|
|
35
|
+
if (depsChanged(hook.deps, deps)) {
|
|
36
|
+
hook.value = factory();
|
|
37
|
+
hook.deps = deps;
|
|
38
|
+
}
|
|
39
|
+
return hook.value;
|
|
40
|
+
};
|
|
41
|
+
export const useCallback = (callback, deps) => useMemo(() => callback, deps);
|
|
42
|
+
const depsChanged = (previous, next) => !previous ||
|
|
43
|
+
!next ||
|
|
44
|
+
previous.length !== next.length ||
|
|
45
|
+
previous.some((dep, i) => !Object.is(dep, next[i]));
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { useCallback, useEffect, useMemo, useState } from "./hooks.js";
|
|
2
|
+
export type { JSX } from "./jsx.js";
|
|
3
|
+
export { mount, render } from "./render.js";
|
|
4
|
+
export type { Child, Component, DependencyList, Dispatch, EffectCallback, Props, SetStateAction, VirtualNode, } from "./types.js";
|
|
5
|
+
export { Fragment, createVirtualNode } from "./virtual-node.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { Fragment, jsx as jsxDEV } from "./jsx-runtime.js";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Component, Props, VirtualNode } from "./types.js";
|
|
2
|
+
import { Fragment } from "./virtual-node.js";
|
|
3
|
+
export { Fragment };
|
|
4
|
+
export type { JSX } from "./jsx.js";
|
|
5
|
+
export declare const jsx: (type: string | Component, props: Props, key?: unknown) => VirtualNode;
|
|
6
|
+
export declare const jsxs: (type: string | Component, props: Props, key?: unknown) => VirtualNode;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Fragment, createVirtualNode } from "./virtual-node.js";
|
|
2
|
+
export { Fragment };
|
|
3
|
+
export const jsx = (type, props, key) => {
|
|
4
|
+
const { children, ...rest } = props;
|
|
5
|
+
if (key !== undefined)
|
|
6
|
+
rest.key = key;
|
|
7
|
+
return children === undefined
|
|
8
|
+
? createVirtualNode(type, rest)
|
|
9
|
+
: createVirtualNode(type, rest, children);
|
|
10
|
+
};
|
|
11
|
+
export const jsxs = jsx;
|
package/dist/jsx.d.ts
ADDED
package/dist/jsx.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/render.d.ts
ADDED
package/dist/render.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRoot, renderRoot, unmount } from "./core/reconcile.js";
|
|
2
|
+
import { createVirtualNode } from "./virtual-node.js";
|
|
3
|
+
const rootsByContainer = new WeakMap();
|
|
4
|
+
export const render = (child, container) => {
|
|
5
|
+
const root = createRoot(container);
|
|
6
|
+
const roots = rootsByContainer.get(container) ?? [];
|
|
7
|
+
rootsByContainer.set(container, [...roots, root]);
|
|
8
|
+
const node = typeof child === "function" ? createVirtualNode(child, null) : child;
|
|
9
|
+
renderRoot(root, node);
|
|
10
|
+
};
|
|
11
|
+
export const mount = (child, container) => {
|
|
12
|
+
rootsByContainer.get(container)?.forEach(unmount);
|
|
13
|
+
rootsByContainer.delete(container);
|
|
14
|
+
container.replaceChildren();
|
|
15
|
+
render(child, container);
|
|
16
|
+
};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type Child = VirtualNode | string | number | boolean | null | undefined | Child[];
|
|
2
|
+
export type Props = Record<string, unknown>;
|
|
3
|
+
export type Component<P = any> = (props: P) => Child;
|
|
4
|
+
export interface VirtualNode {
|
|
5
|
+
type: string | Component;
|
|
6
|
+
props: Props;
|
|
7
|
+
children: Child[];
|
|
8
|
+
}
|
|
9
|
+
export type SetStateAction<S> = S | ((previous: S) => S);
|
|
10
|
+
export type Dispatch<A> = (action: A) => void;
|
|
11
|
+
export type DependencyList = readonly unknown[];
|
|
12
|
+
export type EffectCallback = () => void | (() => void);
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Child, Component, Props, VirtualNode } from "./types.js";
|
|
2
|
+
export declare const createVirtualNode: (type: string | Component, props: Props | null, ...children: Child[]) => VirtualNode;
|
|
3
|
+
export declare const Fragment: (props: {
|
|
4
|
+
children?: Child[];
|
|
5
|
+
}) => Child;
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@koniwa/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "A tiny JSX renderer for small static sites: real DOM, React-style hooks, no dependencies.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"jsx",
|
|
7
|
+
"dom",
|
|
8
|
+
"renderer",
|
|
9
|
+
"jsx-runtime",
|
|
10
|
+
"vite"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "Trần Thành Phương Đăng",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/dangttp97/koniwa.git"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./jsx-runtime": {
|
|
29
|
+
"types": "./dist/jsx-runtime.d.ts",
|
|
30
|
+
"default": "./dist/jsx-runtime.js"
|
|
31
|
+
},
|
|
32
|
+
"./jsx-dev-runtime": {
|
|
33
|
+
"types": "./dist/jsx-dev-runtime.d.ts",
|
|
34
|
+
"default": "./dist/jsx-dev-runtime.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"packageManager": "yarn@4.18.0",
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"test:watch": "vitest",
|
|
44
|
+
"format": "prettier --write .",
|
|
45
|
+
"format:check": "prettier --check .",
|
|
46
|
+
"prepack": "yarn build"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"happy-dom": "^21.0.4",
|
|
50
|
+
"prettier": "^3.10.1",
|
|
51
|
+
"typescript": "~6.0.3",
|
|
52
|
+
"vite": "^8.3.8",
|
|
53
|
+
"vitest": "^5.1.0"
|
|
54
|
+
}
|
|
55
|
+
}
|