@koniwa/core 0.1.0 → 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/README.md CHANGED
@@ -6,15 +6,16 @@
6
6
 
7
7
  <p align="center">A tiny JSX renderer that turns JSX straight into real DOM nodes.</p>
8
8
 
9
- - **No virtual DOM diffing, no state, no hooks.** Components are plain functions that run once.
10
- - **No dependencies.** About 100 lines of TypeScript.
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.
11
13
  - **Works with any JSX compiler** through the automatic runtime (`jsxImportSource`) or the
12
14
  classic `createVirtualNode` factory.
13
15
 
14
16
  It is a good fit for mostly static pages (portfolios, landing pages, CVs) where you want to
15
- write markup as components but don't need React. If you know React, you already know most of
16
- koniwa (see [Coming from React](#coming-from-react)). React-style hooks are planned (see
17
- [Roadmap](#roadmap)); until they land, use React or Preact if you need state or re-rendering.
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)).
18
19
 
19
20
  ## The name
20
21
 
@@ -74,56 +75,79 @@ With the automatic runtime the compiler imports what it needs, so components nev
74
75
  ## Usage
75
76
 
76
77
  ```tsx
77
- import { render } from "@koniwa/core";
78
+ import { mount, useEffect, useState } from "@koniwa/core";
78
79
 
79
80
  const Greeting = ({ name }: { name: string }) => <h1>Hello, {name}!</h1>;
80
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
+
81
96
  const App = () => (
82
97
  <>
83
98
  <Greeting name="Ken Musashi" />
84
- <button onClick={() => alert("Hi")}>Say hi</button>
99
+ <Counter />
85
100
  </>
86
101
  );
87
102
 
88
- render(<App />, document.getElementById("root")!);
103
+ mount(<App />, document.getElementById("root")!);
89
104
  ```
90
105
 
91
106
  ## Coming from React
92
107
 
93
108
  The parts you write every day work the same way:
94
109
 
95
- | React | koniwa |
96
- | -------------------------------------------- | -------------------------------------------- |
97
- | Function components with `props`, `children` | Same |
98
- | `<>...</>` / `Fragment` | Same |
99
- | `className`, `htmlFor`, `style={{ ... }}` | Same |
100
- | `onClick`, `onInput`, `onSubmit`, … | Same names, attached with `addEventListener` |
101
- | `"jsxImportSource": "react"` | `"jsxImportSource": "@koniwa/core"` |
102
- | `React.createElement(type, props, ...kids)` | `createVirtualNode(type, props, ...kids)` |
103
- | `createRoot(root).render(<App />)` | `mount(<App />, root)` |
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 |
104
122
 
105
123
  What is different:
106
124
 
107
- - **Components run once.** Nothing re-renders; to update the page, call `mount` again or change
108
- the DOM in an event handler.
109
125
  - **Events are native DOM events**, not React's synthetic events. `onChange` fires on the
110
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.
111
131
  - **Numbers in `style` get no unit.** Write `{ width: "10px" }`, not `{ width: 10 }`.
112
- - **Every prop is an attribute.** `value` and `checked` set the initial HTML attribute, and
113
- `dangerouslySetInnerHTML` is not supported.
114
- - **No class components**, no `key`-based reordering (`key` is ignored), no hooks yet.
132
+ - **No class components** and no `dangerouslySetInnerHTML`. `useRef`, `useContext` and
133
+ `useImperativeHandle` are not there yet (see [Roadmap](#roadmap)).
115
134
 
116
135
  ## API
117
136
 
118
137
  | Export | Description |
119
138
  | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
120
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)`). |
121
- | `mount(child, container)` | Clears `container`, then renders into it. |
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. |
122
145
  | `createVirtualNode(type, props, ...children)` | Classic JSX factory. Returns a VirtualNode `{ type, props, children }`. |
123
146
  | `Fragment` | `<>...</>`: renders children without a wrapper element. |
124
147
  | `@koniwa/core/jsx-runtime` | Automatic runtime (`jsx`, `jsxs`, `Fragment`) used by the compiler. |
125
148
 
126
- Types: `Child`, `Component`, `Props`, `VirtualNode`, `JSX`.
149
+ Types: `Child`, `Component`, `Props`, `VirtualNode`, `JSX`, `Dispatch`, `SetStateAction`,
150
+ `DependencyList`, `EffectCallback`.
127
151
 
128
152
  ### How props are applied
129
153
 
@@ -133,9 +157,10 @@ Types: `Child`, `Component`, `Props`, `VirtualNode`, `JSX`.
133
157
  | `htmlFor` | `for` attribute |
134
158
  | `onClick`, `onInput`, … (functions) | `addEventListener("click", …)` |
135
159
  | `style={{ color: "red" }}` | assigned to `element.style` |
160
+ | `value`, `checked`, `selected` | set as DOM properties |
136
161
  | `true` | empty attribute (`hidden=""`) |
137
- | `false`, `null`, `undefined` | attribute is not set |
138
- | `key` | ignored |
162
+ | `false`, `null`, `undefined` | attribute is not set (or removed) |
163
+ | `key` | used to match list items |
139
164
  | anything else | `setAttribute(name, String(value))` |
140
165
 
141
166
  `<svg>` and its children are created in the SVG namespace; children of `<foreignObject>` go back
@@ -143,10 +168,11 @@ to HTML.
143
168
 
144
169
  ## Limitations
145
170
 
146
- - **Render once.** There is no diffing: calling `render` again appends a second copy. Use
147
- `mount` to replace the content, or update the DOM directly (for example through `data-*`
148
- attributes that your CSS reacts to).
149
- - **No state, effects, context or refs** yet (see [Roadmap](#roadmap)).
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)).
150
176
  - **Loose attribute types.** Intrinsic elements accept any attribute; there is no per-element
151
177
  type checking like `@types/react` provides.
152
178
  - **Custom CSS properties in `style` objects** (`{ "--size": "10px" }`) are not applied; set
@@ -154,20 +180,20 @@ to HTML.
154
180
 
155
181
  ## Roadmap
156
182
 
157
- The next step is React-style hooks, with the same names and call signatures as React, so
158
- code and habits carry over:
183
+ React-style hooks, with the same names and call signatures as React, so code and habits
184
+ carry over:
159
185
 
160
- | Hook | What it is for |
161
- | --------------------- | ----------------------------------------------------------- |
162
- | `useState` | Local state; changing it re-renders the component |
163
- | `useEffect` | Run code after render, with cleanup |
164
- | `useRef` | Hold a DOM element or a value across renders |
165
- | `useMemo` | Cache a computed value until its dependencies change |
166
- | `useCallback` | Keep the same function between renders |
167
- | `useContext` | Read a value from a `createContext` provider up the tree |
168
- | `useImperativeHandle` | Expose methods from a component to its parent through `ref` |
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 |
169
195
 
170
- These are **planned, not available yet**; details may change while they are built.
196
+ Planned hooks may change while they are built.
171
197
 
172
198
  Out of scope, on purpose: server-side rendering, client-side routing (SPA), server
173
199
  components, Suspense and concurrent rendering. koniwa stays a small tool for static sites of
@@ -182,6 +208,10 @@ yarn typecheck
182
208
  yarn build # emits dist/
183
209
  ```
184
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
+
185
215
  ## License
186
216
 
187
217
  [MIT](LICENSE)
@@ -0,0 +1,7 @@
1
+ import type { Child } from "../types.js";
2
+ import type { Instance } from "./instance.js";
3
+ export declare const callComponent: (instance: Instance) => Child;
4
+ export declare const useHookSlot: <T>(create: () => T) => {
5
+ hook: T;
6
+ instance: Instance;
7
+ };
@@ -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
+ };
@@ -0,0 +1,3 @@
1
+ import type { Props } from "../types.js";
2
+ export declare const createDomElement: (tag: string, isSvg: boolean) => Element;
3
+ export declare const updateProps: (element: Element, oldProps: Props, newProps: Props) => void;
@@ -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,2 @@
1
+ import type { Instance } from "./instance.js";
2
+ export declare const scheduleRender: (instance: Instance) => void;
@@ -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
+ };
@@ -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 CHANGED
@@ -1,4 +1,5 @@
1
- export { Fragment, createVirtualNode } from "./virtual-node.js";
1
+ export { useCallback, useEffect, useMemo, useState } from "./hooks.js";
2
2
  export type { JSX } from "./jsx.js";
