@shadow-js/web 1.0.2 → 1.0.4
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/CHANGELOG.md +21 -0
- package/README.md +2 -3
- package/dist/dev/attributes.js +1 -5
- package/dist/dev/attributes.js.map +1 -1
- package/dist/dev/class-style.d.ts +10 -5
- package/dist/dev/class-style.js +44 -47
- package/dist/dev/class-style.js.map +1 -1
- package/dist/dev/control-flow/dynamic.js +2 -2
- package/dist/dev/control-flow/dynamic.js.map +1 -1
- package/dist/dev/control-flow/error-boundary.js +2 -2
- package/dist/dev/control-flow/error-boundary.js.map +1 -1
- package/dist/dev/control-flow/portal.d.ts +2 -2
- package/dist/dev/control-flow/portal.js +15 -13
- package/dist/dev/control-flow/portal.js.map +1 -1
- package/dist/dev/control-flow/suspense-list.js +2 -2
- package/dist/dev/control-flow/suspense-list.js.map +1 -1
- package/dist/dev/control-flow/suspense.js +2 -2
- package/dist/dev/control-flow/suspense.js.map +1 -1
- package/dist/dev/element.js +13 -27
- package/dist/dev/element.js.map +1 -1
- package/dist/dev/events.js +64 -80
- package/dist/dev/events.js.map +1 -1
- package/dist/dev/extend.d.ts +2 -2
- package/dist/dev/extend.js +2 -2
- package/dist/dev/insert.d.ts +11 -0
- package/dist/dev/insert.js +99 -100
- package/dist/dev/insert.js.map +1 -1
- package/dist/dev/internal/accessor.js +56 -0
- package/dist/dev/internal/accessor.js.map +1 -0
- package/dist/dev/internal/claim.js +0 -1
- package/dist/dev/internal/claim.js.map +1 -1
- package/dist/dev/internal/css-units.js +2 -2
- package/dist/dev/internal/css-units.js.map +1 -1
- package/dist/dev/internal/portal-context.d.ts +9 -0
- package/dist/dev/internal/portal-context.js.map +1 -1
- package/dist/dev/internal/react-names.js +22 -12
- package/dist/dev/internal/react-names.js.map +1 -1
- package/dist/dev/internal/reconcile.d.ts +2 -1
- package/dist/dev/internal/reconcile.js +23 -8
- package/dist/dev/internal/reconcile.js.map +1 -1
- package/dist/dev/server/attributes.js +1 -31
- package/dist/dev/server/attributes.js.map +1 -1
- package/dist/dev/server/element.js +5 -6
- package/dist/dev/server/element.js.map +1 -1
- package/dist/dev/server/index.js +1 -1
- package/dist/dev/server/portals.js +3 -0
- package/dist/dev/server/portals.js.map +1 -1
- package/dist/dev/server/render.js +1 -1
- package/dist/dev/server/stream.js +1 -1
- package/dist/dev/server.js +1 -1
- package/dist/dev/spread.js +95 -106
- package/dist/dev/spread.js.map +1 -1
- package/dist/dev/template.js +1 -3
- package/dist/dev/template.js.map +1 -1
- package/dist/dev/view-transition.js +12 -4
- package/dist/dev/view-transition.js.map +1 -1
- package/dist/prod/attributes.js +1 -1
- package/dist/prod/attributes.js.map +1 -1
- package/dist/prod/class-style.js +1 -1
- package/dist/prod/class-style.js.map +1 -1
- package/dist/prod/control-flow/dynamic.js +1 -1
- package/dist/prod/control-flow/dynamic.js.map +1 -1
- package/dist/prod/control-flow/error-boundary.js +1 -1
- package/dist/prod/control-flow/error-boundary.js.map +1 -1
- package/dist/prod/control-flow/portal.js +1 -1
- package/dist/prod/control-flow/portal.js.map +1 -1
- package/dist/prod/control-flow/suspense-list.js +1 -1
- package/dist/prod/control-flow/suspense-list.js.map +1 -1
- package/dist/prod/control-flow/suspense.js +1 -1
- package/dist/prod/control-flow/suspense.js.map +1 -1
- package/dist/prod/element.js +1 -1
- package/dist/prod/element.js.map +1 -1
- package/dist/prod/events.js +1 -1
- package/dist/prod/events.js.map +1 -1
- package/dist/prod/extend.js +1 -1
- package/dist/prod/insert.js +1 -1
- package/dist/prod/insert.js.map +1 -1
- package/dist/prod/internal/accessor.js +2 -0
- package/dist/prod/internal/accessor.js.map +1 -0
- package/dist/prod/internal/claim.js +1 -1
- package/dist/prod/internal/claim.js.map +1 -1
- package/dist/prod/internal/css-units.js +1 -1
- package/dist/prod/internal/css-units.js.map +1 -1
- package/dist/prod/internal/portal-context.js.map +1 -1
- package/dist/prod/internal/react-names.js +1 -1
- package/dist/prod/internal/react-names.js.map +1 -1
- package/dist/prod/internal/reconcile.js +1 -1
- package/dist/prod/internal/reconcile.js.map +1 -1
- package/dist/prod/server/attributes.js +1 -1
- package/dist/prod/server/attributes.js.map +1 -1
- package/dist/prod/server/element.js +1 -1
- package/dist/prod/server/element.js.map +1 -1
- package/dist/prod/server/index.js +1 -1
- package/dist/prod/server/portals.js +1 -1
- package/dist/prod/server/portals.js.map +1 -1
- package/dist/prod/server/render.js +1 -1
- package/dist/prod/server/stream.js +1 -1
- package/dist/prod/server.js +1 -1
- package/dist/prod/spread.js +1 -1
- package/dist/prod/spread.js.map +1 -1
- package/dist/prod/template.js +1 -1
- package/dist/prod/template.js.map +1 -1
- package/dist/prod/view-transition.js +1 -1
- package/dist/prod/view-transition.js.map +1 -1
- package/dist/server/attributes.js +1 -1
- package/dist/server/attributes.js.map +1 -1
- package/dist/server/class-style.js +1 -1
- package/dist/server/class-style.js.map +1 -1
- package/dist/server/control-flow/dynamic.js.map +1 -1
- package/dist/server/control-flow/error-boundary.js +1 -1
- package/dist/server/control-flow/error-boundary.js.map +1 -1
- package/dist/server/control-flow/portal.js +1 -1
- package/dist/server/control-flow/portal.js.map +1 -1
- package/dist/server/control-flow/suspense-list.js +1 -1
- package/dist/server/control-flow/suspense-list.js.map +1 -1
- package/dist/server/control-flow/suspense.js +1 -1
- package/dist/server/control-flow/suspense.js.map +1 -1
- package/dist/server/element.js.map +1 -1
- package/dist/server/events.js +1 -1
- package/dist/server/events.js.map +1 -1
- package/dist/server/extend.js +1 -1
- package/dist/server/insert.js +1 -1
- package/dist/server/insert.js.map +1 -1
- package/dist/server/internal/accessor.js +2 -0
- package/dist/server/internal/accessor.js.map +1 -0
- package/dist/server/internal/claim.js +1 -1
- package/dist/server/internal/claim.js.map +1 -1
- package/dist/server/internal/css-units.js +1 -1
- package/dist/server/internal/css-units.js.map +1 -1
- package/dist/server/internal/portal-context.js.map +1 -1
- package/dist/server/internal/react-names.js +1 -1
- package/dist/server/internal/react-names.js.map +1 -1
- package/dist/server/internal/reconcile.js +1 -1
- package/dist/server/internal/reconcile.js.map +1 -1
- package/dist/server/server/attributes.js +1 -1
- package/dist/server/server/attributes.js.map +1 -1
- package/dist/server/server/element.js +1 -1
- package/dist/server/server/element.js.map +1 -1
- package/dist/server/server/index.js +1 -1
- package/dist/server/server/portals.js +1 -1
- package/dist/server/server/portals.js.map +1 -1
- package/dist/server/server/render.js +1 -1
- package/dist/server/server/stream.js +1 -1
- package/dist/server/server.js +1 -1
- package/dist/server/spread.js +1 -1
- package/dist/server/spread.js.map +1 -1
- package/dist/server/template.js +1 -1
- package/dist/server/template.js.map +1 -1
- package/dist/server/view-transition.js.map +1 -1
- package/dist/server-dev/attributes.js +1 -5
- package/dist/server-dev/attributes.js.map +1 -1
- package/dist/server-dev/class-style.js +44 -47
- package/dist/server-dev/class-style.js.map +1 -1
- package/dist/server-dev/control-flow/dynamic.js.map +1 -1
- package/dist/server-dev/control-flow/error-boundary.js +2 -2
- package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
- package/dist/server-dev/control-flow/portal.js +15 -13
- package/dist/server-dev/control-flow/portal.js.map +1 -1
- package/dist/server-dev/control-flow/suspense-list.js +2 -2
- package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
- package/dist/server-dev/control-flow/suspense.js +2 -2
- package/dist/server-dev/control-flow/suspense.js.map +1 -1
- package/dist/server-dev/element.js.map +1 -1
- package/dist/server-dev/events.js +64 -80
- package/dist/server-dev/events.js.map +1 -1
- package/dist/server-dev/extend.js +2 -2
- package/dist/server-dev/insert.js +99 -100
- package/dist/server-dev/insert.js.map +1 -1
- package/dist/server-dev/internal/accessor.js +56 -0
- package/dist/server-dev/internal/accessor.js.map +1 -0
- package/dist/server-dev/internal/claim.js +0 -1
- package/dist/server-dev/internal/claim.js.map +1 -1
- package/dist/server-dev/internal/css-units.js +2 -2
- package/dist/server-dev/internal/css-units.js.map +1 -1
- package/dist/server-dev/internal/portal-context.js.map +1 -1
- package/dist/server-dev/internal/react-names.js +22 -12
- package/dist/server-dev/internal/react-names.js.map +1 -1
- package/dist/server-dev/internal/reconcile.js +23 -8
- package/dist/server-dev/internal/reconcile.js.map +1 -1
- package/dist/server-dev/server/attributes.js +1 -31
- package/dist/server-dev/server/attributes.js.map +1 -1
- package/dist/server-dev/server/element.js +5 -6
- package/dist/server-dev/server/element.js.map +1 -1
- package/dist/server-dev/server/index.js +1 -1
- package/dist/server-dev/server/portals.js +3 -0
- package/dist/server-dev/server/portals.js.map +1 -1
- package/dist/server-dev/server/render.js +1 -1
- package/dist/server-dev/server/stream.js +1 -1
- package/dist/server-dev/server.js +1 -1
- package/dist/server-dev/spread.js +81 -105
- package/dist/server-dev/spread.js.map +1 -1
- package/dist/server-dev/template.js +1 -3
- package/dist/server-dev/template.js.map +1 -1
- package/dist/server-dev/view-transition.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.js","names":[],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n
|
|
1
|
+
{"version":3,"file":"element.js","names":[],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setBoolAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { isFlagAttribute } from \"./internal/react-names\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\nimport { isTextOnlyElement } from \"./server/raw-text\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n // The content of a style or a title is text the parser reads whole: no markers can go in it.\n if (children === undefined || isTextOnlyElement(tag)) return children;\n return [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n if (/^on[A-Z]/.test(key)) {\n // Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n // receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n // untracked, as the event binding of `Dynamic` runs them.\n const handler = read[key];\n const tuple = Array.isArray(handler);\n // The tuple's data is read once, at bind time, like the handler.\n const [fn, data]: readonly unknown[] = tuple ? handler : [handler];\n if (typeof fn === \"function\") {\n el.addEventListener(key.slice(2).toLowerCase(), (event: Event): void => {\n batch(() => untrack(() => (tuple ? fn.call(el, data, event) : fn.call(el, event))));\n });\n }\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n // The server writes a boolean attribute by truthiness; the client does the same. A name\n // that is a flag has no React spelling, so lower case is its attribute name.\n const name = key.toLowerCase();\n if (isFlagAttribute(name, value)) setBoolAttribute(el, name, value);\n else setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") untrack(() => ref(el));\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCpB,SAAgB,QAAQ,KAAa,OAAwB;CAC3D,IAAI,CAAC,YAAY,KAAK,GAAG,KAAK,IAAI,YAAY,MAAM,UAClD,MAAM,IAAI,UAAoB,+BAAsD;CAEtF,MAAM,OAAO;CAGX,OAAO,WACL,KACA,aACM;EACJ,MAAM,WAAW,KAAK;EAEtB,IAAI,aAAa,KAAA,KAAa,kBAAkB,GAAG,GAAG,OAAO;EAC7D,OAAO;GAAC,OAAO,UAAU;GAAG;GAAU,OAAO,UAAU;EAAC;CAC1D,GACA,IACF;AA8CJ"}
|
|
@@ -7,77 +7,60 @@ import { batch, getOwner, onCleanup, untrack } from "@shadow-js/core";
|
|
|
7
7
|
const DELEGATED_EVENTS = /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;
|
|
8
8
|
/** Documents that already carry the delegated listener for a given event name. */
|
|
9
9
|
const installed = /* @__PURE__ */ new WeakMap();
|
|
10
|
-
/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */
|
|
11
|
-
function invoke(fn, node, event, args) {
|
|
12
|
-
Object.defineProperty(event, "currentTarget", {
|
|
13
|
-
configurable: true,
|
|
14
|
-
get: () => node
|
|
15
|
-
});
|
|
16
|
-
try {
|
|
17
|
-
untrack(() => fn.call(node, ...args));
|
|
18
|
-
} finally {
|
|
19
|
-
Reflect.deleteProperty(event, "currentTarget");
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
10
|
/**
|
|
23
11
|
* The one listener per (document, event). It walks `composedPath()` from the target outward,
|
|
24
|
-
* calling `node.$$<type>` with `this = node
|
|
12
|
+
* calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the
|
|
13
|
+
* duration of the call. Stops when a handler stops propagation.
|
|
25
14
|
*/
|
|
26
15
|
function dispatchDelegated(event) {
|
|
27
|
-
batch(() =>
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
16
|
+
batch(() => {
|
|
17
|
+
const key = `$$${event.type}`;
|
|
18
|
+
const dataKey = `${key}Data`;
|
|
19
|
+
const errors = [];
|
|
20
|
+
for (const node of event.composedPath()) {
|
|
21
|
+
if (event.cancelBubble) break;
|
|
22
|
+
const fn = Reflect.get(node, key);
|
|
23
|
+
if (typeof fn !== "function") continue;
|
|
24
|
+
const data = Reflect.get(node, dataKey);
|
|
25
|
+
try {
|
|
26
|
+
Object.defineProperty(event, "currentTarget", {
|
|
27
|
+
configurable: true,
|
|
28
|
+
get: () => node
|
|
29
|
+
});
|
|
30
|
+
untrack(() => fn.call(node, ...data === void 0 ? [event] : [data, event]));
|
|
31
|
+
} catch (error) {
|
|
32
|
+
errors.push(error);
|
|
33
|
+
} finally {
|
|
34
|
+
Reflect.deleteProperty(event, "currentTarget");
|
|
35
|
+
}
|
|
42
36
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
37
|
+
const [first] = errors;
|
|
38
|
+
if (errors.length === 1) throw first;
|
|
39
|
+
if (errors.length > 1) throw new AggregateError(errors, "Several event handlers threw.");
|
|
40
|
+
});
|
|
47
41
|
}
|
|
48
42
|
function isListenerObject(handler) {
|
|
49
43
|
return typeof handler === "object" && handler !== null && typeof handler.handleEvent === "function";
|
|
50
44
|
}
|
|
51
|
-
/**
|
|
52
|
-
function
|
|
53
|
-
const { once, passive, signal } = object;
|
|
54
|
-
const options = {
|
|
55
|
-
capture: object.capture === true || capture,
|
|
56
|
-
once,
|
|
57
|
-
passive,
|
|
58
|
-
signal
|
|
59
|
-
};
|
|
45
|
+
/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */
|
|
46
|
+
function listen(el, name, run, options) {
|
|
60
47
|
const listener = (event) => {
|
|
61
|
-
batch(() => untrack(() =>
|
|
48
|
+
batch(() => untrack(() => run(event)));
|
|
62
49
|
};
|
|
63
50
|
el.addEventListener(name, listener, options);
|
|
64
51
|
return () => {
|
|
65
52
|
el.removeEventListener(name, listener, options);
|
|
66
53
|
};
|
|
67
54
|
}
|
|
68
|
-
/**
|
|
69
|
-
function
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
data: handler[1],
|
|
78
|
-
tuple: true
|
|
79
|
-
};
|
|
80
|
-
throw new TypeError("addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.");
|
|
55
|
+
/** Binds a listener object natively (never delegated), honoring its options. */
|
|
56
|
+
function bindListenerObject(el, name, object, capture) {
|
|
57
|
+
const { once, passive, signal } = object;
|
|
58
|
+
return listen(el, name, (event) => object.handleEvent(event), {
|
|
59
|
+
capture: object.capture === true || capture,
|
|
60
|
+
once,
|
|
61
|
+
passive,
|
|
62
|
+
signal
|
|
63
|
+
});
|
|
81
64
|
}
|
|
82
65
|
/**
|
|
83
66
|
* Combines several handlers for one event name on one element into one handler that calls them in
|
|
@@ -103,6 +86,17 @@ function chainEvents(...handlers) {
|
|
|
103
86
|
for (const handler of handlers) handler.call(this, event);
|
|
104
87
|
};
|
|
105
88
|
}
|
|
89
|
+
/** Installs the delegated listener for one event name on `target`, unless it is there already. */
|
|
90
|
+
function installDelegate(name, target) {
|
|
91
|
+
let known = installed.get(target);
|
|
92
|
+
if (known === void 0) {
|
|
93
|
+
known = /* @__PURE__ */ new Set();
|
|
94
|
+
installed.set(target, known);
|
|
95
|
+
}
|
|
96
|
+
if (known.has(name)) return;
|
|
97
|
+
known.add(name);
|
|
98
|
+
target.addEventListener(name, dispatchDelegated);
|
|
99
|
+
}
|
|
106
100
|
/**
|
|
107
101
|
* Installs the document listener that runs delegated handlers for each event name, once per
|
|
108
102
|
* document and name; repeated calls do nothing. Compiled modules call it for the events they
|
|
@@ -121,16 +115,7 @@ function chainEvents(...handlers) {
|
|
|
121
115
|
* @since 1.0.0
|
|
122
116
|
*/
|
|
123
117
|
function delegateEvents(names, target = globalThis.document) {
|
|
124
|
-
|
|
125
|
-
if (known === void 0) {
|
|
126
|
-
known = /* @__PURE__ */ new Set();
|
|
127
|
-
installed.set(target, known);
|
|
128
|
-
}
|
|
129
|
-
for (const name of names) {
|
|
130
|
-
if (known.has(name)) continue;
|
|
131
|
-
known.add(name);
|
|
132
|
-
target.addEventListener(name, dispatchDelegated);
|
|
133
|
-
}
|
|
118
|
+
for (const name of names) installDelegate(name, target);
|
|
134
119
|
}
|
|
135
120
|
/**
|
|
136
121
|
* Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop
|
|
@@ -174,30 +159,29 @@ function delegationDocument(el) {
|
|
|
174
159
|
function bindEvent(el, name, handler, delegate, capture = false) {
|
|
175
160
|
if (handler === null || handler === void 0 || handler === false) return void 0;
|
|
176
161
|
if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);
|
|
177
|
-
|
|
162
|
+
let fn = handler;
|
|
163
|
+
let data;
|
|
164
|
+
let tuple = false;
|
|
165
|
+
if (Array.isArray(handler) && typeof handler[0] === "function") {
|
|
166
|
+
fn = handler[0];
|
|
167
|
+
data = handler[1];
|
|
168
|
+
tuple = true;
|
|
169
|
+
} else if (typeof handler !== "function") throw new TypeError("addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.");
|
|
178
170
|
const slot = `$$${name}`;
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
delegateEvents([name], delegationDocument(el));
|
|
171
|
+
if (delegate && (!tuple || data !== void 0) && !capture && DELEGATED_EVENTS.test(name) && Reflect.get(el, slot) === void 0) {
|
|
172
|
+
installDelegate(name, delegationDocument(el));
|
|
182
173
|
const dataKey = `${slot}Data`;
|
|
183
|
-
Reflect.set(el, slot,
|
|
184
|
-
if (
|
|
174
|
+
Reflect.set(el, slot, fn);
|
|
175
|
+
if (tuple) Reflect.set(el, dataKey, data);
|
|
185
176
|
else Reflect.deleteProperty(el, dataKey);
|
|
186
177
|
return () => {
|
|
187
|
-
if (Reflect.get(el, slot) ===
|
|
178
|
+
if (Reflect.get(el, slot) === fn) {
|
|
188
179
|
Reflect.deleteProperty(el, slot);
|
|
189
180
|
Reflect.deleteProperty(el, dataKey);
|
|
190
181
|
}
|
|
191
182
|
};
|
|
192
183
|
}
|
|
193
|
-
|
|
194
|
-
const args = binding.tuple ? [binding.data, event] : [event];
|
|
195
|
-
batch(() => untrack(() => binding.fn.call(el, ...args)));
|
|
196
|
-
};
|
|
197
|
-
el.addEventListener(name, listener, capture);
|
|
198
|
-
return () => {
|
|
199
|
-
el.removeEventListener(name, listener, capture);
|
|
200
|
-
};
|
|
184
|
+
return listen(el, name, (event) => fn.call(el, ...tuple ? [data, event] : [event]), capture);
|
|
201
185
|
}
|
|
202
186
|
/**
|
|
203
187
|
* Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","names":[],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(fn: Binding[\"fn\"], node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n invoke(fn as Binding[\"fn\"], node, event, data === undefined ? [event] : [data, event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n const options = {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n const plain = !binding.tuple || binding.data !== undefined;\n if (\n delegate &&\n plain &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":";;;;;;AAMA,MAAM,mBACJ;;AAGF,MAAM,4BAAY,IAAI,QAA+B;;AAUrD,SAAS,OAAO,IAAmB,MAAmB,OAAc,MAAuB;CACzF,OAAO,eAAe,OAAO,iBAAiB;EAAE,cAAc;EAAM,WAAW;CAAK,CAAC;CACrF,IAAI;EACF,cAAc,GAAG,KAAK,MAAM,GAAG,IAAI,CAAC;CACtC,UAAU;EACR,QAAQ,eAAe,OAAO,eAAe;CAC/C;AACF;;;;;AAMA,SAAS,kBAAkB,OAAoB;CAG7C,YAAY,aAAa,KAAK,CAAC;AACjC;AAEA,SAAS,aAAa,OAAoB;CACxC,MAAM,MAAM,KAAK,MAAM;CACvB,MAAM,UAAU,GAAG,IAAI;CACvB,MAAM,SAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,MAAM,aAA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ACxB,QAAQ,IAAI,IAAI,MAAM,QAAQ,EAAE;EAChC,IAAI,QAAQ,OAAO,QAAQ,IAAI,IAAI,SAAS,QAAQ,IAAI;OACnD,QAAQ,eAAe,IAAI,OAAO;EACvC,aAAa;GACX,IAAI,QAAQ,IAAI,IAAI,IAAI,MAAM,QAAQ,IAAI;IACxC,QAAQ,eAAe,IAAI,IAAI;IAC/B,QAAQ,eAAe,IAAI,OAAO;GACpC;EACF;CACF;CACA,MAAM,YAAY,UAAuB;EACvC,MAAM,OAAkB,QAAQ,QAAQ,CAAC,QAAQ,MAAM,KAAK,IAAI,CAAC,KAAK;EACtE,YAAY,cAAc,QAAQ,GAAG,KAAK,IAAI,GAAG,IAAI,CAAC,CAAC;CACzD;CACA,GAAG,iBAAiB,MAAM,UAAU,OAAO;CAC3C,aAAa;EACX,GAAG,oBAAoB,MAAM,UAAU,OAAO;CAChD;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBACd,IACA,MACA,SACA,UACA,SACM;CACN,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,aAAa,MAAM,YAAY,IAAI;CAE/E,IAAI,WAAW,KAAA,KAAa,SAAS,MAAM,MAAM,UAAU,MAAM;AACnE"}
|
|
1
|
+
{"version":3,"file":"events.js","names":[],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS =\n /^(?:click|dblclick|input|beforeinput|contextmenu|key(?:down|up|press)|(?:pointer|mouse)(?:down|up|move|over|out)|focus(?:in|out)|touch(?:start|end|move))$/;\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A bound handler: called with `this` = the node. */\ntype Handler = (this: EventTarget, ...args: unknown[]) => unknown;\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node` and `currentTarget` retargeted to the node for the\n * duration of the call. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = Reflect.get(node, key);\n if (typeof fn !== \"function\") continue;\n const data = Reflect.get(node, dataKey);\n try {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n untrack(() =>\n (fn as Handler).call(node, ...(data === undefined ? [event] : [data, event])),\n );\n } catch (error) {\n errors.push(error);\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n });\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Adds a native listener that runs `run` untracked in one batch; returns the function that removes it. */\nfunction listen(\n el: Element,\n name: string,\n run: (event: Event) => unknown,\n options: AddEventListenerOptions | boolean,\n): () => void {\n const listener = (event: Event): void => {\n batch(() => untrack(() => run(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const { once, passive, signal } = object;\n // A member that is `undefined` counts as absent to the DOM, so none of them needs a check.\n return listen(el, name, (event) => object.handleEvent(event), {\n capture: object.capture === true || capture,\n once,\n passive,\n signal,\n } as AddEventListenerOptions);\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/** Installs the delegated listener for one event name on `target`, unless it is there already. */\nfunction installDelegate(name: string, target: Document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n if (known.has(name)) return;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n for (const name of names) installDelegate(name, target);\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n let fn = handler as Handler;\n let data: unknown;\n let tuple = false;\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n fn = handler[0] as Handler;\n data = handler[1];\n tuple = true;\n } else if (typeof handler !== \"function\") {\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n }\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n // The delegated slot tells a tuple from a plain handler by its data being defined, so a tuple whose\n // data is undefined is bound natively, where it still receives `(undefined, event)`.\n if (\n delegate &&\n (!tuple || data !== undefined) &&\n !capture &&\n DELEGATED_EVENTS.test(name) &&\n Reflect.get(el, slot) === undefined\n ) {\n installDelegate(name, delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, fn);\n if (tuple) Reflect.set(el, dataKey, data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n return listen(el, name, (event) => fn.call(el, ...(tuple ? [data, event] : [event])), capture);\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":";;;;;;AAMA,MAAM,mBACJ;;AAGF,MAAM,4BAAY,IAAI,QAA+B;;;;;;AAUrD,SAAS,kBAAkB,OAAoB;CAG7C,YAAY;EACV,MAAM,MAAM,KAAK,MAAM;EACvB,MAAM,UAAU,GAAG,IAAI;EACvB,MAAM,SAAoB,CAAC;EAC3B,KAAK,MAAM,QAAQ,MAAM,aAAa,GAAG;GACvC,IAAI,MAAM,cAAc;GACxB,MAAM,KAAK,QAAQ,IAAI,MAAM,GAAG;GAChC,IAAI,OAAO,OAAO,YAAY;GAC9B,MAAM,OAAO,QAAQ,IAAI,MAAM,OAAO;GACtC,IAAI;IACF,OAAO,eAAe,OAAO,iBAAiB;KAAE,cAAc;KAAM,WAAW;IAAK,CAAC;IACrF,cACG,GAAe,KAAK,MAAM,GAAI,SAAS,KAAA,IAAY,CAAC,KAAK,IAAI,CAAC,MAAM,KAAK,CAAE,CAC9E;GACF,SAAS,OAAO;IACd,OAAO,KAAK,KAAK;GACnB,UAAU;IACR,QAAQ,eAAe,OAAO,eAAe;GAC/C;EACF;EACA,MAAM,CAAC,SAAS;EAChB,IAAI,OAAO,WAAW,GAAG,MAAM;EAC/B,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,eACR,QACU,+BACZ;CACJ,CAAC;AACH;AAWA,SAAS,iBAAiB,SAA6C;CACrE,OACE,OAAO,YAAY,YACnB,YAAY,QACZ,OAAQ,QAAsC,gBAAgB;AAElE;;AAGA,SAAS,OACP,IACA,MACA,KACA,SACY;CACZ,MAAM,YAAY,UAAuB;EACvC,YAAY,cAAc,IAAI,KAAK,CAAC,CAAC;CACvC;CACA,GAAG,iBAAiB,MAAM,UAAU,OAAO;CAC3C,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
5
5
|
import { claimElement, claimPortal, isClaiming, takeRegion, withoutClaiming } from "./internal/claim.js";
|
|
6
6
|
import { claims } from "./internal/hydration-hooks.js";
|
|
7
7
|
import { reconcileNodes } from "./internal/reconcile.js";
|
|
8
|
-
import { bindRegion, createRegion, removeRegion } from "./insert.js";
|
|
8
|
+
import { bindRegion, createRegion, moveRegion, removeRegion } from "./insert.js";
|
|
9
9
|
import { element } from "./element.js";
|
|
10
10
|
import { PortalContext } from "./internal/portal-context.js";
|
|
11
11
|
import { StreamContext } from "./internal/stream-context.js";
|
|
12
|
-
export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
|
|
12
|
+
export { HTML_NS, MATHML_NS, PortalContext, SVG_NS, StreamContext, bindRegion, childScope, claimElement, claimPortal, claims, createRegion, createRootScope, currentScope, element, enterComponent, isClaiming, isUnsafeUrlAttribute, moveRegion, nextKey, reconcileNodes, removeRegion, resourceKey, takeRegion, warnOnce, withScope, withoutClaiming };
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
+
import { leaves } from "./internal/accessor.js";
|
|
1
2
|
import { checkClaimedText } from "./internal/claim.js";
|
|
2
3
|
import { claims } from "./internal/hydration-hooks.js";
|
|
3
|
-
import { reconcileNodes } from "./internal/reconcile.js";
|
|
4
|
-
import { useRenderEffect } from "@shadow-js/core";
|
|
4
|
+
import { keepFocus, reconcileNodes } from "./internal/reconcile.js";
|
|
5
|
+
import { onCleanup, useRenderEffect } from "@shadow-js/core";
|
|
5
6
|
import { addCleanup, createComputation, currentOwner, disposeOwner, readComputation } from "@shadow-js/core/extend";
|
|
6
7
|
// src/insert.ts
|
|
7
|
-
/** Longest chain of accessors a single value may hold (a function returning a function ...). */
|
|
8
|
-
const MAX_ACCESSOR_DEPTH = 1e4;
|
|
9
8
|
/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */
|
|
10
9
|
const tails = /* @__PURE__ */ new WeakMap();
|
|
11
10
|
/** The document a node belongs to (a Document is its own document). */
|
|
@@ -34,39 +33,23 @@ function pruneTexts(region, keep) {
|
|
|
34
33
|
} else if (!keep.includes(texts)) region.texts = null;
|
|
35
34
|
}
|
|
36
35
|
/**
|
|
36
|
+
* The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect
|
|
37
|
+
* that runs again flattens the same fragment value once more: it must still give those nodes.
|
|
38
|
+
*/
|
|
39
|
+
const fragmentChildren = /* @__PURE__ */ new WeakMap();
|
|
40
|
+
/**
|
|
37
41
|
* Flattens a value into parts without recursion. Functions are called (and their results unwrapped)
|
|
38
42
|
* through `call`, which runs inside the render effect that owns the value, so reads are tracked.
|
|
39
43
|
*/
|
|
40
|
-
function flatten(root, call
|
|
44
|
+
function flatten(root, call) {
|
|
41
45
|
const parts = [];
|
|
42
|
-
const
|
|
43
|
-
const cursors = [0];
|
|
44
|
-
const active = /* @__PURE__ */ new Set();
|
|
45
|
-
while (frames.length > 0) {
|
|
46
|
-
const top = frames.length - 1;
|
|
47
|
-
const frame = frames[top];
|
|
48
|
-
const cursor = cursors[top] ?? 0;
|
|
49
|
-
if (frame === void 0 || cursor >= frame.length) {
|
|
50
|
-
const done = frames.pop();
|
|
51
|
-
if (done !== void 0) active.delete(done);
|
|
52
|
-
cursors.pop();
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
cursors[top] = cursor + 1;
|
|
56
|
-
let item = frame[cursor];
|
|
57
|
-
for (let depth = 0; typeof item === "function"; depth += 1) {
|
|
58
|
-
if (depth >= MAX_ACCESSOR_DEPTH) throw new TypeError("insert(): accessor chain is too deep.");
|
|
59
|
-
item = call(item);
|
|
60
|
-
}
|
|
46
|
+
for (const item of leaves(root, "insert(): a value contains itself.", call)) {
|
|
61
47
|
if (item === null || item === void 0 || typeof item === "boolean") continue;
|
|
62
|
-
if (item instanceof DocumentFragment)
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
frames.push(item);
|
|
68
|
-
cursors.push(0);
|
|
69
|
-
} else parts.push(String(item));
|
|
48
|
+
if (item instanceof DocumentFragment) {
|
|
49
|
+
const kids = fragmentChildren.get(item) ?? [...item.childNodes];
|
|
50
|
+
fragmentChildren.set(item, kids);
|
|
51
|
+
for (const child of kids) parts.push(child);
|
|
52
|
+
} else parts.push(item instanceof Node ? item : String(item));
|
|
70
53
|
}
|
|
71
54
|
return parts;
|
|
72
55
|
}
|
|
@@ -122,16 +105,20 @@ function endOf(region, last) {
|
|
|
122
105
|
if (marker.parentNode !== region.parent) return null;
|
|
123
106
|
return marker.nextSibling;
|
|
124
107
|
}
|
|
125
|
-
/**
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
108
|
+
/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */
|
|
109
|
+
const commitWatchers = /* @__PURE__ */ new WeakMap();
|
|
110
|
+
/**
|
|
111
|
+
* Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the
|
|
112
|
+
* parent holds (a name on the first element of a content region) can follow a change of content.
|
|
113
|
+
* The watch ends with the owner that is current when this is called.
|
|
114
|
+
* @internal
|
|
115
|
+
*/
|
|
116
|
+
function watchCommits(parent, run) {
|
|
117
|
+
const set = commitWatchers.get(parent) ?? /* @__PURE__ */ new Set();
|
|
118
|
+
commitWatchers.set(parent, set.add(run));
|
|
119
|
+
onCleanup(() => {
|
|
120
|
+
set.delete(run);
|
|
121
|
+
});
|
|
135
122
|
}
|
|
136
123
|
/** Applies a flattened value to a region. */
|
|
137
124
|
function commit(region, parts) {
|
|
@@ -139,7 +126,18 @@ function commit(region, parts) {
|
|
|
139
126
|
checkClaimedText(region.claimed, parts);
|
|
140
127
|
region.claimed = void 0;
|
|
141
128
|
}
|
|
142
|
-
|
|
129
|
+
const next = materialize(region, parts);
|
|
130
|
+
const parent = region.parent;
|
|
131
|
+
const attached = region.nodes.filter((node) => node.parentNode === parent);
|
|
132
|
+
const first = attached[0];
|
|
133
|
+
const end = endOf(region, attached.at(-1));
|
|
134
|
+
if (next.length === 0 && first !== void 0) region.marker = first.previousSibling;
|
|
135
|
+
reconcileNodes(parent, attached, next, end);
|
|
136
|
+
region.nodes = next;
|
|
137
|
+
pruneTexts(region, next);
|
|
138
|
+
commitWatchers.get(parent)?.forEach((run) => {
|
|
139
|
+
run();
|
|
140
|
+
});
|
|
143
141
|
}
|
|
144
142
|
/**
|
|
145
143
|
* Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region
|
|
@@ -149,7 +147,7 @@ function commit(region, parts) {
|
|
|
149
147
|
function commitValue(region, raw) {
|
|
150
148
|
if ((typeof raw === "string" || typeof raw === "number") && !region.claimed) {
|
|
151
149
|
const nodes = region.nodes;
|
|
152
|
-
const text =
|
|
150
|
+
const text = String(raw);
|
|
153
151
|
if (nodes.length === 1) {
|
|
154
152
|
const current = nodes[0];
|
|
155
153
|
if (current instanceof Text && current.parentNode === region.parent && ownsText(region, current)) {
|
|
@@ -166,28 +164,25 @@ function commitValue(region, raw) {
|
|
|
166
164
|
}
|
|
167
165
|
commit(region, flatten(raw));
|
|
168
166
|
}
|
|
169
|
-
/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */
|
|
170
|
-
function adoptInitial(parent, initial) {
|
|
171
|
-
const adopted = [];
|
|
172
|
-
const seen = /* @__PURE__ */ new Set();
|
|
173
|
-
for (const part of flatten(initial)) {
|
|
174
|
-
if (typeof part === "string" || seen.has(part) || part.parentNode !== parent) continue;
|
|
175
|
-
seen.add(part);
|
|
176
|
-
adopted.push(part);
|
|
177
|
-
}
|
|
178
|
-
return adopted;
|
|
179
|
-
}
|
|
180
167
|
/**
|
|
181
168
|
* Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes
|
|
182
169
|
* already in the DOM, from hydration or splitText) are both optional.
|
|
183
170
|
* @internal
|
|
184
171
|
*/
|
|
185
172
|
function createRegion(parent, anchorNode, initial) {
|
|
186
|
-
const nodes =
|
|
173
|
+
const nodes = [];
|
|
174
|
+
if (initial !== void 0) {
|
|
175
|
+
const seen = /* @__PURE__ */ new Set();
|
|
176
|
+
for (const part of flatten(initial)) {
|
|
177
|
+
if (typeof part === "string" || seen.has(part) || part.parentNode !== parent) continue;
|
|
178
|
+
seen.add(part);
|
|
179
|
+
nodes.push(part);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
187
182
|
const region = {
|
|
188
183
|
parent,
|
|
189
184
|
anchor: anchorNode,
|
|
190
|
-
marker: nodes.length > 0 ? nodes[0]
|
|
185
|
+
marker: nodes.length > 0 ? nodes[0].previousSibling : parent.lastChild,
|
|
191
186
|
nodes,
|
|
192
187
|
texts: null
|
|
193
188
|
};
|
|
@@ -200,7 +195,9 @@ function createRegion(parent, anchorNode, initial) {
|
|
|
200
195
|
* and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then
|
|
201
196
|
* always goes before that node, and this region's marker is the node, so no region has a marker that a sibling
|
|
202
197
|
* region can replace: the order of the calls holds however the regions change. A region with static content
|
|
203
|
-
* between it and this one needs nothing, because its marker and its end are the static nodes.
|
|
198
|
+
* between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its
|
|
199
|
+
* own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep
|
|
200
|
+
* the regions of that call alive as long as the parent's owner.)
|
|
204
201
|
*/
|
|
205
202
|
function linkRegion(region) {
|
|
206
203
|
const parent = region.parent;
|
|
@@ -223,7 +220,7 @@ function containsFunction(root) {
|
|
|
223
220
|
const stack = [root];
|
|
224
221
|
const seen = /* @__PURE__ */ new Set([root]);
|
|
225
222
|
while (stack.length > 0) {
|
|
226
|
-
const frame = stack.pop()
|
|
223
|
+
const frame = stack.pop();
|
|
227
224
|
for (const item of frame) {
|
|
228
225
|
if (typeof item === "function") return true;
|
|
229
226
|
if (Array.isArray(item) && !seen.has(item)) {
|
|
@@ -235,42 +232,6 @@ function containsFunction(root) {
|
|
|
235
232
|
return false;
|
|
236
233
|
}
|
|
237
234
|
/**
|
|
238
|
-
* One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,
|
|
239
|
-
* so a new result drops them all; the effect that resolves the result runs many times and must not
|
|
240
|
-
* own them). `prune` disposes the memos of accessors the last
|
|
241
|
-
* run did not meet, which bounds the cache by what the region currently shows.
|
|
242
|
-
*/
|
|
243
|
-
function createCallCache(owner) {
|
|
244
|
-
const memos = /* @__PURE__ */ new Map();
|
|
245
|
-
let touched = /* @__PURE__ */ new Set();
|
|
246
|
-
return {
|
|
247
|
-
begin() {
|
|
248
|
-
touched = /* @__PURE__ */ new Set();
|
|
249
|
-
},
|
|
250
|
-
call(fn) {
|
|
251
|
-
touched.add(fn);
|
|
252
|
-
let node = memos.get(fn);
|
|
253
|
-
if (node === void 0) {
|
|
254
|
-
node = createComputation({
|
|
255
|
-
kind: "memo",
|
|
256
|
-
fn: () => fn(),
|
|
257
|
-
allowWrites: true,
|
|
258
|
-
owner
|
|
259
|
-
});
|
|
260
|
-
memos.set(fn, node);
|
|
261
|
-
}
|
|
262
|
-
return readComputation(node);
|
|
263
|
-
},
|
|
264
|
-
prune() {
|
|
265
|
-
for (const [fn, node] of memos) {
|
|
266
|
-
if (touched.has(fn)) continue;
|
|
267
|
-
memos.delete(fn);
|
|
268
|
-
disposeOwner(node);
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
}
|
|
273
|
-
/**
|
|
274
235
|
* Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an
|
|
275
236
|
* array with accessor members) runs inside a render effect, so its reads are tracked. Anything
|
|
276
237
|
* else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps
|
|
@@ -287,11 +248,31 @@ function bindRegion(region, value, ordered) {
|
|
|
287
248
|
useRenderEffect(typeof value === "function" ? value : () => value, (raw) => {
|
|
288
249
|
latest = raw;
|
|
289
250
|
if (containsFunction(raw)) {
|
|
290
|
-
const
|
|
251
|
+
const owner = currentOwner();
|
|
252
|
+
const memos = /* @__PURE__ */ new Map();
|
|
253
|
+
let touched = /* @__PURE__ */ new Set();
|
|
254
|
+
const call = (fn) => {
|
|
255
|
+
touched.add(fn);
|
|
256
|
+
let node = memos.get(fn);
|
|
257
|
+
if (node === void 0) {
|
|
258
|
+
node = createComputation({
|
|
259
|
+
kind: "memo",
|
|
260
|
+
fn: () => fn(),
|
|
261
|
+
allowWrites: true,
|
|
262
|
+
owner
|
|
263
|
+
});
|
|
264
|
+
memos.set(fn, node);
|
|
265
|
+
}
|
|
266
|
+
return readComputation(node);
|
|
267
|
+
};
|
|
291
268
|
useRenderEffect(() => {
|
|
292
|
-
|
|
293
|
-
const parts = flatten(raw,
|
|
294
|
-
|
|
269
|
+
touched = /* @__PURE__ */ new Set();
|
|
270
|
+
const parts = flatten(raw, call);
|
|
271
|
+
for (const [fn, node] of memos) {
|
|
272
|
+
if (touched.has(fn)) continue;
|
|
273
|
+
memos.delete(fn);
|
|
274
|
+
disposeOwner(node);
|
|
275
|
+
}
|
|
295
276
|
return parts;
|
|
296
277
|
}, (parts) => {
|
|
297
278
|
commit(region, parts);
|
|
@@ -301,6 +282,24 @@ function bindRegion(region, value, ordered) {
|
|
|
301
282
|
return latest;
|
|
302
283
|
}
|
|
303
284
|
/**
|
|
285
|
+
* Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts
|
|
286
|
+
* each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so
|
|
287
|
+
* what it shows is not built again. Only for a region without an anchor.
|
|
288
|
+
* @param region The region to move.
|
|
289
|
+
* @param parent The node that receives the region's nodes.
|
|
290
|
+
* @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).
|
|
291
|
+
* @since 1.0.3
|
|
292
|
+
* @internal
|
|
293
|
+
*/
|
|
294
|
+
function moveRegion(region, parent, move) {
|
|
295
|
+
const attached = region.nodes.filter((node) => node.parentNode === region.parent);
|
|
296
|
+
keepFocus(region.parent, () => {
|
|
297
|
+
for (const node of attached) move(node);
|
|
298
|
+
});
|
|
299
|
+
region.parent = parent;
|
|
300
|
+
region.marker = attached[0]?.previousSibling ?? parent.lastChild;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
304
303
|
* Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not
|
|
305
304
|
* touched.
|
|
306
305
|
* @internal
|
|
@@ -373,6 +372,6 @@ function insert(parent, value, anchorNode, initial) {
|
|
|
373
372
|
const resolvedAnchor = anchorNode ?? null;
|
|
374
373
|
return bindRegion(createRegion(parent, resolvedAnchor, initial === void 0 ? claims.current.takeRegion(parent, resolvedAnchor) : initial), value, resolvedAnchor === null);
|
|
375
374
|
}
|
|
376
|
-
export { anchor, bindRegion, createRegion, insert, removeRegion };
|
|
375
|
+
export { anchor, bindRegion, createRegion, insert, moveRegion, removeRegion, watchCommits };
|
|
377
376
|
|
|
378
377
|
//# sourceMappingURL=insert.js.map
|