meowjsx 0.3.0-alpha.0 → 0.3.0-alpha.2

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.
@@ -0,0 +1,346 @@
1
+ import { createContext, isInComponentBody, useContext } from "./context.js";
2
+ import { ParseFailure, parseTemplate } from "./i18n-message.js";
3
+ import { derived, isSignal, signal, unwrap } from "./reactive.js";
4
+ /**
5
+ * Declares messages at module level, away from their use. It performs no lookup: each entry
6
+ * becomes a frozen descriptor that `t` translates where it is used.
7
+ */
8
+ export function defineMessages(table) {
9
+ const entries = [];
10
+ for (const [name, spec] of Object.entries(table)) {
11
+ const value = typeof spec === "string" ? { source: spec } : spec;
12
+ if (typeof value !== "object" ||
13
+ value === null ||
14
+ typeof value.source !== "string") {
15
+ throw new Error(`meowjsx/i18n: defineMessages entry ${JSON.stringify(name)} must be a source string or ` +
16
+ "an object with a string source.");
17
+ }
18
+ const { source, context, note } = value;
19
+ if ((context !== undefined && typeof context !== "string") ||
20
+ (note !== undefined && typeof note !== "string")) {
21
+ throw new Error(`meowjsx/i18n: defineMessages entry ${JSON.stringify(name)} has a non-string context or note.`);
22
+ }
23
+ entries.push([
24
+ name,
25
+ Object.freeze({
26
+ source,
27
+ ...(context === undefined ? {} : { context }),
28
+ ...(note === undefined ? {} : { note }),
29
+ }),
30
+ ]);
31
+ }
32
+ return Object.freeze(Object.fromEntries(entries));
33
+ }
34
+ // ---------------------------------------------------------------------------
35
+ // Locales
36
+ // ---------------------------------------------------------------------------
37
+ const RTL_SCRIPTS = new Set([
38
+ "Arab",
39
+ "Aran",
40
+ "Hebr",
41
+ "Thaa",
42
+ "Syrc",
43
+ "Nkoo",
44
+ "Adlm",
45
+ "Rohg",
46
+ "Mand",
47
+ "Samr",
48
+ "Mend",
49
+ ]);
50
+ function canonicalLocale(tag) {
51
+ try {
52
+ const [canonical] = Intl.getCanonicalLocales(tag);
53
+ if (canonical)
54
+ return canonical;
55
+ }
56
+ catch {
57
+ // Reported below with the offending tag.
58
+ }
59
+ throw new Error(`meowjsx/i18n: invalid locale tag ${JSON.stringify(tag)}`);
60
+ }
61
+ /** `zh-Hant-TW` gives `zh-Hant-TW`, `zh-Hant`, `zh`. Extension subtags are not parents. */
62
+ function localeChain(locale) {
63
+ const parts = locale.split("-");
64
+ const end = parts.findIndex((part, position) => position > 0 && part.length === 1);
65
+ const base = end < 0 ? parts : parts.slice(0, end);
66
+ const chain = [];
67
+ for (let length = base.length; length > 0; length -= 1)
68
+ chain.push(base.slice(0, length).join("-"));
69
+ return chain;
70
+ }
71
+ function isLocaleOrChildOf(locale, parent) {
72
+ return locale === parent || locale.startsWith(`${parent}-`);
73
+ }
74
+ function scriptDirection(locale) {
75
+ const script = new Intl.Locale(locale).maximize().script;
76
+ return script !== undefined && RTL_SCRIPTS.has(script) ? "rtl" : "ltr";
77
+ }
78
+ function ownEntry(catalog, source) {
79
+ return Object.hasOwn(catalog, source) ? catalog[source] : undefined;
80
+ }
81
+ function translationFor(catalog, source, context) {
82
+ const entry = ownEntry(catalog, source);
83
+ let found;
84
+ if (typeof entry === "string")
85
+ found = context === undefined || context === "" ? entry : undefined;
86
+ else if (typeof entry === "object" && entry !== null)
87
+ found = Object.hasOwn(entry, context ?? "") ? entry[context ?? ""] : undefined;
88
+ return typeof found === "string" && found !== "" ? found : undefined;
89
+ }
90
+ const MESSAGE_IS_A_SIGNAL = "meowjsx/i18n: a message is a Signal, not a string. Read .value for the current string, " +
91
+ 'or pass variables through t("template {name}", { name }) instead of concatenating.';
92
+ function refuseString() {
93
+ throw new Error(MESSAGE_IS_A_SIGNAL);
94
+ }
95
+ function messageSignal(read) {
96
+ const message = derived(read);
97
+ Object.defineProperties(message, {
98
+ toString: { value: refuseString },
99
+ [Symbol.toPrimitive]: { value: refuseString },
100
+ });
101
+ return message;
102
+ }
103
+ export function createI18n(options) {
104
+ const sourceLocale = canonicalLocale(options.source);
105
+ const initial = options.locale ?? sourceLocale;
106
+ const locale = typeof initial === "string" ? signal(canonicalLocale(initial)) : initial;
107
+ if (typeof initial !== "string")
108
+ canonicalLocale(initial.value);
109
+ const catalogs = new Map();
110
+ const catalogVersion = signal(0);
111
+ const parsed = new Map();
112
+ const parsedRich = new Map();
113
+ const reported = new Set();
114
+ const formatters = new Map();
115
+ const canonicalCache = new Map();
116
+ let latestSwitch = 0;
117
+ const addCatalog = (target, catalog) => {
118
+ const tag = canonicalLocale(target);
119
+ catalogs.set(tag, { ...catalogs.get(tag), ...catalog });
120
+ catalogVersion.value += 1;
121
+ };
122
+ for (const [tag, catalog] of Object.entries(options.catalogs ?? {}))
123
+ addCatalog(tag, catalog);
124
+ const currentLocale = () => {
125
+ const tag = locale.value;
126
+ let canonical = canonicalCache.get(tag);
127
+ if (canonical === undefined) {
128
+ canonical = canonicalLocale(tag);
129
+ canonicalCache.set(tag, canonical);
130
+ }
131
+ return canonical;
132
+ };
133
+ const formatter = (kind, tag, formatOptions, create) => {
134
+ const key = `${kind}\u0000${tag}\u0000${JSON.stringify(formatOptions ?? {})}`;
135
+ let cached = formatters.get(key);
136
+ if (!cached) {
137
+ cached = create();
138
+ formatters.set(key, cached);
139
+ }
140
+ return cached;
141
+ };
142
+ const numberFormat = (tag, formatOptions) => formatter("number", tag, formatOptions, () => new Intl.NumberFormat(tag, formatOptions));
143
+ const parse = (template, describe, rich) => {
144
+ const cache = rich ? parsedRich : parsed;
145
+ let nodes = cache.get(template);
146
+ if (!nodes) {
147
+ try {
148
+ nodes = parseTemplate(template, { rich });
149
+ }
150
+ catch (error) {
151
+ if (!(error instanceof ParseFailure))
152
+ throw error;
153
+ throw new Error(`meowjsx/i18n: cannot parse ${describe} ${JSON.stringify(template)}: ${error.message}`);
154
+ }
155
+ cache.set(template, nodes);
156
+ }
157
+ return nodes;
158
+ };
159
+ /** Appends the formatted nodes to `out`; adjacent text is merged into one string. */
160
+ const emit = (nodes, values, tag, pound, out, renderTag) => {
161
+ const pushText = (value) => {
162
+ const last = out.length - 1;
163
+ if (last >= 0 && typeof out[last] === "string")
164
+ out[last] += value;
165
+ else
166
+ out.push(value);
167
+ };
168
+ for (const node of nodes) {
169
+ if (node.type === "text")
170
+ pushText(node.value);
171
+ else if (node.type === "pound")
172
+ pushText(pound ?? "#");
173
+ else if (node.type === "arg") {
174
+ const value = values.get(node.name);
175
+ if (value === undefined)
176
+ pushText(`{${node.name}}`);
177
+ else
178
+ pushText(typeof value === "number" ? numberFormat(tag).format(value) : String(value));
179
+ }
180
+ else if (node.type === "tag") {
181
+ const inner = [];
182
+ emit(node.children, values, tag, pound, inner, renderTag);
183
+ if (!renderTag)
184
+ throw new Error("meowjsx/i18n: a tag is only valid in t.rich messages");
185
+ out.push(renderTag(node.name, inner));
186
+ }
187
+ else if (node.type === "select") {
188
+ const value = values.get(node.name);
189
+ if (value === undefined) {
190
+ pushText(`{${node.name}}`);
191
+ continue;
192
+ }
193
+ const branch = node.branches.get(String(value)) ?? node.branches.get("other");
194
+ emit(branch, values, tag, pound, out, renderTag);
195
+ }
196
+ else {
197
+ const value = values.get(node.name);
198
+ if (value === undefined) {
199
+ pushText(`{${node.name}}`);
200
+ continue;
201
+ }
202
+ const count = typeof value === "number" ? value : Number(value);
203
+ const display = Number.isNaN(count) ? String(value) : numberFormat(tag).format(count);
204
+ const rules = formatter(node.ordinal ? "ordinal" : "plural", tag, undefined, () => new Intl.PluralRules(tag, node.ordinal ? { type: "ordinal" } : undefined));
205
+ const branch = node.exact.get(count) ??
206
+ node.categories.get(rules.select(count)) ??
207
+ node.categories.get("other");
208
+ emit(branch, values, tag, display, out, renderTag);
209
+ }
210
+ }
211
+ };
212
+ const format = (nodes, values, tag) => {
213
+ const out = [];
214
+ emit(nodes, values, tag, undefined, out, undefined);
215
+ return out.join("");
216
+ };
217
+ const report = (source, context, tag) => {
218
+ const key = JSON.stringify([tag, context ?? null, source]);
219
+ if (reported.has(key))
220
+ return;
221
+ reported.add(key);
222
+ options.onMissing?.({ source, ...(context === undefined ? {} : { context }), locale: tag });
223
+ };
224
+ const resolve = (source, context, tag) => {
225
+ if (isLocaleOrChildOf(tag, sourceLocale))
226
+ return { template: source, describe: "message" };
227
+ for (const candidate of localeChain(tag)) {
228
+ const catalog = catalogs.get(candidate);
229
+ const found = catalog && translationFor(catalog, source, context);
230
+ if (found !== undefined)
231
+ return { template: found, describe: `translation of ${JSON.stringify(source)}` };
232
+ }
233
+ report(source, context, tag);
234
+ return { template: source, describe: "message" };
235
+ };
236
+ const paramValues = (params) => {
237
+ const values = new Map();
238
+ if (params) {
239
+ for (const name of Object.keys(params))
240
+ values.set(name, unwrap(params[name]));
241
+ }
242
+ return values;
243
+ };
244
+ /** The source and context behind a literal, a descriptor or a Signal of a descriptor. */
245
+ const readSource = (input, translateOptions) => {
246
+ const value = isSignal(input) ? input.value : input;
247
+ if (typeof value === "string")
248
+ return { source: value, context: translateOptions?.context };
249
+ if (typeof value === "object" && value !== null && typeof value.source === "string") {
250
+ return { source: value.source, context: value.context ?? translateOptions?.context };
251
+ }
252
+ throw new Error("meowjsx/i18n: t() needs a literal source, a defineMessages descriptor or a Signal of one.");
253
+ };
254
+ const translate = (input, params, translateOptions) => messageSignal(() => {
255
+ const tag = currentLocale();
256
+ void catalogVersion.value;
257
+ const values = paramValues(params);
258
+ const { source, context } = readSource(input, translateOptions);
259
+ const { template, describe } = resolve(source, context, tag);
260
+ return format(parse(template, describe, false), values, tag);
261
+ });
262
+ const translateRich = (input, parts, params, translateOptions) => messageSignal(() => {
263
+ const tag = currentLocale();
264
+ void catalogVersion.value;
265
+ const values = paramValues(params);
266
+ const { source, context } = readSource(input, translateOptions);
267
+ const { template, describe } = resolve(source, context, tag);
268
+ const out = [];
269
+ emit(parse(template, describe, true), values, tag, undefined, out, (name, children) => {
270
+ const part = Object.hasOwn(parts, name) ? parts[name] : undefined;
271
+ if (typeof part !== "function") {
272
+ throw new Error(`meowjsx/i18n: the ${describe === "message" ? "message" : describe} uses the tag ` +
273
+ `<${name}> but t.rich(${JSON.stringify(source)}) was given no part for it ` +
274
+ `(parts: ${Object.keys(parts).join(", ") || "none"}).`);
275
+ }
276
+ return part(children);
277
+ });
278
+ return out;
279
+ });
280
+ const lookup = (text, lookupOptions) => messageSignal(() => {
281
+ const tag = currentLocale();
282
+ void catalogVersion.value;
283
+ // Both the text and its translation are literal: no placeholder is interpreted.
284
+ return resolve(text, lookupOptions?.context, tag).template;
285
+ });
286
+ const number = (value, formatOptions) => derived(() => numberFormat(currentLocale(), formatOptions).format(unwrap(value)));
287
+ const date = (value, formatOptions) => derived(() => {
288
+ const tag = currentLocale();
289
+ const effective = options.timeZone !== undefined && formatOptions?.timeZone === undefined
290
+ ? { ...formatOptions, timeZone: options.timeZone }
291
+ : formatOptions;
292
+ return formatter("date", tag, effective, () => new Intl.DateTimeFormat(tag, effective)).format(unwrap(value));
293
+ });
294
+ const direction = derived(() => scriptDirection(currentLocale()));
295
+ const setLocale = async (next) => {
296
+ const tag = canonicalLocale(next);
297
+ const ticket = (latestSwitch += 1);
298
+ if (options.load && !isLocaleOrChildOf(tag, sourceLocale) && !catalogs.has(tag)) {
299
+ addCatalog(tag, await options.load(tag));
300
+ }
301
+ if (ticket === latestSwitch)
302
+ locale.value = tag;
303
+ };
304
+ return {
305
+ locale,
306
+ direction,
307
+ t: Object.assign(translate, { rich: translateRich }),
308
+ lookup,
309
+ number,
310
+ date,
311
+ addCatalog,
312
+ setLocale,
313
+ };
314
+ }
315
+ // ---------------------------------------------------------------------------
316
+ // Ambient t
317
+ // ---------------------------------------------------------------------------
318
+ const I18nContext = createContext(undefined);
319
+ /** Provides one instance to the components below it. */
320
+ export const I18nProvider = I18nContext.Provider;
321
+ /** The nearest provided instance, or `undefined`. Read it in a component body. */
322
+ export function useI18n() {
323
+ return useContext(I18nContext);
324
+ }
325
+ let sourceOnly;
326
+ function ambientInstance(name) {
327
+ if (!isInComponentBody()) {
328
+ throw new Error(`meowjsx/i18n: ${name} reads the nearest I18nProvider and works only while a component ` +
329
+ "function body runs. In a handler, a derived body, a keyed callback, after await, at " +
330
+ "module top level or in a plain function, use the instance: i18n.t(...). Declare " +
331
+ "messages away from their use with defineMessages.");
332
+ }
333
+ // Without a provider the message is its source text; plural rules are those of "en".
334
+ return useContext(I18nContext) ?? (sourceOnly ??= createI18n({ source: "en" }));
335
+ }
336
+ function ambientTranslate(input, params, options) {
337
+ return ambientInstance("t()").t(input, params, options);
338
+ }
339
+ function ambientRich(source, parts, params, options) {
340
+ return ambientInstance("t.rich()").t.rich(source, parts, params, options);
341
+ }
342
+ /**
343
+ * Translates with the nearest `I18nProvider`, or renders the source text when there is none.
344
+ * Callable only while a component function body runs; elsewhere it throws.
345
+ */
346
+ export const t = Object.assign(ambientTranslate, { rich: ambientRich });
package/dist/src/keyed.js CHANGED
@@ -1,8 +1,14 @@
1
+ import { outsideComponentBody } from "./context.js";
1
2
  import { isSignal } from "./reactive.js";
