meowjsx 0.3.0-alpha.3 → 0.3.0-alpha.5

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
@@ -32,9 +32,10 @@ It does not intercept module side effects or direct function calls, and does not
32
32
 
33
33
  ## Development metadata and instance observation
34
34
 
35
- Component functions may carry `metadata?: ComponentMetadata`. `ComponentMetadata` is an open type-extension interface; development tools register their own namespaces through declaration merging, and core does not interpret or read their tool fields.
36
- `Component<Props>` preserves this constraint, and ordinary functions can use
37
- `satisfies ComponentMetadata` to check assignment. Metadata is not part of props or component runtime options.
35
+ Development tools extend the component's `meta` through declaration merging on
36
+ `ComponentToolMeta`. Use `satisfies ComponentToolMeta` to check a tool-only annotation or
37
+ `satisfies ComponentMeta` to check an annotation with part declarations. Core treats the tool fields
38
+ as opaque.
38
39
 
39
40
  `runtime.createRenderer(strategy, { observer })` enables target-neutral instance observation:
40
41
  `onComponent(instance)` reports creation, `onUnmount(instance)` reports unmounting; the optional
@@ -78,7 +79,7 @@ if that outlet is missing or throws again, the error is reported asynchronously
78
79
  from an existing renderer are ignored. Usually one observation center is attached to one renderer; the implementation stores by instance identity and does not overwrite because different renderers have the same numeric id. `roots` may use a getter, but the scope is read and fixed when the renderer is created, suitable for tools that set the real child before creation; it is not a runtime dynamic-switch entry. Purely host or text roots
79
80
  have no component instances, and external DOM/styles, font loading and browser size changes also do not belong to this observation contract.
80
81
 
81
- MeowJSX core: the JSX/VNode factory, Signal/batch/effect, component metadata and part bindings, shadow/plugin/theme
82
+ MeowJSX core: the JSX/VNode factory, Signal/batch/effect, component metadata and part bindings, plugin/theme
82
83
  contracts, lifecycle and context, and the target-neutral renderer seam (`RenderStrategy<TNode>` /
83
84
  `createRenderer()`). Core does not know the target platform.
84
85
 
@@ -91,7 +92,7 @@ meowjsx (this package: core + JSX contract)
91
92
 
92
93
  ## Exports
93
94
 
94
- - `.`, `./runtime`: `h`, `Fragment`, `raw`, `createRuntime`, `defaultRuntime`, `defineShadow`,
95
+ - `.`, `./runtime`: `h`, `Fragment`, `raw`, `createRuntime`, `defaultRuntime`,
95
96
  `createThemePlugin`, part descriptor helpers, plus VNode/metadata, `Context` and generic ref types.
96
97
  Existing reactive exports remain available and share the implementation below.
97
98
  - `./signal`: `signal`, `batch`, `mapSignal`, `derived`, `isSignal`, `unwrap`, and the
@@ -108,7 +109,7 @@ meowjsx (this package: core + JSX contract)
108
109
  render hooks, overrides and `key`/`componentPart` identity; the target only implements node and attribute placement.
109
110
  - `./jsx-runtime`: `jsx`/`jsxs`/`jsxDEV`/`Fragment`.
110
111
  - `./jsx-dev-runtime`: the `jsxDEV`/`Fragment` needed by development automatic JSX, reusing the same implementation.
111
- - `./web`: DOM mount, static HTML, Web shadow, instance-observation sources and skeleton visual controls.
112
+ - `./web`: DOM mount, static HTML, instance-observation sources and skeleton visual controls.
112
113
  - `./json`: finite descriptions, host binding/action references, single-source metadata validation and catalog descriptions; see [JSON entry](JSON.md).
