@zubra/runtime 5.7.0 → 5.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -0
- package/dist/production/bridge.js +97 -0
- package/dist/production/context.js +101 -0
- package/dist/production/element.js +25 -1
- package/dist/production/forms.js +126 -0
- package/dist/production/navigation.js +53 -0
- package/dist/production/outlet.js +80 -0
- package/dist/production/react.js +136 -2
- package/dist/production/testing.js +154 -0
- package/dist/production/vue.js +67 -1
- package/package.json +43 -3
- package/src/bridge.js +96 -0
- package/src/context.js +100 -0
- package/src/element.js +25 -1
- package/src/forms.js +125 -0
- package/src/navigation.js +52 -0
- package/src/outlet.js +79 -0
- package/src/react.js +136 -2
- package/src/testing.js +153 -0
- package/src/vue.js +67 -1
- package/types/bridge.d.ts +44 -0
- package/types/context.d.ts +17 -0
- package/types/forms.d.ts +37 -0
- package/types/navigation.d.ts +22 -0
- package/types/outlet.d.ts +23 -0
- package/types/react.d.ts +17 -1
- package/types/testing.d.ts +32 -0
- package/types/vue.d.ts +15 -0
package/README.md
CHANGED
|
@@ -13,9 +13,14 @@ ships one, this package deletes code instead of components being rewritten.
|
|
|
13
13
|
| `src/element.js` hooks | Plain functions (see the project's hooks decision) | `state`, `from`, `computed`, `watch`, `onMount`, `onUnmount`, `id`, `props`, `host`, `emit`, `hydrated` |
|
|
14
14
|
| `src/element.js` slots | Light-DOM slotting with the host's child methods routed to the slots, so frameworks can keep managing the children; native `<slot>` in shadow DOM | Done |
|
|
15
15
|
| `src/react.js`, `src/vue.js` | Adapters: an element as a React (18, 19) or Vue 3 component | Done |
|
|
16
|
+
| `src/testing.js` | `mount(Element, { framework })`: a component through plain HTML, the React adapter or the Vue adapter, for one test per framework in any browser test runner | Done |
|
|
17
|
+
| `src/navigation.js` | Links inside components through the app's router: `routeLinks(navigate)`; `useRouteLinks` in the React and Vue adapters. Not a router | Done |
|
|
18
|
+
| `src/forms.js` | A control as a form library's field: React Hook Form (`registerProps`, `fieldProps`), TanStack Form (`fieldProps`), VeeValidate (`vueFieldProps`), Felte (`felteControl`) | Done |
|
|
19
|
+
| `src/bridge.js` | Signals read from framework code: `subscribe`, and `toStore` (the Svelte store contract and an RxJS-style Subscribable); React and Vue `useSignal` | Done |
|
|
16
20
|
| `types/` | TypeScript declarations for every entry point | Done |
|
|
17
21
|
| `src/element.js` forms | Form-associated custom elements (`ElementInternals`) | `formValue`, `validity`, `onFormReset`, `onFormRestore`, `onFormDisabled`; native control API on the element |
|
|
18
22
|
| `src/element.js` context | [Context Protocol](https://github.com/webcomponents-cg/community-protocols/blob/main/proposals/context.md) (`context-request` / `context-provider` events) | `createContext`, `provide`, `inject`; interoperates with any protocol implementation |
|
|
23
|
+
| `src/context.js` | The same protocol, provided from the app: `<zb-context>` with `context` and `value` properties; `ZubraContext` in the React and Vue adapters | Done |
|
|
19
24
|
|
|
20
25
|
## The production build
|
|
21
26
|
|
|
@@ -82,6 +87,25 @@ await tick();
|
|
|
82
87
|
A write to a signal an effect has already read in the same run does not re-run it (same as a
|
|
83
88
|
computed in the reference). Derive the value instead of writing it back.
|
|
84
89
|
|
|
90
|
+
## Signals in framework code
|
|
91
|
+
|
|
92
|
+
A signal elements read can be read by the app too, so state is shared rather than copied in by
|
|
93
|
+
props and back out by events (`@zubra/runtime/bridge`):
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
import { state } from '@zubra/runtime';
|
|
97
|
+
export const cart = state([]); // cart-state.js, imported by elements too
|
|
98
|
+
|
|
99
|
+
// React // Vue
|
|
100
|
+
const items = useSignal(cart, { deep: true }); const items = useSignal(cart, { deep: true }); // a ref
|
|
101
|
+
// Svelte: const items = toStore(cart, { deep: true }), then {$items.length}
|
|
102
|
+
// Solid: from(toStore(cart)) Angular: toSignal(toStore(cart), { requireSync: true })
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`subscribe` and the stores are effects owned by nothing: they last until unsubscribed (Vue's ref
|
|
106
|
+
stops with the scope it was made in; React's hook with the component). `deep: true` reads through
|
|
107
|
+
an array or plain object, so a mutation inside it notifies.
|
|
108
|
+
|
|
85
109
|
## Tests
|
|
86
110
|
|
|
87
111
|
```sh
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Generated by scripts/build-production.js from src/bridge.js: the runtime without hot reloading or the DevTools hook. Do not edit.
|
|
2
|
+
// Signal bridges: read (and write) a Zubra signal from a framework's own code.
|
|
3
|
+
//
|
|
4
|
+
// import { shared } from './cart-state.js' // export const shared = state([])
|
|
5
|
+
// import { toStore } from '@zubra/runtime/bridge'
|
|
6
|
+
// const cart = toStore(shared, { deep: true })
|
|
7
|
+
//
|
|
8
|
+
// Svelte: {$cart.length} (the store contract)
|
|
9
|
+
// Solid: const items = from(cart) (solid-js `from`)
|
|
10
|
+
// Angular: items = toSignal(cart, { requireSync: true }) (a Subscribable)
|
|
11
|
+
// RxJS: from(cart) (Symbol.observable)
|
|
12
|
+
// React: useSignal(shared) from '@zubra/runtime/react'
|
|
13
|
+
// Vue: useSignal(shared) from '@zubra/runtime/vue'
|
|
14
|
+
//
|
|
15
|
+
// The adapters carry props, events and two-way bindings across the element boundary; this
|
|
16
|
+
// carries state: a signal that elements and the app's code both read, without copying it into
|
|
17
|
+
// the framework's state and back. Any `Signal.State` or `Signal.Computed` works (`state()`,
|
|
18
|
+
// `computed()`, `from()`, a `@zubra/sync` field, a native `Signal` once browsers ship one), as
|
|
19
|
+
// does a function that reads signals (it's tracked like a computed).
|
|
20
|
+
//
|
|
21
|
+
// `deep: true` also tracks what's inside an array or plain object, so `items.push(x)` notifies
|
|
22
|
+
// as `items = [...items, x]` does. Without it a mutation inside the value isn't a change.
|
|
23
|
+
import { Signal } from './signal.js';
|
|
24
|
+
import { effect, root } from './effect.js';
|
|
25
|
+
|
|
26
|
+
const isSignal = (value) => value instanceof Signal.State || value instanceof Signal.Computed;
|
|
27
|
+
|
|
28
|
+
function check(source, name) {
|
|
29
|
+
if (typeof source !== 'function' && !isSignal(source)) {
|
|
30
|
+
throw new TypeError(`zubra: ${name}() needs a signal (state(), computed(), a Signal.State or Signal.Computed) or a function that reads signals`);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The source's current value: a signal's `get()`, or the function's result. */
|
|
35
|
+
export const read = (source) => (typeof source === 'function' ? source() : source.get());
|
|
36
|
+
|
|
37
|
+
/** Whether the source can be written: a `Signal.State`, or a signal with its own `set` (`from()`). */
|
|
38
|
+
export const writable = (source) => typeof source?.set === 'function';
|
|
39
|
+
|
|
40
|
+
// Read every property of an array or plain object (through state's proxy, each read is tracked),
|
|
41
|
+
// so a change anywhere inside notifies.
|
|
42
|
+
function touch(value, seen = new Set()) {
|
|
43
|
+
if (value === null || typeof value !== 'object' || seen.has(value)) return;
|
|
44
|
+
if (!Array.isArray(value)) {
|
|
45
|
+
const proto = Object.getPrototypeOf(value);
|
|
46
|
+
if (proto !== Object.prototype && proto !== null) return;
|
|
47
|
+
}
|
|
48
|
+
seen.add(value);
|
|
49
|
+
if (Array.isArray(value)) for (let index = 0; index < value.length; index++) touch(value[index], seen);
|
|
50
|
+
else for (const key of Object.keys(value)) touch(value[key], seen);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Call `callback(value)` now and whenever `source` changes, until the returned function is
|
|
55
|
+
* called. Changes are batched like the runtime's own effects: one call per microtask, with the
|
|
56
|
+
* latest value. Not owned by any component, so it lives until it's unsubscribed.
|
|
57
|
+
*/
|
|
58
|
+
export function subscribe(source, callback, { deep = false } = {}) {
|
|
59
|
+
check(source, 'subscribe');
|
|
60
|
+
const owner = root(() => {
|
|
61
|
+
effect(() => {
|
|
62
|
+
const value = read(source);
|
|
63
|
+
if (deep) touch(value);
|
|
64
|
+
Signal.subtle.untrack(() => callback(value));
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
return () => owner.dispose();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The source as a store: the Svelte store contract (`subscribe(run)` calls `run` now and on each
|
|
72
|
+
* change, returning the unsubscribe function), which is also an RxJS-style Subscribable
|
|
73
|
+
* (`subscribe({ next })` returns something with `unsubscribe()`), so Angular's `toSignal`, Solid's
|
|
74
|
+
* `from` and RxJS's `from` take it as it is. `set` and `update` are there when the source is
|
|
75
|
+
* writable (a Svelte writable store, so `bind:value={$store}` works).
|
|
76
|
+
*/
|
|
77
|
+
export function toStore(source, options = {}) {
|
|
78
|
+
check(source, 'toStore');
|
|
79
|
+
const store = {
|
|
80
|
+
get: () => read(source),
|
|
81
|
+
subscribe(run) {
|
|
82
|
+
const next = typeof run === 'function' ? run : (value) => run?.next?.(value);
|
|
83
|
+
const stop = subscribe(source, next, options);
|
|
84
|
+
const unsubscribe = () => stop();
|
|
85
|
+
unsubscribe.unsubscribe = unsubscribe;
|
|
86
|
+
return unsubscribe;
|
|
87
|
+
},
|
|
88
|
+
[Symbol.observable ?? '@@observable']() {
|
|
89
|
+
return this;
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
if (writable(source)) {
|
|
93
|
+
store.set = (value) => source.set(value);
|
|
94
|
+
store.update = (fn) => source.set(fn(Signal.subtle.untrack(() => read(source))));
|
|
95
|
+
}
|
|
96
|
+
return store;
|
|
97
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Generated by scripts/build-production.js from src/context.js: the runtime without hot reloading or the DevTools hook. Do not edit.
|
|
2
|
+
// Context from the app: a `<zb-context>` element that answers the Context Protocol for the
|
|
3
|
+
// elements inside it, so an app's theme, locale or current user reaches every component without
|
|
4
|
+
// being passed down as props.
|
|
5
|
+
//
|
|
6
|
+
// <zb-context .context=${theme} .value=${'dark'}> …elements that inject(theme)… </zb-context>
|
|
7
|
+
//
|
|
8
|
+
// It's a plain custom element with two properties, so every framework can use it as it is:
|
|
9
|
+
// Svelte `<zb-context {context} {value}>`, Solid `prop:context`, Angular `[context]`, Lit
|
|
10
|
+
// `.context`, plain HTML `el.value = …`. React and Vue have `ZubraContext` components
|
|
11
|
+
// (`@zubra/runtime/react`, `@zubra/runtime/vue`) that wrap it. The element is `display:
|
|
12
|
+
// contents`, so it adds no box to the layout.
|
|
13
|
+
//
|
|
14
|
+
// The value can be a plain value or a signal; subscribers hear each change either way. Any
|
|
15
|
+
// Context Protocol consumer is answered: Zubra's `inject()`, Lit's `@consume`, and so on. A
|
|
16
|
+
// consumer that asked before the element was given its context asks again when the element
|
|
17
|
+
// announces it with a `context-provider` event (children connect after their parent, so one
|
|
18
|
+
// given its context before it's in the document is there when they first ask).
|
|
19
|
+
import { Signal } from './signal.js';
|
|
20
|
+
import { effect, root } from './effect.js';
|
|
21
|
+
import { ContextProviderEvent } from './element.js';
|
|
22
|
+
|
|
23
|
+
const isSignal = (value) => value instanceof Signal.State || value instanceof Signal.Computed;
|
|
24
|
+
const unwrap = (value) => (isSignal(value) ? value.get() : value);
|
|
25
|
+
|
|
26
|
+
const Base = globalThis.HTMLElement ?? class {};
|
|
27
|
+
|
|
28
|
+
export class ZubraContextElement extends Base {
|
|
29
|
+
#context = undefined;
|
|
30
|
+
#value = undefined;
|
|
31
|
+
#subscribers = new Set();
|
|
32
|
+
#watching = null; // the effect following a signal value
|
|
33
|
+
|
|
34
|
+
constructor() {
|
|
35
|
+
super();
|
|
36
|
+
this.addEventListener('context-request', (event) => {
|
|
37
|
+
if (this.#context === undefined || event.context !== this.#context || event.contextTarget === this) return;
|
|
38
|
+
event.stopPropagation();
|
|
39
|
+
const current = Signal.subtle.untrack(() => unwrap(this.#value));
|
|
40
|
+
if (!event.subscribe) return event.callback(current);
|
|
41
|
+
const subscriber = { callback: event.callback };
|
|
42
|
+
subscriber.unsubscribe = () => this.#subscribers.delete(subscriber);
|
|
43
|
+
this.#subscribers.add(subscriber);
|
|
44
|
+
event.callback(current, subscriber.unsubscribe);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The context key this element provides (from `createContext()`, or any protocol key). */
|
|
49
|
+
get context() {
|
|
50
|
+
return this.#context;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
set context(key) {
|
|
54
|
+
if (key === this.#context) return;
|
|
55
|
+
// Consumers of the old key keep what they have, but stop hearing from this element.
|
|
56
|
+
this.#subscribers.clear();
|
|
57
|
+
this.#context = key;
|
|
58
|
+
this.#announce();
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The value, or a signal holding it. */
|
|
62
|
+
get value() {
|
|
63
|
+
return this.#value;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
set value(next) {
|
|
67
|
+
if (Object.is(next, this.#value)) return;
|
|
68
|
+
this.#value = next;
|
|
69
|
+
this.#watching?.dispose();
|
|
70
|
+
this.#watching = null;
|
|
71
|
+
if (isSignal(next)) {
|
|
72
|
+
let first = true;
|
|
73
|
+
this.#watching = root(() => effect(() => {
|
|
74
|
+
const value = next.get();
|
|
75
|
+
if (first) first = false;
|
|
76
|
+
else Signal.subtle.untrack(() => this.#notify(value));
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
79
|
+
this.#notify(Signal.subtle.untrack(() => unwrap(next)));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
connectedCallback() {
|
|
83
|
+
if (!this.style.display) this.style.display = 'contents';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
#notify(value) {
|
|
87
|
+
for (const subscriber of [...this.#subscribers]) subscriber.callback(value, subscriber.unsubscribe);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
#announce() {
|
|
91
|
+
if (this.#context !== undefined && this.isConnected) this.dispatchEvent(new ContextProviderEvent(this.#context, this));
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Define `<zb-context>` (once; a no-op where there's no `customElements`, as on a server). */
|
|
96
|
+
export function defineContextElement() {
|
|
97
|
+
const registry = globalThis.customElements;
|
|
98
|
+
if (registry && !registry.get('zb-context')) registry.define('zb-context', ZubraContextElement);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
defineContextElement();
|
|
@@ -60,6 +60,15 @@ const clone = (value) => (value && typeof value === 'object' ? structuredClone(v
|
|
|
60
60
|
/** Attribute text → prop value, typed by the prop's default (JSON for arrays and objects). */
|
|
61
61
|
function parseAttribute(spec, raw) {
|
|
62
62
|
const fallback = spec.default;
|
|
63
|
+
// An enum prop (`<script lang="ts">`): the member whose value the text is, or the member it names.
|
|
64
|
+
if (spec.enum) {
|
|
65
|
+
if (raw === null) return clone(fallback);
|
|
66
|
+
const found = Object.values(spec.enum).find((value) => String(value) === raw);
|
|
67
|
+
if (found !== undefined) return found;
|
|
68
|
+
if (Object.hasOwn(spec.enum, raw)) return spec.enum[raw];
|
|
69
|
+
console.warn(`zubra: attribute "${spec.attribute}" is "${raw}", not one of ${Object.keys(spec.enum).join(', ')}`);
|
|
70
|
+
return clone(fallback);
|
|
71
|
+
}
|
|
63
72
|
if (typeof fallback === 'boolean') return fallback ? raw !== 'false' : raw !== null;
|
|
64
73
|
if (raw === null) return clone(fallback);
|
|
65
74
|
if (typeof fallback === 'number') return Number(raw);
|
|
@@ -1523,6 +1532,18 @@ function defineElement(tag, definition) {
|
|
|
1523
1532
|
let templateSignature = signature(childRange(componentTemplate.content));
|
|
1524
1533
|
let instances = 0;
|
|
1525
1534
|
const byAttribute = Object.fromEntries(Object.entries(props).map(([name, spec]) => [spec.attribute, name]));
|
|
1535
|
+
// HTML lowercases attribute names, so `maxValue` in a page arrives as `maxvalue`, which isn't
|
|
1536
|
+
// the prop's attribute (`max-value`): the element would ignore it without a word.
|
|
1537
|
+
const lowercased = Object.entries(props)
|
|
1538
|
+
.filter(([name, spec]) => name !== name.toLowerCase() && spec.attribute !== name.toLowerCase())
|
|
1539
|
+
.map(([name, spec]) => [name.toLowerCase(), name, spec.attribute]);
|
|
1540
|
+
const checkAttributeCase = (element) => {
|
|
1541
|
+
for (const [lower, name, attribute] of lowercased) {
|
|
1542
|
+
if (element.hasAttribute(lower) && !element.hasAttribute(attribute)) {
|
|
1543
|
+
console.warn(`zubra: <${tag}> ignores the attribute "${lower}": HTML lowercases attribute names, and the prop ${name} is the attribute "${attribute}"${see('writing-a-component')}`);
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
};
|
|
1526
1547
|
|
|
1527
1548
|
let internals; // (element) => its ElementInternals; set in the static block below
|
|
1528
1549
|
class ZubraElement extends HTMLElement {
|
|
@@ -1597,7 +1618,10 @@ function defineElement(tag, definition) {
|
|
|
1597
1618
|
// Server markup without its comments: start once the code that puts them back is here.
|
|
1598
1619
|
loadRemark().then(() => { if (this.isConnected && !this.#scope) this.connectedCallback(); });
|
|
1599
1620
|
return;
|
|
1600
|
-
} else
|
|
1621
|
+
} else {
|
|
1622
|
+
if (lowercased.length) checkAttributeCase(this);
|
|
1623
|
+
this.#boot();
|
|
1624
|
+
}
|
|
1601
1625
|
this.#cleanups = this.#hooks.mount.map((fn) => fn()).filter((cleanup) => typeof cleanup === 'function');
|
|
1602
1626
|
this.#started();
|
|
1603
1627
|
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Generated by scripts/build-production.js from src/forms.js: the runtime without hot reloading or the DevTools hook. Do not edit.
|
|
2
|
+
// Form libraries: a Zubra control as a field of React Hook Form, TanStack Form, VeeValidate or
|
|
3
|
+
// Felte. Each helper turns what the library hands you for a field into the props (or the Svelte
|
|
4
|
+
// action) a Zubra control takes, through its two-way binding: a `<prop>` and its `<prop>change`
|
|
5
|
+
// event (`value` and `valuechange` by default).
|
|
6
|
+
//
|
|
7
|
+
// React Hook Form <Stepper {...registerProps(register('seats'))} />
|
|
8
|
+
// <Controller name="seats" render={({ field }) => <Stepper {...fieldProps(field)} />} />
|
|
9
|
+
// TanStack Form <form.Field name="seats">{(field) => <Stepper {...fieldProps(field)} />}</form.Field>
|
|
10
|
+
// VeeValidate <Stepper v-bind="vueFieldProps(useField('seats'))" />
|
|
11
|
+
// Felte <zb-stepper use:felteControl={createField('seats')}>
|
|
12
|
+
//
|
|
13
|
+
// Nothing here imports a library: each helper reads the shape the library documents. Native
|
|
14
|
+
// form submission needs none of this; a Zubra control with `form-associated` is already a form
|
|
15
|
+
// control (FormData, `<form method=post>`, server actions).
|
|
16
|
+
|
|
17
|
+
const handler = (prop) => `on${prop.toLowerCase()}change`; // the React wrapper takes any casing
|
|
18
|
+
const unref = (value) => (value && typeof value === 'object' && value.__v_isRef ? value.value : value);
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* React Hook Form's `register(name)` as props for a wrapped Zubra control: the control's
|
|
22
|
+
* `value`, its `valuechange` reported as a change, blur reported as a blur, and the element as
|
|
23
|
+
* the ref (so `reset()` and `setValue()` write its `value`, and `setFocus()` focuses it). For a
|
|
24
|
+
* control whose model isn't `value`, use `fieldProps` with a `<Controller>`.
|
|
25
|
+
*/
|
|
26
|
+
export function registerProps(registration) {
|
|
27
|
+
const { name, ref, onChange, onBlur, disabled } = registration;
|
|
28
|
+
return {
|
|
29
|
+
name,
|
|
30
|
+
ref,
|
|
31
|
+
...(disabled === undefined ? {} : { disabled }),
|
|
32
|
+
onvaluechange: (event) => onChange({ type: 'change', target: { name, value: event.detail } }),
|
|
33
|
+
onBlur: (event) => onBlur({ type: 'blur', target: { name, value: event.currentTarget?.value } }),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A field's props for a wrapped Zubra control in React, from React Hook Form's `<Controller>`
|
|
39
|
+
* (`{ value, onChange, onBlur, name, ref }`) or TanStack Form's field API
|
|
40
|
+
* (`{ state: { value }, handleChange, handleBlur, name }`). `prop` names the control's model
|
|
41
|
+
* (`value` by default).
|
|
42
|
+
*/
|
|
43
|
+
export function fieldProps(field, { prop = 'value' } = {}) {
|
|
44
|
+
const tanstack = typeof field.handleChange === 'function';
|
|
45
|
+
const value = tanstack ? field.state.value : field.value;
|
|
46
|
+
const change = tanstack ? field.handleChange : field.onChange;
|
|
47
|
+
const blur = tanstack ? field.handleBlur : field.onBlur;
|
|
48
|
+
return {
|
|
49
|
+
name: field.name,
|
|
50
|
+
[prop]: value,
|
|
51
|
+
[handler(prop)]: (event) => change(event.detail),
|
|
52
|
+
onBlur: () => blur(),
|
|
53
|
+
...(field.ref ? { ref: field.ref } : {}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A field's props for a wrapped Zubra control in Vue, from VeeValidate's `useField()` (whose
|
|
59
|
+
* `value` is a ref) or the `field` a `<Field v-slot="{ field }">` gives. `prop` names the
|
|
60
|
+
* control's model (`value` by default).
|
|
61
|
+
*/
|
|
62
|
+
export function vueFieldProps(field, { prop = 'value' } = {}) {
|
|
63
|
+
const change = field.handleChange ?? field.onChange;
|
|
64
|
+
const blur = field.handleBlur ?? field.onBlur;
|
|
65
|
+
const value = 'value' in field ? unref(field.value) : field.modelValue;
|
|
66
|
+
return {
|
|
67
|
+
name: unref(field.name),
|
|
68
|
+
[prop]: value,
|
|
69
|
+
[`onUpdate:${prop}`]: (next) => (Array.isArray(change) ? change.forEach((fn) => fn(next)) : change(next)),
|
|
70
|
+
// The control's own focus leaves it: `blur` doesn't bubble out of its inner input, `focusout` does.
|
|
71
|
+
onFocusout: (event) => (Array.isArray(blur) ? blur.forEach((fn) => fn(event)) : blur?.(event)),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Felte: a Svelte action (or a plain function for `@felte/vanilla`) that connects a Zubra control
|
|
77
|
+
* to a field from Felte's `createField(name)`. Felte reads native inputs, so the field keeps a
|
|
78
|
+
* hidden one in step with the control: each `<prop>change` is reported as input, focus leaving
|
|
79
|
+
* the control as a blur, and Felte's own writes (`reset()`, `setFields()`) reach the control. Returns `{ destroy }`.
|
|
80
|
+
*
|
|
81
|
+
* <zb-stepper use:felteControl={createField('seats')}></zb-stepper>
|
|
82
|
+
*/
|
|
83
|
+
export function felteControl(node, created, { prop = 'value' } = {}) {
|
|
84
|
+
const field = created?.field ? created : null;
|
|
85
|
+
if (!field) throw new TypeError("zubra: felteControl() needs the result of Felte's createField(name)");
|
|
86
|
+
const action = field.field(node) ?? {};
|
|
87
|
+
// Felte puts its hidden input in place, after the control, on the next task. Start it at the
|
|
88
|
+
// control's value; keep a number a number (Felte reads `type="number"` inputs as numbers, and this
|
|
89
|
+
// one stays hidden); and pass Felte's own writes to it (`reset()`, `setFields()`) to the control.
|
|
90
|
+
let writing = false;
|
|
91
|
+
const start = setTimeout(() => {
|
|
92
|
+
const input = node.nextElementSibling;
|
|
93
|
+
if (input?.localName === 'input' && input.type === 'hidden') {
|
|
94
|
+
if (typeof node[prop] === 'number') {
|
|
95
|
+
input.type = 'number';
|
|
96
|
+
input.hidden = true;
|
|
97
|
+
}
|
|
98
|
+
const own = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
|
|
99
|
+
Object.defineProperty(input, 'value', {
|
|
100
|
+
configurable: true,
|
|
101
|
+
get: () => own.get.call(input),
|
|
102
|
+
set: (value) => {
|
|
103
|
+
own.set.call(input, value);
|
|
104
|
+
if (!writing) node[prop] = input.type === 'number' && value !== '' ? Number(value) : value;
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
report(node[prop]);
|
|
109
|
+
});
|
|
110
|
+
const report = (value) => {
|
|
111
|
+
writing = true;
|
|
112
|
+
try { field.onInput(value); } finally { writing = false; }
|
|
113
|
+
};
|
|
114
|
+
const change = (event) => report(event.detail);
|
|
115
|
+
const blur = () => field.onBlur();
|
|
116
|
+
node.addEventListener(prop.toLowerCase() + 'change', change);
|
|
117
|
+
node.addEventListener('focusout', blur);
|
|
118
|
+
return {
|
|
119
|
+
destroy() {
|
|
120
|
+
clearTimeout(start);
|
|
121
|
+
node.removeEventListener(prop.toLowerCase() + 'change', change);
|
|
122
|
+
node.removeEventListener('focusout', blur);
|
|
123
|
+
action.destroy?.();
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Generated by scripts/build-production.js from src/navigation.js: the runtime without hot reloading or the DevTools hook. Do not edit.
|
|
2
|
+
// Links inside components, through the app's router: a plain `<a href>` in a Zubra component
|
|
3
|
+
// navigates with the router the app already has (React Router, Next.js, Vue Router, SvelteKit,
|
|
4
|
+
// Angular Router…) instead of reloading the page. Not a router: one listener that hands the
|
|
5
|
+
// app's router the URL, and otherwise leaves the link alone.
|
|
6
|
+
//
|
|
7
|
+
// routeLinks((to) => router.push(to)) // Vue Router; returns a function that stops it
|
|
8
|
+
// useRouteLinks(useNavigate()) // React Router (`@zubra/runtime/react`)
|
|
9
|
+
// useRouteLinks(useRouter().push) // Next.js
|
|
10
|
+
// routeLinks((to) => goto(to)) // SvelteKit, in onMount
|
|
11
|
+
// routeLinks((to) => router.navigateByUrl(to)) // Angular
|
|
12
|
+
//
|
|
13
|
+
// Without JavaScript, or for a link it leaves alone, the link is a link. It leaves alone: a click
|
|
14
|
+
// something already handled (`preventDefault()`), a modified or non-primary click (new tab,
|
|
15
|
+
// window, download), a `target` other than `_self`, `download`, `rel="external"`, another
|
|
16
|
+
// origin, and a link to a place on the current page (`#…`). Only links inside a Zubra component
|
|
17
|
+
// are routed by default (the app's own links are its router's business); `within` changes that.
|
|
18
|
+
//
|
|
19
|
+
// If the app's router already intercepts the Navigation API's `navigate` event (Baseline since
|
|
20
|
+
// January 2026), links in components already go through it, and none of this is needed.
|
|
21
|
+
|
|
22
|
+
/** A Zubra component's host: its class carries the compiled `zubra` metadata. */
|
|
23
|
+
export const isComponent = (node) => Boolean(node?.constructor?.zubra);
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Route clicks on links inside Zubra components through `navigate(to, { event, anchor, url })`,
|
|
27
|
+
* where `to` is the path, query and hash (`/seats?row=b#top`). Returns a function that stops it.
|
|
28
|
+
* `within(node)` decides which ancestors count (by default, a Zubra component's host); `root` is
|
|
29
|
+
* where to listen (by default, the document).
|
|
30
|
+
*/
|
|
31
|
+
export function routeLinks(navigate, { within = isComponent, root = globalThis.document } = {}) {
|
|
32
|
+
if (typeof navigate !== 'function') throw new TypeError('zubra: routeLinks() needs a function that navigates, such as (to) => router.push(to)');
|
|
33
|
+
if (!root) return () => {};
|
|
34
|
+
const click = (event) => {
|
|
35
|
+
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
36
|
+
const path = event.composedPath();
|
|
37
|
+
const at = path.findIndex((node) => node.localName === 'a' && node.hasAttribute?.('href'));
|
|
38
|
+
if (at < 0) return;
|
|
39
|
+
const anchor = path[at];
|
|
40
|
+
if (!path.slice(at + 1).some((node) => node.nodeType === 1 && within(node))) return;
|
|
41
|
+
const target = anchor.getAttribute('target');
|
|
42
|
+
if ((target && target !== '_self') || anchor.hasAttribute('download')) return;
|
|
43
|
+
if ((anchor.getAttribute('rel') ?? '').split(/\s+/).includes('external')) return;
|
|
44
|
+
const url = new URL(anchor.href, anchor.baseURI);
|
|
45
|
+
const here = new URL(globalThis.location.href);
|
|
46
|
+
if (url.origin !== here.origin) return;
|
|
47
|
+
if (url.hash && url.pathname === here.pathname && url.search === here.search) return;
|
|
48
|
+
event.preventDefault();
|
|
49
|
+
navigate(url.pathname + url.search + url.hash, { event, anchor, url });
|
|
50
|
+
};
|
|
51
|
+
root.addEventListener('click', click);
|
|
52
|
+
return () => root.removeEventListener('click', click);
|
|
53
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Generated by scripts/build-production.js from src/outlet.js: the runtime without hot reloading or the DevTools hook. Do not edit.
|
|
2
|
+
// Outlets (experimental): a place in a Zubra component where the app's framework renders its
|
|
3
|
+
// own components, with the app's context, state and events, through a portal.
|
|
4
|
+
//
|
|
5
|
+
// <!-- row-list.zb -->
|
|
6
|
+
// <zb-each items={items} as="item" key={item.id}>
|
|
7
|
+
// <li><zb-outlet name="row" item={item}></zb-outlet></li>
|
|
8
|
+
// </zb-each>
|
|
9
|
+
//
|
|
10
|
+
// // React
|
|
11
|
+
// <RowList items={rows} renderRow={(item) => <Row item={item} />} />
|
|
12
|
+
//
|
|
13
|
+
// Slots let the consumer put content *in* a component; an outlet lets the component ask the
|
|
14
|
+
// consumer for content *per item*, which is what render props and scoped slots do inside one
|
|
15
|
+
// framework. The component stays the owner of the structure (the list, its keys, its order);
|
|
16
|
+
// the framework renders what goes in each outlet, as a portal, so React context, hooks and
|
|
17
|
+
// event handlers work there as anywhere else in the app.
|
|
18
|
+
//
|
|
19
|
+
// Protocol: a connected `<zb-outlet>` fires a bubbling, composed `outletconnect` event. A
|
|
20
|
+
// listener that serves outlets of that name calls `event.claim({ change, disconnect })` and
|
|
21
|
+
// stops it: `change(outlet)` is called when the outlet's `item` changes, `disconnect(outlet)`
|
|
22
|
+
// when it leaves the document. Outlets connected before anyone listened are found with
|
|
23
|
+
// `outletsOf(host)`. A keyed move disconnects and reconnects the outlet node itself, so a
|
|
24
|
+
// renderer that keys its portal by the node (as the React adapter does) keeps what's in it.
|
|
25
|
+
const Base = globalThis.HTMLElement ?? class {};
|
|
26
|
+
|
|
27
|
+
export class ZubraOutletElement extends Base {
|
|
28
|
+
#item = undefined;
|
|
29
|
+
/** Who renders into this outlet: `{ change, disconnect }`, or null. */
|
|
30
|
+
owner = null;
|
|
31
|
+
|
|
32
|
+
/** Which of the consumer's renderers fills it. */
|
|
33
|
+
get name() {
|
|
34
|
+
return this.getAttribute('name') ?? '';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The data the component gives the renderer for this outlet. */
|
|
38
|
+
get item() {
|
|
39
|
+
return this.#item;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
set item(value) {
|
|
43
|
+
if (Object.is(value, this.#item)) return;
|
|
44
|
+
this.#item = value;
|
|
45
|
+
this.owner?.change(this);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
connectedCallback() {
|
|
49
|
+
if (!this.style.display) this.style.display = 'contents';
|
|
50
|
+
if (this.owner) return;
|
|
51
|
+
const event = new Event('outletconnect', { bubbles: true, composed: true });
|
|
52
|
+
event.outlet = this;
|
|
53
|
+
event.claim = (owner) => {
|
|
54
|
+
this.owner = owner;
|
|
55
|
+
event.stopPropagation();
|
|
56
|
+
};
|
|
57
|
+
this.dispatchEvent(event);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
disconnectedCallback() {
|
|
61
|
+
const owner = this.owner;
|
|
62
|
+
this.owner = null;
|
|
63
|
+
owner?.disconnect(this);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The unclaimed outlets inside `host` (its light DOM and its shadow root), in document order. */
|
|
68
|
+
export function outletsOf(host) {
|
|
69
|
+
const found = [...host.querySelectorAll('zb-outlet')];
|
|
70
|
+
if (host.shadowRoot) found.push(...host.shadowRoot.querySelectorAll('zb-outlet'));
|
|
71
|
+
return found.filter((outlet) => !outlet.owner);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Define `<zb-outlet>` (once; a no-op without `customElements`). */
|
|
75
|
+
export function defineOutletElement() {
|
|
76
|
+
const registry = globalThis.customElements;
|
|
77
|
+
if (registry && !registry.get('zb-outlet')) registry.define('zb-outlet', ZubraOutletElement);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
defineOutletElement();
|