3
3
  export { mount, render } from "./render.js";
4
- export type { Child, Component, Props, VirtualNode } from "./types.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 CHANGED
@@ -1,2 +1,3 @@
1
- export { Fragment, createVirtualNode } from "./virtual-node.js";
1
+ export { useCallback, useEffect, useMemo, useState } from "./hooks.js";
2
2
  export { mount, render } from "./render.js";
3
+ export { Fragment, createVirtualNode } from "./virtual-node.js";
@@ -1,6 +1,6 @@
1
- import { Fragment } from "./virtual-node.js";
2
1
  import type { Component, Props, VirtualNode } from "./types.js";
2
+ import { Fragment } from "./virtual-node.js";
3
3
  export { Fragment };
4
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;
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;
@@ -1,7 +1,9 @@
1
1
  import { Fragment, createVirtualNode } from "./virtual-node.js";
2
2
  export { Fragment };
3
- export const jsx = (type, props, _key) => {
3
+ export const jsx = (type, props, key) => {
4
4
  const { children, ...rest } = props;
5
+ if (key !== undefined)
6
+ rest.key = key;
5
7
  return children === undefined
6
8
  ? createVirtualNode(type, rest)
7
9
  : createVirtualNode(type, rest, children);
package/dist/render.js CHANGED
@@ -1,65 +1,16 @@
1
+ import { createRoot, renderRoot, unmount } from "./core/reconcile.js";
1
2
  import { createVirtualNode } from "./virtual-node.js";
2
- const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
3
+ const rootsByContainer = new WeakMap();
3
4
  export const render = (child, container) => {
5
+ const root = createRoot(container);
6
+ const roots = rootsByContainer.get(container) ?? [];
7
+ rootsByContainer.set(container, [...roots, root]);
4
8
  const node = typeof child === "function" ? createVirtualNode(child, null) : child;
5
- appendChild(container, node, false);
9
+ renderRoot(root, node);
6
10
  };
7
11
  export const mount = (child, container) => {
12
+ rootsByContainer.get(container)?.forEach(unmount);
13
+ rootsByContainer.delete(container);
8
14
  container.replaceChildren();
9
15
  render(child, container);
10
16
  };
11
- const appendChild = (parent, child, insideSvg) => {
12
- if (child == null || typeof child === "boolean")
13
- return;
14
- if (Array.isArray(child)) {
15
- for (const item of child)
16
- appendChild(parent, item, insideSvg);
17
- }
18
- else if (typeof child === "string" || typeof child === "number") {
19
- parent.appendChild(document.createTextNode(String(child)));
20
- }
21
- else if (typeof child.type === "function") {
22
- appendChild(parent, callComponent(child.type, child), insideSvg);
23
- }
24
- else {
25
- parent.appendChild(createDomElement(child.type, child, insideSvg));
26
- }
27
- };
28
- const callComponent = (component, node) => component({ ...node.props, children: node.children });
29
- const createDomElement = (tag, node, insideSvg) => {
30
- const isSvg = insideSvg || tag === "svg";
31
- const element = isSvg
32
- ? document.createElementNS(SVG_NAMESPACE, tag)
33
- : document.createElement(tag);
34
- setProps(element, node.props);
35
- // Children of <foreignObject> are HTML again.
36
- const childrenInsideSvg = isSvg && tag !== "foreignObject";
37
- for (const child of node.children)
38
- appendChild(element, child, childrenInsideSvg);
39
- return element;
40
- };
41
- const setProps = (element, props) => {
42
- for (const [name, value] of Object.entries(props)) {
43
- if (name === "key" || name === "children")
44
- continue;
45
- if (value == null || value === false)
46
- continue;
47
- if (name.startsWith("on") && typeof value === "function") {
48
- const eventName = name.slice(2).toLowerCase();
49
- element.addEventListener(eventName, value);
50
- }
51
- else if (name === "style" && typeof value === "object") {
52
- Object.assign(element.style, value);
53
- }
54
- else {
55
- element.setAttribute(toAttributeName(name), value === true ? "" : String(value));
56
- }
57
- }
58
- };
59
- const toAttributeName = (propName) => {
60
- if (propName === "className")
61
- return "class";
62
- if (propName === "htmlFor")
63
- return "for";
64
- return propName;
65
- };
package/dist/types.d.ts CHANGED
@@ -6,3 +6,7 @@ export interface VirtualNode {
6
6
  props: Props;
7
7
  children: Child[];
8
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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@koniwa/core",
3
- "version": "0.1.0",
4
- "description": "A tiny JSX renderer that turns JSX straight into real DOM. No virtual DOM diffing, no state, no dependencies.",
3
+ "version": "0.2.0",
4
+ "description": "A tiny JSX renderer for small static sites: real DOM, React-style hooks, no dependencies.",
5
5
  "keywords": [
6
6
  "jsx",
7
7
  "dom",