113
114
  - `Runtime.targetHooks`: when the target owns the output path (Web's static HTML), reuse the runtime's
114
115
  component calls, render hooks and override semantics instead of copying a set into the target.
@@ -116,12 +117,26 @@ meowjsx (this package: core + JSX contract)
116
117
  The core root has no `render`/`renderToHtml`: `render(node, Element)` and HTML serialization are imported from
117
118
  `meowjsx/web`. The root does not import Web back; both use the same core module, and multiple explicit Runtimes can still be created independently.
118
119
 
119
- ### API migration
120
+ For an attribute that refers to a sibling part's ID, `deferStaticAttribute(signal)` lets the HTML
121
+ renderer read the current value after all components in that render have run. In mounted Web
122
+ views it stays a normal Signal binding.
123
+
124
+ ### Component metadata and replacements
125
+
126
+ Declare component parts on the function's `meta`. MeowJSX reads this metadata when it first
127
+ encounters the component. Within one runtime, distinct functions with the same name and distinct
128
+ parts with the same `data-slot` value cause an error. Tool packages can augment `ComponentToolMeta`
129
+ to add a namespace to the same `meta` object.
130
+
131
+ Use `runtime.replaceComponent(original, replacement)` to deliberately select a different function
132
+ at mount time. The replacement receives the original props and uses its own parts and lifecycle.
133
+ The returned cleanup removes the replacement for future mounts. A plugin can declare the same
134
+ function pairs in its `replacements` option. For mounted element behavior, compose a ref with
135
+ the part ref and return cleanup from that ref. A part that lets callers supply a component
136
+ through a render callback can forward `composePartRef(part)`. The outer part becomes the
137
+ element identity, and any inner part bindings are exposed as `appearanceParts` on the vnode for
138
+ style plugins (the core writes no styling attribute for them).
120
139
 
121
- - Use `defineShadow(component, part, setup)` in place of the removed `shadow` alias. It creates a
122
- definition; register it through `createRuntime({ shadows: [...] })` or a runtime plugin. Setup runs
123
- when the target mounts the matching part. Core keeps the host handle generic; `meowjsx/web` types
124
- it as `Element`.
125
140
  - Use `renderer.render(node, parent, before?)` on the target-neutral renderer and
126
141
  `web.render(node, container)` on the Web renderer. Both return an `unmount()` handle. The `mount`
127
142
  methods and top-level Web `mount` export are removed; static output remains `renderToHtml`.
@@ -138,9 +153,7 @@ bun node_modules/typescript/bin/tsc -p packages/meowjsx/tsconfig.core.json
138
153
 
139
154
  The command above runs from the repository root and only checks the DOM-free core group. The package's `bun run typecheck` runs core, renderer and Web configurations in order; the final Web group explicitly includes the DOM and is not equivalent to the DOM-free core-only check. `tsconfig.renderer.json` independently checks the target-neutral renderer seam, and behavior cases use a fake target.
140
155
 
141
- `ShadowContext.element` is the target-provided host handle, typed as generic `TNode` in core
142
- (defaults to `unknown`); the Web module narrows it to a real element. Theme contracts (`Theme`/`ThemeRule`/
143
- `ThemeStyle` and their merge rules) stay in core as planned; they carry values only and touch no style API.
156
+ Theme contracts (`Theme`/`ThemeRule`/`ThemeStyle`) carry values and do not touch a style API.
144
157
 
145
158
  ## Class lists
146
159
 
@@ -382,7 +395,7 @@ const mounted = web.render(h("p", {}, "Hello"), document.querySelector("main")!)
382
395
  mounted.unmount();
383
396
  ```
384
397
 
385
- The Web source lives in `web/`, and DOM types only arrive through that entry. Static `renderToHtml` does not mount a DOM or run shadow;
398
+ The Web source lives in `web/`, and DOM types only arrive through that entry. Static `renderToHtml` does not mount DOM elements or invoke refs;
386
399
  `createSkeletonController` needs a real document and CSS Custom Highlight support only when called.
387
400
  Importing the module creates the default Web renderer and observation Context; it does not install styles or listeners.
388
401
  `createWebRenderer(runtime)` respects the components, themes and plugins already installed in that runtime; when an observation source is passed explicitly,
@@ -1,4 +1,4 @@
1
- export { jsonSchema, JsonViewError, describeJsonSchema, validateJsonValue } from "./schema.js";
1
+ export { cloneJsonValue, jsonSchema, JsonViewError, describeJsonSchema, validateJsonValue, } from "./schema.js";
2
2
  export type { JsonSchema, JsonValue, JsonPrimitive } from "./schema.js";
3
3
  export { defineJsonComponent, parseJsonView, createJsonView, describeJsonCatalog } from "./view.js";
4
4
  export type { JsonValueProperty, JsonActionProperty, JsonPropsDefinition, JsonComponentDefinition, JsonCatalog, JsonNode, JsonView, JsonViewOptions, } from "./view.js";
@@ -1,2 +1,2 @@
1
- export { jsonSchema, JsonViewError, describeJsonSchema, validateJsonValue } from "./schema.js";
1
+ export { cloneJsonValue, jsonSchema, JsonViewError, describeJsonSchema, validateJsonValue, } from "./schema.js";
2
2
  export { defineJsonComponent, parseJsonView, createJsonView, describeJsonCatalog } from "./view.js";
@@ -1,27 +1,37 @@
1
- import type { Cleanup } from "./types.js";
1
+ import type { Cleanup, ComponentMeta } from "./types.js";
2
2
  /** An opaque component and part identity carried by a host VNode. */
3
3
  export interface PartDescriptor<Name extends string = string, Part extends string = string> {
4
4
  readonly component: Name;
5
5
  readonly part: Part;
6
- readonly state?: Readonly<Record<string, unknown>>;
6
+ readonly componentProps?: Readonly<Record<string, unknown>>;
7
7
  }
8
8
  /** Create a descriptor by stable component and part names. */
9
- export declare function createPartDescriptor<Name extends string, Part extends string>(component: Name, part: Part, state?: Readonly<Record<string, unknown>>): PartDescriptor<Name, Part>;
9
+ export declare function createPartDescriptor<Name extends string, Part extends string>(component: Name, part: Part, componentProps?: Readonly<Record<string, unknown>>, meta?: ComponentMeta): PartDescriptor<Name, Part>;
10
10
  export declare function isPartDescriptor(value: unknown): value is PartDescriptor;
11
+ export declare function getPartMeta(part: PartDescriptor): ComponentMeta | undefined;
12
+ /** The CSS slot for a component part. DOM consumers use the descriptor for identity. */
13
+ export declare function partSlot({ component, part }: PartDescriptor): string;
11
14
  export type RefCleanup = () => void | {
12
15
  readonly then?: never;
13
16
  };
14
17
  export type RefCallback<TNode> = (node: TNode) => void | RefCleanup;
15
- export type RefBinding<TNode> = RefCallback<TNode> | PartDescriptor | false | null | undefined | readonly RefBinding<TNode>[];
18
+ declare const composedPart: unique symbol;
19
+ interface ComposedPartRef {
20
+ readonly [composedPart]: PartDescriptor;
21
+ }
22
+ /** Project the enclosing part onto the element returned by a render callback. */
23
+ export declare function composePartRef(part: PartDescriptor): ComposedPartRef;
24
+ export type RefBinding<TNode> = RefCallback<TNode> | PartDescriptor | ComposedPartRef | false | null | undefined | readonly RefBinding<TNode>[];
16
25
  declare const normalizedRef: unique symbol;
17
26
  export interface NormalizedRef<TNode = unknown> {
18
27
  readonly [normalizedRef]: true;
19
28
  readonly callbacks: readonly RefCallback<TNode>[];
20
29
  }
21
- /** Flatten composed refs and resolve the single host part identity before hooks. */
30
+ /** Flatten refs and resolve the outermost explicitly composed part before hooks. */
22
31
  export declare function normalizeRefBinding<TNode>(value: unknown): {
23
32
  readonly ref?: NormalizedRef<TNode>;
24
33
  readonly part?: PartDescriptor;
34
+ readonly appearanceParts?: readonly PartDescriptor[];
25
35
  };
26
36
  export declare function isNormalizedRef(value: unknown): value is NormalizedRef;
27
37
  /** Invoke callbacks in order and release their successful cleanups in reverse order. */
package/dist/src/parts.js CHANGED
@@ -1,22 +1,42 @@
1
1
  const descriptors = new WeakSet();
2
+ const metadata = new WeakMap();
2
3
  /** Create a descriptor by stable component and part names. */
3
- export function createPartDescriptor(component, part, state) {
4
+ export function createPartDescriptor(component, part, componentProps, meta) {
4
5
  const descriptor = Object.freeze({
5
6
  component,
6
7
  part,
7
- ...(state === undefined ? {} : { state }),
8
+ ...(componentProps === undefined ? {} : { componentProps }),
8
9
  });
9
10
  descriptors.add(descriptor);
11
+ if (meta)
12
+ metadata.set(descriptor, meta);
10
13
  return descriptor;
11
14
  }
12
15
  export function isPartDescriptor(value) {
13
16
  return typeof value === "object" && value !== null && descriptors.has(value);
14
17
  }
18
+ export function getPartMeta(part) {
19
+ return metadata.get(part);
20
+ }
21
+ /** The CSS slot for a component part. DOM consumers use the descriptor for identity. */
22
+ export function partSlot({ component, part }) {
23
+ return part === "root"
24
+ ? component
25
+ : `${component}-${part.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}`;
26
+ }
27
+ const composedPart = Symbol("meowjsx.composedPart");
28
+ /** Project the enclosing part onto the element returned by a render callback. */
29
+ export function composePartRef(part) {
30
+ if (!isPartDescriptor(part))
31
+ throw new Error("meowjsx cannot compose an invalid part descriptor");
32
+ return Object.freeze({ [composedPart]: part });
33
+ }
15
34
  const normalizedRef = Symbol("meowjsx.normalized-ref");
16
- /** Flatten composed refs and resolve the single host part identity before hooks. */
35
+ /** Flatten refs and resolve the outermost explicitly composed part before hooks. */
17
36
  export function normalizeRefBinding(value) {
18
37
  const callbacks = [];
19
38
  let part;
39
+ const projected = [];
20
40
  const visit = (entry) => {
21
41
  if (entry === undefined || entry === null || entry === false)
22
42
  return;
@@ -28,10 +48,14 @@ export function normalizeRefBinding(value) {
28
48
  if (isPartDescriptor(entry)) {
29
49
  if (part && (part.component !== entry.component || part.part !== entry.part))
30
50
  throw new Error("meowjsx host refs cannot bind multiple distinct parts");
31
- if (!part || (part.state === undefined && entry.state !== undefined))
51
+ if (!part || (part.componentProps === undefined && entry.componentProps !== undefined))
32
52
  part = entry;
33
53
  return;
34
54
  }
55
+ if (typeof entry === "object" && Object.hasOwn(entry, composedPart)) {
56
+ projected.push(entry[composedPart]);
57
+ return;
58
+ }
35
59
  if (typeof entry === "function") {
36
60
  callbacks.push(entry);
37
61
  return;
@@ -39,6 +63,16 @@ export function normalizeRefBinding(value) {
39
63
  throw new Error("meowjsx ref bindings must be callbacks, part descriptors, or nested arrays");
40
64
  };
41
65
  visit(value);
66
+ const primary = projected.at(-1) ?? part;
67
+ const appearance = new Map();
68
+ if (primary && projected.length) {
69
+ const primarySlot = partSlot(primary);
70
+ for (const candidate of part ? [part, ...projected] : projected) {
71
+ const slot = partSlot(candidate);
72
+ if (slot !== primarySlot)
73
+ appearance.set(slot, candidate);
74
+ }
75
+ }
42
76
  return {
43
77
  ...(callbacks.length > 0
44
78
  ? {
@@ -48,7 +82,8 @@ export function normalizeRefBinding(value) {
48
82
  }),
49
83
  }
50
84
  : {}),
51
- ...(part ? { part } : {}),
85
+ ...(primary ? { part: primary } : {}),
86
+ ...(appearance.size ? { appearanceParts: Object.freeze([...appearance.values()]) } : {}),
52
87
  };
53
88
  }
54
89
  export function isNormalizedRef(value) {
@@ -1,4 +1,4 @@
1
- import type { AnyShadowDefinition, Child, Cleanup, Component, ComponentMeta, ComponentRegistry, ComponentRenderContext, CreateContext, CreateHook, LifecycleScope, Props, RegisteredComponent, RenderHook, ResolveComponentHook, PrepareContainerHook, Runtime, RuntimePluginEnforce, ShadowRegistry, VNode } from "./types.js";
1
+ import type { Child, Cleanup, Component, ComponentMeta, ComponentRenderContext, CreateContext, CreateHook, LifecycleScope, Props, RenderHook, ResolveComponentHook, PrepareContainerHook, Runtime, RuntimePluginEnforce, VNode } from "./types.js";
2
2
  import { type ContextScope } from "./context.js";
3
3
  export interface HookEntry<Hook> {
4
4
  readonly handler: Hook;
@@ -9,13 +9,11 @@ export interface RuntimeState {
9
9
  renderHooks: HookEntry<RenderHook>[];
10
10
  resolveComponentHooks: HookEntry<ResolveComponentHook>[];
11
11
  containerHooks: HookEntry<PrepareContainerHook>[];
12
- shadowRegistry: ShadowRegistry;
13
12
  overrides: Map<string, Component<any>>;
14
13
  }
15
14
  export declare function addHook<Hook>(hooks: HookEntry<Hook>[], handler: Hook, enforce: RuntimePluginEnforce | undefined): HookEntry<Hook>;
16
15
  export declare function removeHook<Hook>(hooks: HookEntry<Hook>[], entry: HookEntry<Hook>): void;
17
- export declare function createComponentRegistry(initial: readonly RegisteredComponent[]): ComponentRegistry;
18
- export declare function createShadowRegistry(initial?: readonly AnyShadowDefinition[]): ShadowRegistry;
16
+ export declare function createComponentNames(): (component: Component<any, any>, original?: Component<any, any>) => void;
19
17
  export declare function createComponentContext<Meta extends ComponentMeta, PropsType extends object>(runtime: Runtime, component: Component<PropsType, Meta>, props: PropsType, scope: LifecycleScope): ComponentRenderContext<Meta, PropsType>;
20
18
  interface ComponentInvocation {
21
19
  child: Child;
@@ -1,4 +1,4 @@
1
- import { createPartDescriptor, normalizeRefBinding, isNormalizedRef } from "./parts.js";
1
+ import { createPartDescriptor, normalizeRefBinding, isNormalizedRef, partSlot } from "./parts.js";
2
2
  import { contextScopeForProvider, runComponentBody } from "./context.js";
3
3
  import { createLifecycleScope } from "./lifecycle.js";
4
4
  export function addHook(hooks, handler, enforce) {
@@ -27,63 +27,46 @@ export function removeHook(hooks, entry) {
27
27
  if (index >= 0)
28
28
  hooks.splice(index, 1);
29
29
  }
30
- export function createComponentRegistry(initial) {
31
- const components = new Map();
32
- const register = (component) => {
30
+ export function createComponentNames() {
31
+ const names = new Map();
32
+ const slots = new Map();
33
+ const checked = new WeakSet();
34
+ return (component, original = component) => {
33
35
  const meta = component.meta;
34
- if (!meta?.name.trim())
35
- throw new Error("meowjsx components need a nonempty meta.name");
36
- if (!Array.isArray(meta.parts) || new Set(meta.parts).size !== meta.parts.length)
37
- throw new Error(`meowjsx component ${meta.name} needs unique meta.parts`);
38
- if (meta.parts.some((part) => typeof part !== "string" || !part.trim()))
39
- throw new Error(`meowjsx component ${meta.name} has an invalid meta.parts entry`);
40
- const previous = components.get(meta.name);
41
- components.set(meta.name, component);
42
- let active = true;
43
- return () => {
44
- if (!active)
45
- return;
46
- active = false;
47
- if (components.get(meta.name) !== component)
48
- return;
49
- if (previous)
50
- components.set(meta.name, previous);
51
- else
52
- components.delete(meta.name);
53
- };
54
- };
55
- for (const component of initial)
56
- register(component);
57
- return {
58
- register,
59
- get: (name) => components.get(name),
60
- has: (name) => components.has(name),
61
- list: () => [...components.values()],
62
- };
63
- }
64
- export function createShadowRegistry(initial = []) {
65
- const shadows = [];
66
- const register = (shadow) => {
67
- shadows.push(shadow);
68
- let active = true;
69
- return () => {
70
- if (!active)
71
- return;
72
- active = false;
73
- const index = shadows.lastIndexOf(shadow);
74
- if (index >= 0)
75
- shadows.splice(index, 1);
76
- };
36
+ if (!meta?.name && !meta?.parts)
37
+ return;
38
+ if (!meta.name?.trim())
39
+ throw new Error("meowjsx components with parts need a nonempty meta.name");
40
+ const owner = original.meta?.name === meta.name ? original : component;
41
+ const existing = names.get(meta.name);
42
+ if (existing && existing !== owner)
43
+ throw new Error(`meowjsx component name ${meta.name} is already in use`);
44
+ if (checked.has(component))
45
+ return;
46
+ const declared = new Map();
47
+ for (const part of meta.parts ?? []) {
48
+ if (typeof part !== "string" || !part.trim())
49
+ throw new Error(`meowjsx component ${meta.name} has an invalid meta.parts entry`);
50
+ const slot = partSlot({ component: meta.name, part });
51
+ const identity = `${meta.name}/${part}`;
52
+ if (declared.has(slot) || (slots.has(slot) && slots.get(slot) !== identity))
53
+ throw new Error(`meowjsx components share data-slot ${slot}`);
54
+ declared.set(slot, identity);
55
+ }
56
+ for (const [slot, identity] of declared)
57
+ slots.set(slot, identity);
58
+ names.set(meta.name, owner);
59
+ checked.add(component);
77
60
  };
78
- for (const shadow of initial)
79
- register(shadow);
80
- return { register, list: () => [...shadows] };
81
61
  }
82
62
  export function createComponentContext(runtime, component, props, scope) {
83
- const meta = component.meta ?? { name: "anonymous", parts: [] };
63
+ const annotation = component.meta;
64
+ const meta = (annotation?.parts
65
+ ? annotation
66
+ : { ...annotation, name: annotation?.name ?? "anonymous", parts: [] });
84
67
  const bindings = Object.create(null);
85
68
  for (const part of meta.parts)
86
- bindings[part] = createPartDescriptor(meta.name, part, props);
69
+ bindings[part] = createPartDescriptor(meta.name, part, props, meta);
87
70
  return {
88
71
  ...scope,
89
72
  component: meta,
@@ -157,15 +140,13 @@ export function normalizeHostVNode(vnode) {
157
140
  if (current &&
158
141
  (current.component !== normalized.part.component || current.part !== normalized.part.part))
159
142
  throw new Error("meowjsx host refs cannot bind multiple distinct parts");
143
+ props["data-slot"] = partSlot(normalized.part);
160
144
  return {
161
145
  ...vnode,
162
146
  raw: true,
163
147
  props,
164
- componentPart: {
165
- component: normalized.part.component,
166
- part: normalized.part.part,
167
- state: normalized.part.state,
168
- },
148
+ componentPart: normalized.part,
149
+ ...(normalized.appearanceParts ? { appearanceParts: normalized.appearanceParts } : {}),
169
150
  };
170
151
  }
171
152
  export { isNormalizedRef, isPartDescriptor, mountRefBindings } from "./parts.js";
@@ -1,7 +1,7 @@
1
1
  import type { ContextScope } from "./context.js";
2
2
  import { type KeyedChild } from "./keyed.js";
3
3
  export { createComponentObservation, type ComponentObservation, type ComponentObservationOptions, } from "./observation.js";
4
- import type { ComponentMeta, ComponentMetadata } from "./types.js";
4
+ import type { ComponentAnnotation } from "./types.js";
5
5
  /** A target-owned cleanup operation. */
6
6
  export type RendererCleanup = () => void;
7
7
  /**
@@ -24,13 +24,12 @@ export type RenderableProps = Record<string, unknown> & {
24
24
  */
25
25
  export type RenderableComponent = {
26
26
  (...args: never[]): RenderableChild;
27
- readonly meta?: ComponentMeta;
28
- metadata?: ComponentMetadata;
27
+ readonly meta?: ComponentAnnotation;
29
28
  };
30
29
  export interface RenderableComponentPart {
31
30
  readonly component: string;
32
31
  readonly part: string;
33
- readonly state?: Readonly<Record<string, unknown>>;
32
+ readonly componentProps?: Readonly<Record<string, unknown>>;
34
33
  }
35
34
  export interface RenderableVNode {
36
35
  readonly type: string | RenderableComponent;
@@ -38,6 +37,7 @@ export interface RenderableVNode {
38
37
  readonly key?: string | number;
39
38
  readonly raw?: boolean;
40
39
  readonly componentPart?: RenderableComponentPart;
40
+ readonly appearanceParts?: readonly RenderableComponentPart[];
41
41
  }
42
42
  /**
43
43
  * The platform boundary for MeowJSX rendering.
@@ -54,6 +54,7 @@ export interface RenderStrategy<TNode> {
54
54
  insert(parent: TNode, node: TNode, before?: TNode | null): void;
55
55
  remove(node: TNode): void;
56
56
  setProperty(node: TNode, name: string, value: unknown): void | RendererCleanup;
57
+ bindPart?(node: TNode, part: RenderableComponentPart): void | RendererCleanup;
57
58
  /**
58
59
  * Optional host-node rule: return true when the target node's content comes
59
60
  * from the node itself instead of mounted children (the Web target's raw
@@ -497,6 +497,8 @@ export function createRenderer(strategy, options = {}) {
497
497
  let childrenMount;
498
498
  let observed = false;
499
499
  try {
500
+ if (vnode.componentPart && strategy.bindPart)
501
+ propertyCleanups.push(cleanupResult(strategy.bindPart(element, vnode.componentPart)));
500
502
  for (const [name, prop] of Object.entries(vnode.props)) {
501
503
  if (name === "children" || name === "key")
502
504
  continue;
@@ -1,20 +1,15 @@
1
1
  export { createContext, useContext, type ContextScope, type ContextValue } from "./context.js";
2
2
  export { keyed, type KeyedChild } from "./keyed.js";
3
- export { createPartDescriptor, isPartDescriptor } from "./parts.js";
3
+ export { composePartRef, createPartDescriptor, getPartMeta, isPartDescriptor, partSlot, } from "./parts.js";
4
4
  export type { PartDescriptor, RefBinding, RefCallback, RefCleanup } from "./parts.js";
5
- import type { Child, Cleanup, ComponentMeta, Component, HFactory, ShadowDefinition, ShadowSetup, FragmentComponent, Props, Runtime, RuntimeOptions, RuntimePluginOption, VNode } from "./types.js";
6
- export type { Child, ClassValue, Cleanup, Component, ComponentMeta, ComponentMetadata, ComponentPartRef, ComponentRegistry, ComponentRegistryMap, ComponentRenderContext, Context, CreateContext, CreateHook, Effect, ElementType, FragmentComponent, Key, LifecycleScope, MaybeSignal, MountResult, PrepareContainerHook, Props, ReadableSignal, RegisteredComponent, RegisteredComponentName, RegisteredComponentPart, RenderContext, RenderHook, ResolveComponentContext, ResolveComponentHook, Runtime, ContainerContext, RuntimeOptions, RuntimePlugin, RuntimePluginContext, RuntimePluginEnforce, RuntimePluginOption, RuntimePluginSetup, RuntimeRendererOptions, RuntimeTargetHooks, ShadowContext, ShadowDefinition, ShadowRegistry, ShadowSetup, Signal, StyleObject, StyleScalar, StyleValue, Theme, ThemeContext, ThemeRule, ThemeRules, ThemeStyle, VNode, WritableSignal, } from "./types.js";
5
+ import type { Child, Cleanup, HFactory, FragmentComponent, Props, Runtime, RuntimeOptions, RuntimePluginOption, VNode } from "./types.js";
6
+ export type { Child, ClassValue, Cleanup, Component, ComponentMeta, ComponentAnnotation, ComponentToolMeta, ComponentReplacement, ComponentPartRef, ComponentRegistryMap, ComponentRenderContext, Context, CreateContext, CreateHook, Effect, ElementType, FragmentComponent, Key, LifecycleScope, MaybeSignal, MountResult, PrepareContainerHook, Props, ReadableSignal, RegisteredComponent, RegisteredComponentName, RegisteredComponentPart, RenderContext, RenderHook, ResolveComponentContext, ResolveComponentHook, Runtime, ContainerContext, RuntimeOptions, RuntimePlugin, RuntimePluginContext, RuntimePluginEnforce, RuntimePluginOption, RuntimePluginSetup, RuntimeRendererOptions, RuntimeTargetHooks, Signal, StyleObject, StyleScalar, StyleValue, Theme, ThemeContext, ThemeRule, ThemeRules, ThemeStyle, VNode, WritableSignal, } from "./types.js";
7
7
  export { batch, isAsyncIterable, isPromiseLike, derived, isSignal, mapSignal, signal, unwrap, } from "./reactive.js";
8
8
  export { createLifecycleScope } from "./lifecycle.js";
9
9
  export { createThemePlugin, styleText } from "./style.js";
10
- export declare function defineShadow<C extends Component<any, any> & {
11
- readonly meta: ComponentMeta;
12
- }, Part extends C["meta"]["parts"][number], TNode = unknown>(component: C, part: Part, setup: ShadowSetup<Parameters<C>[0], C["meta"]["name"], Part, TNode>): ShadowDefinition<Parameters<C>[0], C["meta"]["name"], C["meta"]["parts"][number], Part, TNode>;
13
10
  export declare function createRuntime(options?: RuntimeOptions): Runtime;
14
11
  export declare const defaultRuntime: Runtime;
15
- export declare const registry: import("./types.js").ComponentRegistry;
16
12
  export declare const h: HFactory;
17
13
  export declare const raw: (type: string, props: Props | null, ...children: Child[]) => VNode;
18
14
  export declare const Fragment: FragmentComponent;
19
- export declare const registerComponent: (component: import("./types.js").RegisteredComponent) => () => void;
20
15
  export declare function useRuntime(plugin: RuntimePluginOption): Cleanup;
@@ -1,9 +1,9 @@
1
1
  export { createContext, useContext } from "./context.js";
2
2
  export { keyed } from "./keyed.js";
3
- export { createPartDescriptor, isPartDescriptor } from "./parts.js";
3
+ export { composePartRef, createPartDescriptor, getPartMeta, isPartDescriptor, partSlot, } from "./parts.js";
4
4
  import { isContextProvider } from "./context.js";
5
5
  import { createRenderer as createTargetRenderer, } from "./renderer.js";
6
- import { addHook, createBaseVNode, createComponentRegistry, createShadowRegistry, invokeComponent, removeHook, runCreateHooks, runRenderHooks, normalizeHostVNode, } from "./registry.js";
6
+ import { addHook, createBaseVNode, createComponentNames, invokeComponent, removeHook, runCreateHooks, runRenderHooks, normalizeHostVNode, } from "./registry.js";
7
7
  import { disposeCleanups } from "./lifecycle.js";
8
8
  export { batch, isAsyncIterable, isPromiseLike, derived, isSignal, mapSignal, signal, unwrap, } from "./reactive.js";
9
9
  export { createLifecycleScope } from "./lifecycle.js";
@@ -17,27 +17,30 @@ function replacementFor(state, node) {
17
17
  return undefined;
18
18
  return state.overrides.get(node.type);
19
19
  }
20
- export function defineShadow(component, part, setup) {
21
- const meta = component.meta;
22
- if (!meta.parts.includes(part))
23
- throw new Error(`meowjsx shadow ${meta.name}.${String(part)} is not declared in component metadata`);
24
- return {
25
- name: `meowjsx-shadow:${meta.name}/${String(part)}`,
26
- component,
27
- part,
28
- setup,
29
- };
30
- }
31
20
  export function createRuntime(options = {}) {
32
21
  const state = {
33
22
  createHooks: [],
34
23
  renderHooks: [],
35
24
  resolveComponentHooks: [],
36
25
  containerHooks: [],
37
- shadowRegistry: createShadowRegistry(options.shadows),
38
26
  overrides: new Map(Object.entries(options.overrides ?? {})),
39
27
  };
40
- const registry = createComponentRegistry(options.components ?? []);
28
+ const validateComponent = createComponentNames();
29
+ const replacements = new Map();
30
+ const replaceComponent = (component, replacement) => {
31
+ if (replacements.has(component))
32
+ throw new Error(`meowjsx already has a replacement for ${component.meta?.name ?? component.name}`);
33
+ replacements.set(component, replacement);
34
+ let active = true;
35
+ return () => {
36
+ if (!active)
37
+ return;
38
+ active = false;
39
+ replacements.delete(component);
40
+ };
41
+ };
42
+ for (const entry of options.replacements ?? [])
43
+ replaceComponent(entry.component, entry.replacement);
41
44
  const runtime = {};
42
45
  // The cleanups each mount hook still owes, so uninstalling its plugin can release them.
43
46
  const activeMounts = new Map();
@@ -105,14 +108,8 @@ export function createRuntime(options = {}) {
105
108
  const entry = addHook(state.resolveComponentHooks, plugin.resolveComponent, plugin.enforce);
106
109
  contributionCleanups.push(() => removeHook(state.resolveComponentHooks, entry));
107
110
  }
108
- for (const shadow of plugin.shadows ?? []) {
109
- const disposeShadow = state.shadowRegistry.register(shadow);
110
- contributionCleanups.push(disposeShadow);
111
- }
112
- for (const component of plugin.components ?? []) {
113
- const disposeComponent = registry.register(component);
114
- contributionCleanups.push(disposeComponent);
115
- }
111
+ for (const entry of plugin.replacements ?? [])
112
+ contributionCleanups.push(replaceComponent(entry.component, entry.replacement));
116
113
  for (const [name, replacement] of Object.entries(plugin.overrides ?? {})) {
117
114
  previousOverrides.set(name, state.overrides.get(name));
118
115
  state.overrides.set(name, replacement);
@@ -128,8 +125,6 @@ export function createRuntime(options = {}) {
128
125
  }
129
126
  const setupCleanup = plugin.setup?.({
130
127
  runtime,
131
- registry,
132
- shadowRegistry: state.shadowRegistry,
133
128
  onCleanup: registerPluginCleanup,
134
129
  });
135
130
  if (setupCleanup)
@@ -189,14 +184,18 @@ export function createRuntime(options = {}) {
189
184
  fragments.add(Fragment);
190
185
  const targetHooks = {
191
186
  invokeComponent(component, props, contextScope) {
192
- let selected = component;
193
- for (const entry of state.resolveComponentHooks) {
187
+ const declared = replacements.get(component);
188
+ let selected = declared ?? component;
189
+ for (const entry of declared ? [] : state.resolveComponentHooks) {
194
190
  const replacement = entry.handler({ component, props, runtime });
195
191
  if (replacement !== undefined) {
196
192
  selected = replacement;
197
193
  break;
198
194
  }
199
195
  }
196
+ validateComponent(component);
197
+ if (selected !== component)
198
+ validateComponent(selected, component);
200
199
  return {
201
200
  ...invokeComponent(selected, props, runtime, contextScope),
202
201
  component: selected,
@@ -248,17 +247,6 @@ export function createRuntime(options = {}) {
248
247
  },
249
248
  };
250
249
  const createRenderer = (strategy, rendererOptions = {}) => {
251
- const defaultOnMount = (vnode) => {
252
- const identity = vnode.componentPart;
253
- if (!identity || !registry.has(identity.component))
254
- return;
255
- const hasShadow = state.shadowRegistry.list().some((shadow) => {
256
- return shadow.component.meta.name === identity.component && shadow.part === identity.part;
257
- });
258
- if (hasShadow) {
259
- throw new Error(`meowjsx target renderer needs an onMount hook for shadow ${identity.component}.${identity.part}`);
260
- }
261
- };
262
250
  return createTargetRenderer(strategy, {
263
251
  invokeComponent(component, props, contextScope) {
264
252
  const invocation = targetHooks.invokeComponent(component, props, contextScope);
@@ -276,33 +264,18 @@ export function createRuntime(options = {}) {
276
264
  replacementFor(vnode) {
277
265
  return targetHooks.replacementFor(vnode);
278
266
  },
279
- onMount: rendererOptions.onMount ?? defaultOnMount,
267
+ onMount: rendererOptions.onMount,
280
268
  onError: rendererOptions.onError,
281
269
  observer: rendererOptions.observer,
282
270
  });
283
271
  };
284
- const registerShadows = (shadows) => {
285
- const disposals = shadows.map((shadow) => state.shadowRegistry.register(shadow));
286
- let active = true;
287
- return () => {
288
- if (!active)
289
- return;
290
- active = false;
291
- for (const dispose of disposals.reverse())
292
- dispose();
293
- };
294
- };
295
272
  Object.assign(runtime, {
296
- registry,
297
- shadowRegistry: state.shadowRegistry,
298
273
  h,
299
274
  raw,
300
275
  Fragment,
301
276
  targetHooks,
302
277
  createRenderer,
303
- registerComponent: registry.register,
304
- registerShadow: state.shadowRegistry.register,
305
- registerShadows,
278
+ replaceComponent,
306
279
  use,
307
280
  });
308
281
  for (const plugin of options.plugins ?? [])
@@ -315,11 +288,9 @@ export const defaultRuntime = /* @__PURE__ */ createRuntime();
315
288
  function defaultMember(key) {
316
289
  return defaultRuntime[key];
317
290
  }
318
- export const registry = /* @__PURE__ */ defaultMember("registry");
319
291
  export const h = /* @__PURE__ */ defaultMember("h");
320
292
  export const raw = /* @__PURE__ */ defaultMember("raw");
321
293
  export const Fragment = /* @__PURE__ */ defaultMember("Fragment");
322
- export const registerComponent = /* @__PURE__ */ defaultMember("registerComponent");
323
294
  export function useRuntime(plugin) {
324
295
  return defaultRuntime.use(plugin);
325
296
  }
package/dist/src/style.js CHANGED
@@ -167,17 +167,19 @@ export function createThemePlugin(theme) {
167
167
  return {
168
168
  name: theme.name,
169
169
  render: (context, next) => {
170
- const identity = context.vnode.componentPart;
171
- if (!identity || !context.runtime.registry.has(identity.component))
172
- return next(context.vnode);
173
- const style = theme.resolve({
174
- component: identity,
175
- vnode: context.vnode,
176
- runtime: context.runtime,
177
- });
178
- if (!style)
179
- return next(context.vnode);
180
- return next({ ...context.vnode, props: applyThemeStyle(context.vnode.props, style) });
170
+ const { vnode, runtime } = context;
171
+ if (!vnode.componentPart)
172
+ return next(vnode);
173
+ const identities = vnode.appearanceParts
174
+ ? [...vnode.appearanceParts, vnode.componentPart]
175
+ : [vnode.componentPart];
176
+ let props = vnode.props;
177
+ for (const component of identities) {
178
+ const style = theme.resolve({ component, vnode, runtime });
179
+ if (style)
180
+ props = applyThemeStyle(props, style);
181
+ }
182
+ return next(props === vnode.props ? vnode : { ...vnode, props });
181
183
  },
182
184
  };
183
185
  }
@@ -28,25 +28,24 @@ export type Props = {
28
28
  /** Open type-level registry for application component name completion. */
29
29
  export interface ComponentRegistryMap {
30
30
  }
31
- /** Open development-tool metadata; namespace owners extend this interface. */
32
- export interface ComponentMetadata {
31
+ /** Open namespace for development tools on a component's `meta`. */
32
+ export interface ComponentToolMeta {
33
33
  }
34
34
  export type RegisteredComponentName = Extract<keyof ComponentRegistryMap, string>;
35
35
  export type RegisteredComponentPart<Name extends string> = Name extends keyof ComponentRegistryMap ? ComponentRegistryMap[Name] extends {
36
36
  parts: infer Part extends string;
37
37
  } ? Part : string : string;
38
- export interface ComponentMeta<Name extends string = string, Parts extends readonly string[] = readonly string[], Style = unknown> {
38
+ export interface ComponentMeta<Name extends string = string, Parts extends readonly string[] = readonly string[], Style = unknown> extends ComponentToolMeta {
39
39
  readonly name: Name;
40
40
  readonly parts: Parts;
41
41
  readonly style?: Style;
42
42
  }
43
+ export type ComponentAnnotation<Meta extends ComponentMeta = ComponentMeta> = Meta | (ComponentToolMeta & {
44
+ readonly name?: string;
45
+ readonly parts?: undefined;
46
+ readonly style?: undefined;
47
+ });
43
48
  export type ComponentPartRef<Name extends string = string, Part extends string = string> = PartDescriptor<Name, Part>;
44
- export interface ComponentRegistry {
45
- register(component: RegisteredComponent): () => void;
46
- get(name: string): RegisteredComponent | undefined;
47
- has(name: string): boolean;
48
- list(): readonly RegisteredComponent[];
49
- }
50
49
  export interface LifecycleScope {
51
50
  readonly runtime: Runtime;
52
51
  effect(run: Effect): Cleanup;
@@ -62,8 +61,7 @@ export interface ComponentRenderContext<Meta extends ComponentMeta = ComponentMe
62
61
  }
63
62
  export type Component<PropsType extends object = Props, Meta extends ComponentMeta = ComponentMeta> = {
64
63
  (props: PropsType, context: ComponentRenderContext<Meta, PropsType>): Child;
65
- readonly meta?: Meta;
66
- metadata?: ComponentMetadata;
64
+ readonly meta?: ComponentAnnotation<Meta>;
67
65
  };
68
66
  export type RegisteredComponent = Component<any, any> & {
69
67
  readonly meta: ComponentMeta;
@@ -89,24 +87,6 @@ export interface ThemeContext {
89
87
  export type ThemeRule<Name extends string = string, Part extends string = string> = ThemeStyle | ((context: ThemeContext & {
90
88
  component: ComponentPartRef<Name, Part>;
91
89
  }) => ThemeStyle | null | undefined);
92
- export interface ShadowContext<PropsType extends object = Props, Name extends string = string, Part extends string = string, TNode = unknown> extends LifecycleScope {
93
- readonly component: ComponentPartRef<Name, Part>;
94
- readonly props: PropsType;
95
- readonly vnode: VNode;
96
- readonly element: TNode;
97
- }
98
- export interface ShadowDefinition<PropsType extends object = any, Name extends string = string, AllPart extends string = string, Part extends AllPart = AllPart, TNode = unknown> {
99
- readonly name: string;
100
- readonly component: RegisteredComponent;
101
- readonly part: Part;
102
- readonly setup: ShadowSetup<PropsType, Name, Part, TNode>;
103
- }
104
- export type AnyShadowDefinition = ShadowDefinition<any, any, any, any, any>;
105
- export type ShadowSetup<PropsType extends object = Props, Name extends string = string, Part extends string = string, TNode = unknown> = (props: PropsType, context: ShadowContext<PropsType, Name, Part, TNode>) => void | Cleanup;
106
- export interface ShadowRegistry {
107
- register(shadow: AnyShadowDefinition): Cleanup;
108
- list(): readonly AnyShadowDefinition[];
109
- }
110
90
  export type ThemeRules = {
111
91
  [Name in RegisteredComponentName]?: {
112
92
  [Part in RegisteredComponentPart<Name>]?: ThemeRule<Name, Part>;
@@ -122,6 +102,7 @@ export interface VNode {
122
102
  key?: Key;
123
103
  raw?: boolean;
124
104
  componentPart?: ComponentPartRef;
105
+ appearanceParts?: readonly ComponentPartRef[];
125
106
  }
126
107
  export interface CreateContext {
127
108
  type: ElementType;
@@ -142,11 +123,13 @@ export interface ResolveComponentContext {
142
123
  readonly runtime: Runtime;
143
124
  }
144
125
  export type ResolveComponentHook = (context: ResolveComponentContext) => Component<any, any> | undefined;
126
+ export interface ComponentReplacement {
127
+ readonly component: Component<any, any>;
128
+ readonly replacement: Component<any, any>;
129
+ }
145
130
  export type RuntimePluginEnforce = "pre" | "post";
146
131
  export interface RuntimePluginContext {
147
132
  readonly runtime: Runtime;
148
- readonly registry: ComponentRegistry;
149
- readonly shadowRegistry: ShadowRegistry;
150
133
  onCleanup(cleanup: Cleanup): void;
151
134
  }
152
135
  export type RuntimePluginSetup = (context: RuntimePluginContext) => void | Cleanup;
@@ -172,16 +155,14 @@ export type RuntimePlugin = {
172
155
  resolveComponent?: ResolveComponentHook;
173
156
  /** Runs when a target renderer mounts into a container; not for static output. */
174
157
  prepareContainer?: PrepareContainerHook;
175
- shadows?: readonly AnyShadowDefinition[];
176
158
  overrides?: Record<string, Component<any>>;
177
- components?: readonly RegisteredComponent[];
159
+ replacements?: readonly ComponentReplacement[];
178
160
  };
179
161
  export type RuntimePluginOption = RuntimePlugin | readonly RuntimePluginOption[] | false | null | undefined;
180
162
  export type RuntimeOptions = {
181
163
  plugins?: readonly RuntimePluginOption[];
182
164
  overrides?: Record<string, Component<any>>;
183
- components?: readonly RegisteredComponent[];
184
- shadows?: readonly AnyShadowDefinition[];
165
+ replacements?: readonly ComponentReplacement[];
185
166
  };
186
167
  export interface MountResult {
187
168
  unmount(): void;
@@ -212,16 +193,12 @@ export type HFactory = {
212
193
  (type: string, props: Props | null, ...children: Child[]): VNode;
213
194
  };
214
195
  export interface Runtime {
215
- readonly registry: ComponentRegistry;
216
- readonly shadowRegistry: ShadowRegistry;
217
196
  readonly h: HFactory;
218
197
  readonly raw: (type: string, props: Props | null, ...children: Child[]) => VNode;
219
198
  readonly Fragment: FragmentComponent;
220
199
  readonly targetHooks: RuntimeTargetHooks;
221
200
  readonly createRenderer: <TNode>(strategy: RenderStrategy<TNode>, options?: RuntimeRendererOptions<TNode>) => TargetRenderer<TNode>;
222
- registerComponent(component: RegisteredComponent): () => void;
223
- registerShadow(shadow: AnyShadowDefinition): Cleanup;
224
- registerShadows(shadows: readonly AnyShadowDefinition[]): Cleanup;
201
+ replaceComponent<P extends object>(component: Component<P, any>, replacement: Component<NoInfer<P>, any>): Cleanup;
225
202
  use(plugin: RuntimePluginOption): Cleanup;
226
203
  }
227
204
  declare global {
@@ -0,0 +1,4 @@
1
+ import type { ReadableSignal } from "../src/signal.js";
2
+ /** Read a cross-part attribute after the static render has visited all sibling parts. */
3
+ export declare function deferStaticAttribute<T>(source: ReadableSignal<T>): ReadableSignal<T>;
4
+ export declare function isLateStaticAttribute(value: unknown): value is ReadableSignal<unknown>;
@@ -0,0 +1,17 @@
1
+ const lateAttributes = new WeakSet();
2
+ /** Read a cross-part attribute after the static render has visited all sibling parts. */
3
+ export function deferStaticAttribute(source) {
4
+ const binding = {
5
+ get value() {
6
+ return source.value;
7
+ },
8
+ subscribe(listener) {
9
+ return source.subscribe(listener);
10
+ },
11
+ };
12
+ lateAttributes.add(binding);
13
+ return binding;
14
+ }
15
+ export function isLateStaticAttribute(value) {
16
+ return typeof value === "object" && value !== null && lateAttributes.has(value);
17
+ }
@@ -2,7 +2,6 @@ import { type Child, type Runtime } from "../src/index.js";
2
2
  /**
3
3
  * Static HTML output for content and site rendering. It reuses the runtime's
4
4
  * component, hook, and override semantics through `RuntimeTargetHooks` and adds
5
- * only the HTML facts; it never mounts into a document, so registered shadows
6
- * stay mount-only.
5
+ * only the HTML facts. It never mounts into a document or invokes element refs.
7
6
  */
8
7
  export declare function renderToHtmlWithRuntime(runtime: Runtime, node: Child): string;
package/dist/web/html.js CHANGED
@@ -3,6 +3,7 @@ import { ATTRIBUTE_NAMES, VOID_ELEMENTS, isRecord } from "./html-facts.js";
3
3
  import { isKeyedChild, readKeyedEntries } from "../src/keyed.js";
4
4
  import { signal } from "../src/reactive.js";
5
5
  import { classText } from "../src/style.js";
6
+ import { isLateStaticAttribute } from "./attributes.js";
6
7
  function escapeHtml(value) {
7
8
  return value
8
9
  .replaceAll("&", "&amp;")
@@ -11,89 +12,98 @@ function escapeHtml(value) {
11
12
  .replaceAll('"', "&quot;")
12
13
  .replaceAll("'", "&#39;");
13
14
  }
14
- function renderAttributes(props) {
15
- return Object.entries(props)
16
- .filter(([name]) => {
17
- return (name !== "children" &&
18
- name !== "key" &&
19
- name !== "ref" &&
20
- name !== "dangerouslySetInnerHTML" &&
21
- !name.startsWith("on"));
22
- })
23
- .map(([name, value]) => {
24
- const resolved = unwrap(value);
25
- if (resolved === false || resolved === null || resolved === undefined)
26
- return "";
27
- const attributeName = ATTRIBUTE_NAMES[name] ?? name;
28
- if (name === "className" || name === "class") {
29
- const serialized = classText(resolved);
30
- return serialized ? ` ${attributeName}="${escapeHtml(serialized)}"` : "";
31
- }
32
- if (name === "style") {
33
- const serialized = styleText(resolved);
34
- return serialized ? ` ${attributeName}="${escapeHtml(serialized)}"` : "";
35
- }
36
- if (resolved === true)
37
- return ` ${attributeName}`;
38
- if (typeof resolved === "object")
39
- return "";
40
- return ` ${attributeName}="${escapeHtml(String(resolved))}"`;
41
- })
42
- .join("");
15
+ function renderAttribute(name, value) {
16
+ const resolved = unwrap(value);
17
+ if (resolved === false || resolved === null || resolved === undefined)
18
+ return "";
19
+ const attributeName = ATTRIBUTE_NAMES[name] ?? name;
20
+ if (name === "className" || name === "class") {
21
+ const serialized = classText(resolved);
22
+ return serialized ? ` ${attributeName}="${escapeHtml(serialized)}"` : "";
23
+ }
24
+ if (name === "style") {
25
+ const serialized = styleText(resolved);
26
+ return serialized ? ` ${attributeName}="${escapeHtml(serialized)}"` : "";
27
+ }
28
+ if (resolved === true)
29
+ return ` ${attributeName}`;
30
+ if (typeof resolved === "object")
31
+ return "";
32
+ return ` ${attributeName}="${escapeHtml(String(resolved))}"`;
43
33
  }
44
- function renderHostHtml(node, runtime, contextScope) {
34
+ function renderHostHtml(output, node, runtime, contextScope) {
45
35
  const rendered = runtime.targetHooks.transformVNode(node);
46
36
  if (typeof rendered.type === "function") {
47
- return renderChild(rendered, runtime, contextScope);
37
+ renderChild(output, rendered, runtime, contextScope);
38
+ return;
48
39
  }
49
- const attributes = renderAttributes(rendered.props);
50
- const innerHtml = unwrap(rendered.props.dangerouslySetInnerHTML);
51
- const children = isRecord(innerHtml) && typeof innerHtml.__html === "string"
52
- ? innerHtml.__html
53
- : renderChild(rendered.props.children, runtime, contextScope);
40
+ output.push(`<${rendered.type}`);
41
+ for (const [name, value] of Object.entries(rendered.props)) {
42
+ if (name === "children" ||
43
+ name === "key" ||
44
+ name === "ref" ||
45
+ name === "dangerouslySetInnerHTML" ||
46
+ name.startsWith("on"))
47
+ continue;
48
+ output.push(isLateStaticAttribute(value)
49
+ ? () => renderAttribute(name, value)
50
+ : renderAttribute(name, value));
51
+ }
52
+ output.push(">");
54
53
  if (VOID_ELEMENTS.has(rendered.type))
55
- return `<${rendered.type}${attributes}>`;
56
- return `<${rendered.type}${attributes}>${children}</${rendered.type}>`;
54
+ return;
55
+ const innerHtml = unwrap(rendered.props.dangerouslySetInnerHTML);
56
+ if (isRecord(innerHtml) && typeof innerHtml.__html === "string")
57
+ output.push(innerHtml.__html);
58
+ else
59
+ renderChild(output, rendered.props.children, runtime, contextScope);
60
+ output.push(`</${rendered.type}>`);
57
61
  }
58
- function renderComponentHtml(component, props, runtime, contextScope) {
62
+ function renderComponentHtml(output, component, props, runtime, contextScope) {
59
63
  const invocation = runtime.targetHooks.invokeComponent(component, props, contextScope);
60
64
  try {
61
- return renderChild(invocation.child, runtime, invocation.contextScope ?? contextScope);
65
+ renderChild(output, invocation.child, runtime, invocation.contextScope ?? contextScope);
62
66
  }
63
67
  finally {
64
68
  invocation.dispose();
65
69
  }
66
70
  }
67
- function renderChild(node, runtime, contextScope) {
71
+ function renderChild(output, node, runtime, contextScope) {
68
72
  if (node === null || node === undefined || typeof node === "boolean")
69
- return "";
73
+ return;
70
74
  if (isPromiseLike(node) || isAsyncIterable(node)) {
71
75
  throw new Error("meowjsx renderToHtml() cannot render async content");
72
76
  }
73
77
  if (isSignal(node))
74
- return renderChild(unwrap(node), runtime, contextScope);
75
- if (isKeyedChild(node))
76
- return readKeyedEntries(node)
77
- .map(({ value }) => renderChild(node.render(signal(value)), runtime, contextScope))
78
- .join("");
78
+ return renderChild(output, unwrap(node), runtime, contextScope);
79
+ if (isKeyedChild(node)) {
80
+ for (const { value } of readKeyedEntries(node))
81
+ renderChild(output, node.render(signal(value)), runtime, contextScope);
82
+ return;
83
+ }
79
84
  if (Array.isArray(node)) {
80
- return node.map((child) => renderChild(child, runtime, contextScope)).join("");
85
+ for (const child of node)
86
+ renderChild(output, child, runtime, contextScope);
87
+ return;
88
+ }
89
+ if (typeof node === "string" || typeof node === "number") {
90
+ output.push(escapeHtml(String(node)));
91
+ return;
81
92
  }
82
- if (typeof node === "string" || typeof node === "number")
83
- return escapeHtml(String(node));
84
93
  if (typeof node.type === "function")
85
- return renderComponentHtml(node.type, node.props, runtime, contextScope);
94
+ return renderComponentHtml(output, node.type, node.props, runtime, contextScope);
86
95
  const replacement = runtime.targetHooks.replacementFor(node);
87
96
  if (replacement)
88
- return renderComponentHtml(replacement, node.props, runtime, contextScope);
89
- return renderHostHtml(node, runtime, contextScope);
97
+ return renderComponentHtml(output, replacement, node.props, runtime, contextScope);
98
+ renderHostHtml(output, node, runtime, contextScope);
90
99
  }
91
100
  /**
92
101
  * Static HTML output for content and site rendering. It reuses the runtime's
93
102
  * component, hook, and override semantics through `RuntimeTargetHooks` and adds
94
- * only the HTML facts; it never mounts into a document, so registered shadows
95
- * stay mount-only.
103
+ * only the HTML facts. It never mounts into a document or invokes element refs.
96
104
  */
97
105
  export function renderToHtmlWithRuntime(runtime, node) {
98
- return renderChild(node, runtime);
106
+ const output = [];
107
+ renderChild(output, node, runtime);
108
+ return output.map((chunk) => (typeof chunk === "string" ? chunk : chunk())).join("");
99
109
  }
@@ -2,6 +2,7 @@ export type { WebRef, WebRefCallback, WebRefCleanup, WebHostProps, WebIntrinsicE
2
2
  export { createWebRenderer, defaultWebRenderer, render, renderToHtml, type WebRenderer, type WebRendererOptions, } from "./render.js";
3
3
  export { renderToHtmlWithRuntime } from "./html.js";
4
4
  export { useWebObservation } from "./observation.js";
5
+ export { bindElementPart, getElementPart } from "./parts.js";
6
+ export { deferStaticAttribute } from "./attributes.js";
5
7
  export { createDomStrategy, setDOMProperty, type DomNode } from "./strategy.js";
6
- export { defineShadow, runShadows } from "./shadows.js";
7
8
  export { createSkeletonController, type SkeletonOptions, type SkeletonSnapshot, type SkeletonController, } from "./skeleton.js";
package/dist/web/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { createWebRenderer, defaultWebRenderer, render, renderToHtml, } from "./render.js";
2
2
  export { renderToHtmlWithRuntime } from "./html.js";
3
3
  export { useWebObservation } from "./observation.js";
4
+ export { bindElementPart, getElementPart } from "./parts.js";
5
+ export { deferStaticAttribute } from "./attributes.js";
4
6
  export { createDomStrategy, setDOMProperty } from "./strategy.js";
5
- export { defineShadow, runShadows } from "./shadows.js";
6
7
  export { createSkeletonController, } from "./skeleton.js";
@@ -0,0 +1,5 @@
1
+ import { type PartDescriptor } from "../src/parts.js";
2
+ /** The runtime identity of a rendered part, independent of its DOM attributes. */
3
+ export declare function getElementPart(node: Node): PartDescriptor | undefined;
4
+ /** Bind an element created by a Web adapter rather than by the JSX renderer. */
5
+ export declare function bindElementPart(element: Element, part: PartDescriptor): () => void;
@@ -0,0 +1,15 @@
1
+ import { partSlot } from "../src/parts.js";
2
+ const parts = new WeakMap();
3
+ /** The runtime identity of a rendered part, independent of its DOM attributes. */
4
+ export function getElementPart(node) {
5
+ return parts.get(node);
6
+ }
7
+ /** Bind an element created by a Web adapter rather than by the JSX renderer. */
8
+ export function bindElementPart(element, part) {
9
+ element.setAttribute("data-slot", partSlot(part));
10
+ parts.set(element, part);
11
+ return () => {
12
+ if (parts.get(element) === part)
13
+ parts.delete(element);
14
+ };
15
+ }
@@ -1,7 +1,6 @@
1
1
  import { defaultRuntime, h, } from "../src/index.js";
2
2
  import { renderToHtmlWithRuntime } from "./html.js";
3
3
  import { createDomStrategy, setDOMProperty } from "./strategy.js";
4
- import { runShadows } from "./shadows.js";
5
4
  import { WebObservationContext } from "./observation.js";
6
5
  export function createWebRenderer(runtime = defaultRuntime, options = {}) {
7
6
  if (options.observation && options.observer)
@@ -11,10 +10,13 @@ export function createWebRenderer(runtime = defaultRuntime, options = {}) {
11
10
  onMount(vnode, node) {
12
11
  // A native select cannot resolve its value until its options exist.
13
12
  // The normal property subscription still handles subsequent Signal updates.
14
- if (vnode.type === "select" && Object.hasOwn(vnode.props, "value")) {
15
- setDOMProperty(node, "value", vnode.props.value);
13
+ if (vnode.type === "select") {
14
+ // An explicit `value={undefined}` means no value, like an absent prop: select the first option.
15
+ if (Object.hasOwn(vnode.props, "value") && vnode.props.value !== undefined)
16
+ setDOMProperty(node, "value", vnode.props.value);
17
+ else
18
+ resetSelectedness(node);
16
19
  }
17
- return runShadows(runtime, vnode, node);
18
20
  },
19
21
  onError: options.onError ??
20
22
  ((error) => {
@@ -58,6 +60,23 @@ export function createWebRenderer(runtime = defaultRuntime, options = {}) {
58
60
  renderToHtml: (node) => renderToHtmlWithRuntime(runtime, node),
59
61
  };
60
62
  }
63
+ /**
64
+ * Siblings mount last to first, so the browser selects a single-choice select's first inserted
65
+ * option, which is its last one. Without a host value, restore what parsing the same markup
66
+ * would select: the last `selected` option, otherwise the first enabled one.
67
+ */
68
+ function resetSelectedness(select) {
69
+ const options = Array.from(select.options ?? []);
70
+ if (select.multiple || select.size > 1) {
71
+ for (const option of options)
72
+ option.selected = option.defaultSelected;
73
+ return;
74
+ }
75
+ const chosen = options.filter((option) => option.defaultSelected).pop() ??
76
+ options.find((option) => !option.disabled);
77
+ if (chosen)
78
+ chosen.selected = true;
79
+ }
61
80
  /** The default runtime's Web renderer; apps that install into it use this one. */
62
81
  export const defaultWebRenderer = /* @__PURE__ */ createWebRenderer();
63
82
  // A pure read lets bundlers drop the default renderer when none of these members is used.
@@ -4,6 +4,7 @@ export interface SkeletonOptions {
4
4
  exclude?: readonly Element[];
5
5
  observe?: boolean;
6
6
  preserveExisting?: boolean;
7
+ colorSchemeAttribute?: string;
7
8
  observation?: {
8
9
  source: ComponentObservation<Node>;
9
10
  root?: ObservedComponent<Node>;
@@ -330,7 +330,7 @@ export function createSkeletonController(options) {
330
330
  "open",
331
331
  "disabled",
332
332
  "value",
333
- "data-meowui-color-scheme",
333
+ ...(options.colorSchemeAttribute ? [options.colorSchemeAttribute] : []),
334
334
  "data-theme",
335
335
  "color-scheme",
336
336
  ];
@@ -1,6 +1,7 @@
1
1
  import { isSignal, unwrap } from "../src/index.js";
2
2
  import { ATTRIBUTE_NAMES, HTML_NAMESPACE, SVG_NAMESPACE, isRecord } from "./html-facts.js";
3
3
  import { classText } from "../src/style.js";
4
+ import { bindElementPart } from "./parts.js";
4
5
  function setDOMStyle(element, value) {
5
6
  if (!(element instanceof HTMLElement) ||
6
7
  value === null ||
@@ -138,6 +139,9 @@ export function createDomStrategy() {
138
139
  setProperty(node, name, value) {
139
140
  return setDOMProperty(node, name, value);
140
141
  },
142
+ bindPart(node, part) {
143
+ return bindElementPart(node, part);
144
+ },
141
145
  ownsChildren(vnode) {
142
146
  return Object.hasOwn(vnode.props, "dangerouslySetInnerHTML");
143
147
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meowjsx",
3
- "version": "0.3.0-alpha.3",
3
+ "version": "0.3.0-alpha.5",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -1,15 +0,0 @@
1
- import { type Cleanup, type Component, type ComponentMeta, type Runtime, type ShadowDefinition, type ShadowSetup, type VNode } from "../src/index.js";
2
- /**
3
- * Mount the registered shadows of a component part against the real element the
4
- * DOM renderer just inserted. A shadow that is registered for a part whose
5
- * component is not registered is ignored, matching the runtime contract.
6
- */
7
- export declare function runShadows(runtime: Runtime, vnode: VNode, element: Element): Cleanup;
8
- /**
9
- * DOM shadows receive the real element. Core's `defineShadow` keeps the same
10
- * contract with a target-neutral host handle; Web code uses this narrowing so a
11
- * shadow can work with the element the renderer mounted.
12
- */
13
- export declare function defineShadow<C extends Component<any, any> & {
14
- readonly meta: ComponentMeta;
15
- }, Part extends C["meta"]["parts"][number]>(target: C, part: Part, setup: ShadowSetup<Parameters<C>[0], C["meta"]["name"], Part, Element>): ShadowDefinition<Parameters<C>[0], C["meta"]["name"], C["meta"]["parts"][number], Part, Element>;
@@ -1,88 +0,0 @@
1
- import { createLifecycleScope, defineShadow as defineTargetShadow, } from "../src/index.js";
2
- /** Run every cleanup, retaining the first error raised by any operation. */
3
- function disposeCleanups(cleanups) {
4
- let firstError;
5
- for (const cleanup of cleanups.reverse()) {
6
- try {
7
- cleanup();
8
- }
9
- catch (error) {
10
- firstError ??= error;
11
- }
12
- }
13
- if (firstError)
14
- throw firstError;
15
- }
16
- /**
17
- * Mount the registered shadows of a component part against the real element the
18
- * DOM renderer just inserted. A shadow that is registered for a part whose
19
- * component is not registered is ignored, matching the runtime contract.
20
- */
21
- export function runShadows(runtime, vnode, element) {
22
- const identity = vnode.componentPart;
23
- if (!identity || !runtime.registry.has(identity.component))
24
- return () => { };
25
- const shadows = runtime.shadowRegistry.list().filter((shadow) => {
26
- return shadow.component.meta.name === identity.component && shadow.part === identity.part;
27
- });
28
- if (shadows.length === 0)
29
- return () => { };
30
- const props = (identity.state ?? vnode.props);
31
- const mounted = [];
32
- try {
33
- for (const shadow of shadows) {
34
- const scope = createLifecycleScope(runtime);
35
- const context = {
36
- ...scope,
37
- component: identity,
38
- props,
39
- vnode,
40
- element,
41
- };
42
- try {
43
- const cleanup = shadow.setup(props, context);
44
- mounted.push(() => {
45
- try {
46
- cleanup?.();
47
- }
48
- finally {
49
- scope.dispose();
50
- }
51
- });
52
- }
53
- catch (error) {
54
- try {
55
- scope.dispose();
56
- }
57
- catch {
58
- // Preserve the setup error; cleanup is best-effort while mounting fails.
59
- }
60
- throw error;
61
- }
62
- }
63
- }
64
- catch (error) {
65
- try {
66
- disposeCleanups(mounted);
67
- }
68
- catch {
69
- // Preserve the setup error; cleanup is best-effort while mounting fails.
70
- }
71
- throw error;
72
- }
73
- let disposed = false;
74
- return () => {
75
- if (disposed)
76
- return;
77
- disposed = true;
78
- disposeCleanups(mounted);
79
- };
80
- }
81
- /**
82
- * DOM shadows receive the real element. Core's `defineShadow` keeps the same
83
- * contract with a target-neutral host handle; Web code uses this narrowing so a
84
- * shadow can work with the element the renderer mounted.
85
- */
86
- export function defineShadow(target, part, setup) {
87
- return defineTargetShadow(target, part, setup);
88
- }