2
3
  const keyedBrand = Symbol("meowjsx.keyed");
3
4
  /** Keep rows mounted by identity. The callback constructs children, not a lifecycle scope. */
4
5
  export function keyed(items, key, render) {
5
- return { [keyedBrand]: true, items, key, render };
6
+ return {
7
+ [keyedBrand]: true,
8
+ items,
9
+ key: (item) => outsideComponentBody(() => key(item)),
10
+ render: (row) => outsideComponentBody(() => render(row)),
11
+ };
6
12
  }
7
13
  export function isKeyedChild(value) {
8
14
  return typeof value === "object" && value !== null && keyedBrand in value;
@@ -1,3 +1,4 @@
1
+ import { outsideComponentBody } from "./context.js";
1
2
  const pendingJobs = new Set();
2
3
  let flushScheduled = false;
3
4
  let batchDepth = 0;
@@ -8,7 +9,7 @@ function flushJobs() {
8
9
  const jobs = [...pendingJobs];
9
10
  pendingJobs.clear();
10
11
  for (const job of jobs)
11
- job();
12
+ outsideComponentBody(job);
12
13
  }
13
14
  }
14
15
  function schedule(job) {
@@ -100,7 +101,7 @@ export function createReactiveEffect(run) {
100
101
  const previousEffect = activeEffect;
101
102
  activeEffect = state;
102
103
  try {
103
- currentCleanup = run() ?? undefined;
104
+ currentCleanup = outsideComponentBody(run) ?? undefined;
104
105
  }
105
106
  finally {
106
107
  activeEffect = previousEffect;
@@ -148,10 +149,10 @@ export function mapSignal(source, map) {
148
149
  const mapped = {
149
150
  get value() {
150
151
  trackSignal(mapped);
151
- return map(source.value);
152
+ return outsideComponentBody(() => map(source.value));
152
153
  },
153
154
  subscribe(listener) {
154
- return source.subscribe((value) => listener(map(value)));
155
+ return source.subscribe((value) => listener(outsideComponentBody(() => map(value))));
155
156
  },
156
157
  };
157
158
  return mapped;
@@ -189,7 +190,7 @@ export function derived(read) {
189
190
  computing = true;
190
191
  let next;
191
192
  try {
192
- next = read();
193
+ next = outsideComponentBody(read);
193
194
  }
194
195
  finally {
195
196
  activeEffect = previousEffect;
@@ -218,7 +219,7 @@ export function derived(read) {
218
219
  trackSignal(computed);
219
220
  computing = true;
220
221
  try {
221
- return read();
222
+ return outsideComponentBody(read);
222
223
  }
223
224
  finally {
224
225
  computing = false;
@@ -1,4 +1,4 @@
1
- import type { AnyShadowDefinition, Child, Cleanup, Component, ComponentMeta, ComponentRegistry, ComponentRenderContext, CreateContext, CreateHook, LifecycleScope, Props, RegisteredComponent, RenderHook, ResolveComponentHook, Runtime, RuntimePluginEnforce, ShadowRegistry, VNode } from "./types.js";
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";
2
2
  import { type ContextScope } from "./context.js";
3
3
  export interface HookEntry<Hook> {
4
4
  readonly handler: Hook;
@@ -8,6 +8,7 @@ export interface RuntimeState {
8
8
  createHooks: HookEntry<CreateHook>[];
9
9
  renderHooks: HookEntry<RenderHook>[];
10
10
  resolveComponentHooks: HookEntry<ResolveComponentHook>[];
11
+ containerHooks: HookEntry<PrepareContainerHook>[];
11
12
  shadowRegistry: ShadowRegistry;
12
13
  overrides: Map<string, Component<any>>;
13
14
  }
@@ -1,5 +1,5 @@
1
1
  import { createPartDescriptor, normalizeRefBinding, isNormalizedRef } from "./parts.js";
2
- import { contextScopeForProvider, withContextScope } from "./context.js";
2
+ import { contextScopeForProvider, runComponentBody } from "./context.js";
3
3
  import { createLifecycleScope } from "./lifecycle.js";
4
4
  export function addHook(hooks, handler, enforce) {
5
5
  const entry = { handler, enforce };
@@ -96,7 +96,7 @@ export function invokeComponent(component, props, runtime, contextScope) {
96
96
  const componentContext = createComponentContext(runtime, component, props, scope);
97
97
  try {
98
98
  return {
99
- child: withContextScope(contextScope, () => component(props, componentContext)),
99
+ child: runComponentBody(contextScope, () => component(props, componentContext)),
100
100
  contextScope: contextScopeForProvider(component, props.value, contextScope),
101
101
  dispose: scope.dispose,
102
102
  };
@@ -3,7 +3,7 @@ export { keyed, type KeyedChild } from "./keyed.js";
3
3
  export { createPartDescriptor, isPartDescriptor } from "./parts.js";
4
4
  export type { PartDescriptor, RefBinding, RefCallback, RefCleanup } from "./parts.js";
5
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, Props, ReadableSignal, RegisteredComponent, RegisteredComponentName, RegisteredComponentPart, RenderContext, RenderHook, ResolveComponentContext, ResolveComponentHook, Runtime, 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";
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";
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";
@@ -33,11 +33,14 @@ export function createRuntime(options = {}) {
33
33
  createHooks: [],
34
34
  renderHooks: [],
35
35
  resolveComponentHooks: [],
36
+ containerHooks: [],
36
37
  shadowRegistry: createShadowRegistry(options.shadows),
37
38
  overrides: new Map(Object.entries(options.overrides ?? {})),
38
39
  };
39
40
  const registry = createComponentRegistry(options.components ?? []);
40
41
  const runtime = {};
42
+ // The cleanups each mount hook still owes, so uninstalling its plugin can release them.
43
+ const activeMounts = new Map();
41
44
  const installPlugin = (plugin) => {
42
45
  let createEntry;
43
46
  let renderEntry;
@@ -87,6 +90,17 @@ export function createRuntime(options = {}) {
87
90
  renderEntry = addHook(state.renderHooks, plugin.render, plugin.enforce);
88
91
  contributionCleanups.push(() => removeHook(state.renderHooks, renderEntry));
89
92
  }
93
+ if (plugin.prepareContainer) {
94
+ const entry = addHook(state.containerHooks, plugin.prepareContainer, plugin.enforce);
95
+ const owed = new Set();
96
+ activeMounts.set(entry, owed);
97
+ contributionCleanups.push(() => {
98
+ removeHook(state.containerHooks, entry);
99
+ activeMounts.delete(entry);
100
+ });
101
+ // Runs before the hook is removed: a mount the plugin prepared does not outlive it.
102
+ contributionCleanups.push(() => disposeCleanups([...owed]));
103
+ }
90
104
  if (plugin.resolveComponent) {
91
105
  const entry = addHook(state.resolveComponentHooks, plugin.resolveComponent, plugin.enforce);
92
106
  contributionCleanups.push(() => removeHook(state.resolveComponentHooks, entry));
@@ -195,6 +209,43 @@ export function createRuntime(options = {}) {
195
209
  },
196
210
  transformVNode: (vnode) => runRenderHooks(state, runtime, vnode),
197
211
  replacementFor: (vnode) => replacementFor(state, vnode),
212
+ prepareContainer(container, target) {
213
+ const acquired = [];
214
+ try {
215
+ for (const entry of state.containerHooks.slice()) {
216
+ const cleanup = entry.handler({ runtime, container, target });
217
+ if (typeof cleanup !== "function")
218
+ continue;
219
+ const owed = activeMounts.get(entry);
220
+ let released = false;
221
+ const once = () => {
222
+ if (released)
223
+ return;
224
+ released = true;
225
+ owed?.delete(once);
226
+ cleanup();
227
+ };
228
+ owed?.add(once);
229
+ acquired.push(once);
230
+ }
231
+ }
232
+ catch (error) {
233
+ try {
234
+ disposeCleanups(acquired);
235
+ }
236
+ catch {
237
+ // Preserve the mount hook's error; rollback is best-effort.
238
+ }
239
+ throw error;
240
+ }
241
+ let active = true;
242
+ return () => {
243
+ if (!active)
244
+ return;
245
+ active = false;
246
+ disposeCleanups(acquired);
247
+ };
248
+ },
198
249
  };
199
250
  const createRenderer = (strategy, rendererOptions = {}) => {
200
251
  const defaultOnMount = (vnode) => {
@@ -150,6 +150,19 @@ export interface RuntimePluginContext {
150
150
  onCleanup(cleanup: Cleanup): void;
151
151
  }
152
152
  export type RuntimePluginSetup = (context: RuntimePluginContext) => void | Cleanup;
153
+ /** What a target renderer hands a plugin when it prepares a container for a mount. */
154
+ export interface ContainerContext {
155
+ readonly runtime: Runtime;
156
+ /** The node the target renders into; meowjsx/web passes the container Element. */
157
+ readonly container: unknown;
158
+ /** The target that mounts, such as "web"; a plugin narrows `container` by it. */
159
+ readonly target: string;
160
+ }
161
+ /**
162
+ * Prepares a container before a target renders into it, such as delivering a stylesheet to its
163
+ * document. The returned cleanup runs after that mount's tree is removed.
164
+ */
165
+ export type PrepareContainerHook = (context: ContainerContext) => void | Cleanup;
153
166
  export type RuntimePlugin = {
154
167
  name?: string;
155
168
  enforce?: RuntimePluginEnforce;
@@ -157,6 +170,8 @@ export type RuntimePlugin = {
157
170
  create?: CreateHook;
158
171
  render?: RenderHook;
159
172
  resolveComponent?: ResolveComponentHook;
173
+ /** Runs when a target renderer mounts into a container; not for static output. */
174
+ prepareContainer?: PrepareContainerHook;
160
175
  shadows?: readonly AnyShadowDefinition[];
161
176
  overrides?: Record<string, Component<any>>;
162
177
  components?: readonly RegisteredComponent[];
@@ -182,6 +197,12 @@ export interface RuntimeTargetHooks {
182
197
  };
183
198
  transformVNode(vnode: VNode): VNode;
184
199
  replacementFor(vnode: VNode): Component<any, any> | undefined;
200
+ /**
201
+ * Runs the installed plugins' `prepareContainer` hooks for one container, in plugin order, and returns
202
+ * the cleanup that releases them in reverse. A target renderer calls it before rendering into
203
+ * the container and calls the cleanup after the tree is removed.
204
+ */
205
+ prepareContainer(container: unknown, target: string): Cleanup;
185
206
  }
186
207
  export type FragmentComponent = (props: {
187
208
  children?: Child;
@@ -25,8 +25,32 @@ export function createWebRenderer(runtime = defaultRuntime, options = {}) {
25
25
  const child = options.observation
26
26
  ? h(WebObservationContext.Provider, { value: options.observation }, node)
27
27
  : node;
28
- const mounted = renderer.render(child, container, null);
29
- return { unmount: () => mounted.unmount() };
28
+ // Plugins prepare the container first, so a stylesheet or theme root exists when component
29
+ // setup and refs run; they are released after the tree is gone.
30
+ const release = runtime.targetHooks.prepareContainer(container, "web");
31
+ let mounted;
32
+ try {
33
+ mounted = renderer.render(child, container, null);
34
+ }
35
+ catch (error) {
36
+ try {
37
+ release();
38
+ }
39
+ catch {
40
+ // Preserve the render error; the release is best-effort.
41
+ }
42
+ throw error;
43
+ }
44
+ return {
45
+ unmount: () => {
46
+ try {
47
+ mounted.unmount();
48
+ }
49
+ finally {
50
+ release();
51
+ }
52
+ },
53
+ };
30
54
  };
31
55
  return {
32
56
  runtime,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meowjsx",
3
- "version": "0.3.0-alpha.0",
3
+ "version": "0.3.0-alpha.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -29,6 +29,14 @@
29
29
  "types": "./dist/src/signal.d.ts",
30
30
  "import": "./dist/src/signal.js"
31
31
  },
32
+ "./i18n": {
33
+ "types": "./dist/src/i18n.d.ts",
34
+ "import": "./dist/src/i18n.js"
35
+ },
36
+ "./i18n/audit": {
37
+ "types": "./dist/src/i18n-audit.d.ts",
38
+ "import": "./dist/src/i18n-audit.js"
39
+ },
32
40
  "./renderer": {
33
41
  "types": "./dist/src/renderer.d.ts",
34
42
  "import": "./dist/src/renderer.js"