@vielzeug/ore 1.0.5 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -3
- package/dist/_dev.cjs +1 -1
- package/dist/_dev.cjs.map +1 -1
- package/dist/_dev.js +1 -1
- package/dist/_dev.js.map +1 -1
- package/dist/aria.cjs +1 -1
- package/dist/aria.cjs.map +1 -1
- package/dist/aria.d.ts +16 -8
- package/dist/aria.d.ts.map +1 -1
- package/dist/aria.js +1 -1
- package/dist/aria.js.map +1 -1
- package/dist/base-element.cjs +1 -1
- package/dist/base-element.cjs.map +1 -1
- package/dist/base-element.d.ts +36 -1
- package/dist/base-element.d.ts.map +1 -1
- package/dist/base-element.js +1 -1
- package/dist/base-element.js.map +1 -1
- package/dist/component-types.d.ts +13 -76
- package/dist/component-types.d.ts.map +1 -1
- package/dist/context.cjs +1 -1
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.ts +11 -2
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +1 -1
- package/dist/context.js.map +1 -1
- package/dist/define.cjs.map +1 -1
- package/dist/define.d.ts +13 -12
- package/dist/define.d.ts.map +1 -1
- package/dist/define.js.map +1 -1
- package/dist/directives/each.cjs +1 -1
- package/dist/directives/each.cjs.map +1 -1
- package/dist/directives/each.d.ts +6 -0
- package/dist/directives/each.d.ts.map +1 -1
- package/dist/directives/each.js +1 -1
- package/dist/directives/each.js.map +1 -1
- package/dist/directives/raw.cjs +1 -1
- package/dist/directives/raw.cjs.map +1 -1
- package/dist/directives/raw.d.ts.map +1 -1
- package/dist/directives/raw.js +1 -1
- package/dist/directives/raw.js.map +1 -1
- package/dist/directives/when.cjs +1 -1
- package/dist/directives/when.cjs.map +1 -1
- package/dist/directives/when.d.ts.map +1 -1
- package/dist/directives/when.js +1 -1
- package/dist/directives/when.js.map +1 -1
- package/dist/errors.cjs +2 -2
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +23 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -2
- package/dist/errors.js.map +1 -1
- package/dist/forms/context.cjs +2 -0
- package/dist/forms/context.cjs.map +1 -0
- package/dist/{form-context.d.ts → forms/context.d.ts} +5 -5
- package/dist/forms/context.d.ts.map +1 -0
- package/dist/forms/context.js +2 -0
- package/dist/forms/context.js.map +1 -0
- package/dist/forms/field.cjs +2 -0
- package/dist/forms/field.cjs.map +1 -0
- package/dist/{form-field.d.ts → forms/field.d.ts} +19 -2
- package/dist/forms/field.d.ts.map +1 -0
- package/dist/forms/field.js +2 -0
- package/dist/forms/field.js.map +1 -0
- package/dist/forms/index.d.ts +11 -0
- package/dist/forms/index.d.ts.map +1 -0
- package/dist/forms.cjs +1 -0
- package/dist/forms.js +1 -0
- package/dist/host-bind.cjs +1 -1
- package/dist/host-bind.cjs.map +1 -1
- package/dist/host-bind.d.ts +8 -2
- package/dist/host-bind.d.ts.map +1 -1
- package/dist/host-bind.js +1 -1
- package/dist/host-bind.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +8 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/ore.cjs +2 -2
- package/dist/ore.cjs.map +1 -1
- package/dist/ore.iife.js +2 -2
- package/dist/ore.iife.js.map +1 -1
- package/dist/ore.js +2 -2
- package/dist/ore.js.map +1 -1
- package/dist/props.cjs +1 -1
- package/dist/props.cjs.map +1 -1
- package/dist/props.d.ts.map +1 -1
- package/dist/props.js +1 -1
- package/dist/props.js.map +1 -1
- package/dist/runtime.cjs +1 -1
- package/dist/runtime.cjs.map +1 -1
- package/dist/runtime.d.ts +32 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +1 -1
- package/dist/runtime.js.map +1 -1
- package/dist/slots.cjs +1 -1
- package/dist/slots.cjs.map +1 -1
- package/dist/slots.d.ts +12 -1
- package/dist/slots.d.ts.map +1 -1
- package/dist/slots.js +1 -1
- package/dist/slots.js.map +1 -1
- package/dist/template/bindings.cjs +1 -1
- package/dist/template/bindings.cjs.map +1 -1
- package/dist/template/bindings.d.ts.map +1 -1
- package/dist/template/bindings.js +1 -1
- package/dist/template/bindings.js.map +1 -1
- package/dist/template/compiler.cjs +1 -1
- package/dist/template/compiler.cjs.map +1 -1
- package/dist/template/compiler.d.ts +11 -1
- package/dist/template/compiler.d.ts.map +1 -1
- package/dist/template/compiler.js +1 -1
- package/dist/template/compiler.js.map +1 -1
- package/dist/template/instantiator.cjs +1 -1
- package/dist/template/instantiator.cjs.map +1 -1
- package/dist/template/instantiator.d.ts +0 -5
- package/dist/template/instantiator.d.ts.map +1 -1
- package/dist/template/instantiator.js +1 -1
- package/dist/template/instantiator.js.map +1 -1
- package/dist/testing/dom.cjs +2 -0
- package/dist/testing/dom.cjs.map +1 -0
- package/dist/testing/dom.d.ts +22 -0
- package/dist/testing/dom.d.ts.map +1 -0
- package/dist/testing/dom.js +2 -0
- package/dist/testing/dom.js.map +1 -0
- package/dist/testing/form-internals-polyfill.cjs +2 -0
- package/dist/testing/form-internals-polyfill.cjs.map +1 -0
- package/dist/testing/form-internals-polyfill.d.ts +17 -0
- package/dist/testing/form-internals-polyfill.d.ts.map +1 -0
- package/dist/testing/form-internals-polyfill.js +2 -0
- package/dist/testing/form-internals-polyfill.js.map +1 -0
- package/dist/testing/mount.cjs.map +1 -1
- package/dist/testing/mount.d.ts +4 -4
- package/dist/testing/mount.d.ts.map +1 -1
- package/dist/testing/mount.js.map +1 -1
- package/dist/testing/render-hook.cjs +1 -1
- package/dist/testing/render-hook.cjs.map +1 -1
- package/dist/testing/render-hook.d.ts +6 -6
- package/dist/testing/render-hook.d.ts.map +1 -1
- package/dist/testing/render-hook.js +1 -1
- package/dist/testing/render-hook.js.map +1 -1
- package/dist/testing/testing.cjs +1 -1
- package/dist/testing/testing.cjs.map +1 -1
- package/dist/testing/testing.d.ts +7 -1
- package/dist/testing/testing.d.ts.map +1 -1
- package/dist/testing/testing.js +1 -1
- package/dist/testing/testing.js.map +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +1 -1
- package/dist/utils/emit.cjs +1 -1
- package/dist/utils/emit.cjs.map +1 -1
- package/dist/utils/emit.d.ts +28 -5
- package/dist/utils/emit.d.ts.map +1 -1
- package/dist/utils/emit.js +1 -1
- package/dist/utils/emit.js.map +1 -1
- package/package.json +12 -5
- package/dist/context-bag.cjs +0 -2
- package/dist/context-bag.cjs.map +0 -1
- package/dist/context-bag.d.ts +0 -12
- package/dist/context-bag.d.ts.map +0 -1
- package/dist/context-bag.js +0 -2
- package/dist/context-bag.js.map +0 -1
- package/dist/form-context.cjs +0 -2
- package/dist/form-context.cjs.map +0 -1
- package/dist/form-context.d.ts.map +0 -1
- package/dist/form-context.js +0 -2
- package/dist/form-context.js.map +0 -1
- package/dist/form-field.cjs +0 -2
- package/dist/form-field.cjs.map +0 -1
- package/dist/form-field.d.ts.map +0 -1
- package/dist/form-field.js +0 -2
- package/dist/form-field.js.map +0 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
|
|
10
10
|
**Package:** `@vielzeug/ore` · **Category:** UI Primitives
|
|
11
11
|
|
|
12
|
-
**Key exports:** `define`, `html`, `css`, `prop`, `ref`, `
|
|
12
|
+
**Key exports:** `define`, `html`, `css`, `prop`, `ref`, `onMounted`, `onCleanup`, `onEvent`, `onElement`, `watch`, `bind`, `aria`, `provide`, `inject`, `useEmit`, `useSlots`, `getHost`, `each`, `when`, `model`, `live`
|
|
13
13
|
|
|
14
14
|
**When to use:** Functional custom-element authoring with typed props, reactive templates, lifecycle helpers, observers, and testing utilities.
|
|
15
15
|
|
|
@@ -30,7 +30,8 @@ yarn add @vielzeug/ore
|
|
|
30
30
|
## Quick Start
|
|
31
31
|
|
|
32
32
|
```ts
|
|
33
|
-
import { computed,
|
|
33
|
+
import { computed, signal } from '@vielzeug/ripple';
|
|
34
|
+
import { bind, css, define, html, onMounted, prop } from '@vielzeug/ore';
|
|
34
35
|
|
|
35
36
|
define('my-counter', {
|
|
36
37
|
props: {
|
|
@@ -45,7 +46,7 @@ define('my-counter', {
|
|
|
45
46
|
}
|
|
46
47
|
`,
|
|
47
48
|
],
|
|
48
|
-
setup(props
|
|
49
|
+
setup(props) {
|
|
49
50
|
const count = signal(0);
|
|
50
51
|
const doubled = computed(() => count.value * 2);
|
|
51
52
|
|
|
@@ -61,6 +62,38 @@ define('my-counter', {
|
|
|
61
62
|
});
|
|
62
63
|
```
|
|
63
64
|
|
|
65
|
+
`setup()` takes only `props`. Everything else — lifecycle hooks (`onMounted`, `onCleanup`, `onEvent`, `onElement`, `watch`), host bindings (`bind`, `aria`), context (`inject`/`injectStrict`/`provide`), and per-instance factories (`useEmit<Emits>()`, `useSlots<SlotNames>()`) — are plain functions imported from `@vielzeug/ore`, resolved through the current component while `setup()` (or a composable it calls) is running. Form-association helpers (`useField`, `createFormContext`) live under `@vielzeug/ore/forms`.
|
|
66
|
+
|
|
67
|
+
## Testing
|
|
68
|
+
|
|
69
|
+
`@vielzeug/ore/testing` mounts real custom elements into jsdom/happy-dom and gives you `act`/query/dispose in one fixture — no separate render + flush + query steps to remember:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { mount } from '@vielzeug/ore/testing';
|
|
73
|
+
|
|
74
|
+
const { element, query, act, dispose } = await mount('my-counter');
|
|
75
|
+
|
|
76
|
+
expect(query('button')?.textContent).toContain('Count: 0');
|
|
77
|
+
|
|
78
|
+
await act(() => query('button')?.click());
|
|
79
|
+
|
|
80
|
+
expect(query('button')?.textContent).toContain('Count: 1');
|
|
81
|
+
|
|
82
|
+
dispose(); // or: use the fixture as `using fixture = await mount(...)`
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Register `cleanup` once so mounted elements don't leak between tests:
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
// vitest.setup.ts
|
|
89
|
+
import { afterEach } from 'vitest';
|
|
90
|
+
import { install } from '@vielzeug/ore/testing';
|
|
91
|
+
|
|
92
|
+
install(afterEach);
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Also available from `@vielzeug/ore/testing`: `renderHook` (test a composable in isolation, without a full template), `fire`/`user` (dispatch DOM/user-interaction events), `waitFor`/`waitForEvent`, and `within` (scoped queries for slotted content). See the [Usage Guide](https://vielzeug.dev/ore/usage) for the full API.
|
|
96
|
+
|
|
64
97
|
## Documentation
|
|
65
98
|
|
|
66
99
|
- [Overview](https://vielzeug.dev/ore/)
|
package/dist/_dev.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=!globalThis.__ORE_PROD__;function t(t){e&&console.warn(`[@vielzeug/ore] ${t}`)}function n(t,...n){e&&console.error(`[@vielzeug/ore] ${t}`,...n)}
|
|
1
|
+
var e=!globalThis.__ORE_PROD__;function t(t){e&&console.warn(`[@vielzeug/ore] ${t}`)}function n(t,...n){e&&console.error(`[@vielzeug/ore] ${t}`,...n)}exports.error=n,exports.warn=t;
|
|
2
2
|
//# sourceMappingURL=_dev.cjs.map
|
package/dist/_dev.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __ORE_PROD__?: boolean }).__ORE_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/ore] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/ore] ${msg}`, ...args);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA0C,aAG1D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,mBAAmB,GAAK,CAClD,CAGA,SAAgB,EAAM,EAAa,GAAG,EAAuB,CACvD,GAAO,QAAQ,MAAM,mBAAmB,IAAO,GAAG,CAAI,CAC5D
|
|
1
|
+
{"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __ORE_PROD__?: boolean }).__ORE_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/ore] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/ore] ${msg}`, ...args);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA0C,aAG1D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,mBAAmB,GAAK,CAClD,CAGA,SAAgB,EAAM,EAAa,GAAG,EAAuB,CACvD,GAAO,QAAQ,MAAM,mBAAmB,IAAO,GAAG,CAAI,CAC5D"}
|
package/dist/_dev.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e=!globalThis.__ORE_PROD__;function t(t){e&&console.warn(`[@vielzeug/ore] ${t}`)}function n(t,...n){e&&console.error(`[@vielzeug/ore] ${t}`,...n)}
|
|
1
|
+
var e=!globalThis.__ORE_PROD__;function t(t){e&&console.warn(`[@vielzeug/ore] ${t}`)}function n(t,...n){e&&console.error(`[@vielzeug/ore] ${t}`,...n)}export{n as error,t as warn};
|
|
2
2
|
//# sourceMappingURL=_dev.js.map
|
package/dist/_dev.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __ORE_PROD__?: boolean }).__ORE_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/ore] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/ore] ${msg}`, ...args);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA0C,aAG1D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,mBAAmB,GAAK,CAClD,CAGA,SAAgB,EAAM,EAAa,GAAG,EAAuB,CACvD,GAAO,QAAQ,MAAM,mBAAmB,IAAO,GAAG,CAAI,CAC5D
|
|
1
|
+
{"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __ORE_PROD__?: boolean }).__ORE_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/ore] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/ore] ${msg}`, ...args);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAA0C,aAG1D,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,mBAAmB,GAAK,CAClD,CAGA,SAAgB,EAAM,EAAa,GAAG,EAAuB,CACvD,GAAO,QAAQ,MAAM,mBAAmB,IAAO,GAAG,CAAI,CAC5D"}
|
package/dist/aria.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./
|
|
1
|
+
const e=require("./utils/aria.cjs"),t=require("./host-bind.cjs");var n=(n,r)=>{let i={};for(let[t,n]of Object.entries(r))i[e.normalizeAriaKey(t)]=n;return t.bind({attr:i},{target:n})};exports.aria=n;
|
|
2
2
|
//# sourceMappingURL=aria.cjs.map
|
package/dist/aria.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aria.cjs","names":[],"sources":["../src/aria.ts"],"sourcesContent":["/**\n * Reactive ARIA attribute sync
|
|
1
|
+
{"version":3,"file":"aria.cjs","names":[],"sources":["../src/aria.ts"],"sourcesContent":["/**\n * Reactive ARIA attribute sync.\n *\n * `aria()` is a thin wrapper over `bind({ attr })` — the two used to carry\n * independent copies of the same \"static | getter | signal → attribute write\"\n * logic, which had already drifted (this file's writes bypassed the\n * `on*`/dangerous-URL-scheme hardening that `setAttr()` gives every other\n * attribute write in the package). `aria()` now exists purely to normalize\n * bare ARIA property names (`expanded` → `aria-expanded`) before delegating —\n * for attributes that are already fully-qualified, `bind({ attr }, { target })`\n * is equivalent.\n */\n\nimport { bind, type HostBindingValue } from './host-bind';\nimport { normalizeAriaKey } from './utils/aria';\n\nexport type AriaConfig = Record<string, HostBindingValue>;\n\n/**\n * Reactively sync ARIA attributes on any element, auto-cleanup on component\n * disconnect. Returns a cleanup function that removes all reactive bindings.\n */\nexport const aria = (target: Element, config: AriaConfig): (() => void) => {\n const attr: Record<string, HostBindingValue> = {};\n\n for (const [key, value] of Object.entries(config)) attr[normalizeAriaKey(key)] = value;\n\n return bind({ attr }, { target });\n};\n"],"mappings":"iEAsBA,IAAa,GAAQ,EAAiB,IAAqC,CACzE,IAAM,EAAyC,CAAC,EAEhD,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EAAG,EAAK,EAAA,iBAAiB,CAAG,GAAK,EAEjF,OAAO,EAAA,KAAK,CAAE,MAAK,EAAG,CAAE,QAAO,CAAC,CAClC"}
|
package/dist/aria.d.ts
CHANGED
|
@@ -1,12 +1,20 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Reactive ARIA attribute sync
|
|
2
|
+
* Reactive ARIA attribute sync.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* `aria()` is a thin wrapper over `bind({ attr })` — the two used to carry
|
|
5
|
+
* independent copies of the same "static | getter | signal → attribute write"
|
|
6
|
+
* logic, which had already drifted (this file's writes bypassed the
|
|
7
|
+
* `on*`/dangerous-URL-scheme hardening that `setAttr()` gives every other
|
|
8
|
+
* attribute write in the package). `aria()` now exists purely to normalize
|
|
9
|
+
* bare ARIA property names (`expanded` → `aria-expanded`) before delegating —
|
|
10
|
+
* for attributes that are already fully-qualified, `bind({ attr }, { target })`
|
|
11
|
+
* is equivalent.
|
|
6
12
|
*/
|
|
7
|
-
import { type
|
|
8
|
-
type
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
13
|
+
import { type HostBindingValue } from './host-bind';
|
|
14
|
+
export type AriaConfig = Record<string, HostBindingValue>;
|
|
15
|
+
/**
|
|
16
|
+
* Reactively sync ARIA attributes on any element, auto-cleanup on component
|
|
17
|
+
* disconnect. Returns a cleanup function that removes all reactive bindings.
|
|
18
|
+
*/
|
|
19
|
+
export declare const aria: (target: Element, config: AriaConfig) => (() => void);
|
|
12
20
|
//# sourceMappingURL=aria.d.ts.map
|
package/dist/aria.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aria.d.ts","sourceRoot":"","sources":["../src/aria.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"aria.d.ts","sourceRoot":"","sources":["../src/aria.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAQ,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG1D,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;AAE1D;;;GAGG;AACH,eAAO,MAAM,IAAI,GAAI,QAAQ,OAAO,EAAE,QAAQ,UAAU,KAAG,CAAC,MAAM,IAAI,CAMrE,CAAC"}
|
package/dist/aria.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{normalizeAriaKey as e}from"./utils/aria.js";import{bind as t}from"./host-bind.js";var n=(n,r)=>{let i={};for(let[t,n]of Object.entries(r))i[e(t)]=n;return t({attr:i},{target:n})};export{n as aria};
|
|
2
2
|
//# sourceMappingURL=aria.js.map
|
package/dist/aria.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aria.js","names":[],"sources":["../src/aria.ts"],"sourcesContent":["/**\n * Reactive ARIA attribute sync
|
|
1
|
+
{"version":3,"file":"aria.js","names":[],"sources":["../src/aria.ts"],"sourcesContent":["/**\n * Reactive ARIA attribute sync.\n *\n * `aria()` is a thin wrapper over `bind({ attr })` — the two used to carry\n * independent copies of the same \"static | getter | signal → attribute write\"\n * logic, which had already drifted (this file's writes bypassed the\n * `on*`/dangerous-URL-scheme hardening that `setAttr()` gives every other\n * attribute write in the package). `aria()` now exists purely to normalize\n * bare ARIA property names (`expanded` → `aria-expanded`) before delegating —\n * for attributes that are already fully-qualified, `bind({ attr }, { target })`\n * is equivalent.\n */\n\nimport { bind, type HostBindingValue } from './host-bind';\nimport { normalizeAriaKey } from './utils/aria';\n\nexport type AriaConfig = Record<string, HostBindingValue>;\n\n/**\n * Reactively sync ARIA attributes on any element, auto-cleanup on component\n * disconnect. Returns a cleanup function that removes all reactive bindings.\n */\nexport const aria = (target: Element, config: AriaConfig): (() => void) => {\n const attr: Record<string, HostBindingValue> = {};\n\n for (const [key, value] of Object.entries(config)) attr[normalizeAriaKey(key)] = value;\n\n return bind({ attr }, { target });\n};\n"],"mappings":"yFAsBA,IAAa,GAAQ,EAAiB,IAAqC,CACzE,IAAM,EAAyC,CAAC,EAEhD,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EAAG,EAAK,EAAiB,CAAG,GAAK,EAEjF,OAAO,EAAK,CAAE,MAAK,EAAG,CAAE,QAAO,CAAC,CAClC"}
|
package/dist/base-element.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./_dev.cjs"),t=require("./errors.cjs");require("./types/bindings.cjs");const n=require("./runtime.cjs"),r=require("./
|
|
1
|
+
const e=require("./_dev.cjs"),t=require("./errors.cjs");require("./types/bindings.cjs");const n=require("./runtime.cjs"),r=require("./props.cjs"),i=require("./types.cjs"),a=require("./utils/css.cjs");let o=require("@vielzeug/ripple");var s=()=>({formResetCallbacks:[],generation:0,mountCallbacks:[],phase:i.ComponentPhase.UNINITIALIZED,scope:(0,o.scope)(),templateResult:null}),c=class extends HTMLElement{static _definition;static _normalizedPropDefs;static formAssociated=!1;static observedAttributes=[];_component;constructor(){super();let e=this.constructor._definition;e?.shadow!==!1&&this.attachShadow({mode:`open`,...e?.shadow}),this._component=s()}connectedCallback(){(0,o.untrack)(()=>{this._component.phase===i.ComponentPhase.UNINITIALIZED&&this._runSetup(),this._init()}),this.dispatchEvent(new CustomEvent(i.LIFECYCLE_EVENTS.CONNECT,{bubbles:!1,composed:!1}))}attributeChangedCallback(e,t,n){if(t===n)return;let i=r.getPropMeta(this,e);if(!i)return;let a=i.parse(n);Object.is((0,o.untrack)(()=>i.signal.value),a)||(i.signal.value=a)}disconnectedCallback(){this._component.generation++,this._component.phase=i.ComponentPhase.UNMOUNTED,this.dispatchEvent(new CustomEvent(i.LIFECYCLE_EVENTS.DISCONNECT,{bubbles:!1,composed:!1})),this._component.scope.dispose(),this._component.formResetCallbacks=[],this._component.mountCallbacks=[],this._component.phase=i.ComponentPhase.UNINITIALIZED,this._component.scope=(0,o.scope)(),this._component.templateResult=null}formResetCallback(){for(let e of this._component.formResetCallbacks)try{e()}catch(e){this._handleSetupError(e,`form-reset`)}}_handleSetupError(e,n=`setup`){let r=e instanceof Error?e:Error(String(e)),i=new t.OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${n})`,{cause:r,component:this.localName,phase:n}),a=this.constructor._definition;if(a?.onError)try{return a.onError(i,this)}catch{}t.reportRuntimeError(i,this)}_runSetup(){this._component.phase=i.ComponentPhase.SETUP_RUNNING;let e=this.constructor._definition,t=this.constructor._normalizedPropDefs,a={element:this,formResetCallbacks:[],mountCallbacks:[]};try{let o;if(this._component.scope.run(()=>{o=n.runWithContext(a,()=>{let n=t?r.createProps(this,t):{};return e.setup(n)})}),this._component.mountCallbacks.push(...a.mountCallbacks),this._component.formResetCallbacks.push(...a.formResetCallbacks),o!=null&&typeof o.then==`function`){let t=this._component.mountCallbacks.splice(0);this._component.phase=i.ComponentPhase.LOADING,e.loading&&(this._component.templateResult=e.loading()),this._runSetupAsync(o,t,this._component.generation)}else this._component.templateResult=o??null,this._component.phase=i.ComponentPhase.SETUP_DONE}catch(e){let t=this._handleSetupError(e);if(t)this._component.templateResult=t,this._component.phase=i.ComponentPhase.SETUP_DONE;else throw this._component.phase=i.ComponentPhase.UNINITIALIZED,e}}_isStale(e){return this._component.generation!==e||!this.isConnected}async _runSetupAsync(t,n,r){try{let a=await t;if(this._isStale(r)){e.warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);return}this._component.templateResult=a??null,this._component.phase=i.ComponentPhase.SETUP_DONE,this._component.mountCallbacks.push(...n),a&&this._applyResult(a),this._scheduleMountCallbacks()}catch(t){if(this._isStale(r)){e.warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);return}let n=this._handleSetupError(t,`async-setup`);n?(this._component.templateResult=n,this._component.phase=i.ComponentPhase.SETUP_DONE,this._applyResult(n)):this._component.phase=i.ComponentPhase.UNINITIALIZED}}_applyResult(e){e&&((this.shadowRoot??this).replaceChildren(e.fragment),this._component.scope.run(()=>{e.apply(n.onCleanup)}))}_init(){this._applyStyles(),this._mountTemplate(),this._component.phase===i.ComponentPhase.SETUP_DONE&&this._scheduleMountCallbacks()}_applyStyles(){let e=this.constructor._definition;this.shadowRoot&&e?.styles?.length&&(this.shadowRoot.adoptedStyleSheets=e.styles.map(a.loadStylesheet))}_mountTemplate(){let e=this._component.templateResult;e&&this._applyResult(e)}_scheduleMountCallbacks(){if(this._component.mountCallbacks.length===0)return;let e=this._component.generation;queueMicrotask(()=>{if(this._isStale(e))return;let t=this._component.mountCallbacks.splice(0);for(let e of t)try{let t={element:this,formResetCallbacks:[],mountCallbacks:[]};this._component.scope.run(()=>{n.runWithContext(t,()=>{let t=e();typeof t==`function`&&n.onCleanup(t)})}),t.mountCallbacks.length>0&&this._component.mountCallbacks.push(...t.mountCallbacks),t.formResetCallbacks.length>0&&this._component.formResetCallbacks.push(...t.formResetCallbacks)}catch(e){this._handleSetupError(e,`mounted`)}this._component.mountCallbacks.length>0&&this._scheduleMountCallbacks()})}};exports.BaseElement=c;
|
|
2
2
|
//# sourceMappingURL=base-element.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-element.cjs","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { createContextBag } from './context-bag';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport { type OnMountedCallback, onCleanup, type RuntimeContext, runWithContext } from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any, any, any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n const contextBag = createContextBag(this);\n\n return def.setup(setupProps as InferProps<PropInputDefs>, contextBag);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n // Discard stale results: element disconnected+reconnected since this setup started.\n if (this._component.generation !== capturedGeneration || !this.isConnected) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._component.generation !== capturedGeneration || !this.isConnected) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (!this.isConnected || capturedGeneration !== this._component.generation) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = { element: this, mountCallbacks: [] as typeof this._component.mountCallbacks };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"yQAwBA,IAAM,OAA8C,CAClD,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAA,eAAe,cACtB,OAAA,EAAA,EAAA,MAAA,CAAc,EACd,eAAgB,IAClB,GAIa,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,WAAa,EAAqB,CACzC,CAEA,mBAA0B,EACxB,EAAA,EAAA,QAAA,KAAc,CACR,KAAK,WAAW,QAAU,EAAA,eAAe,eAAe,KAAK,UAAU,EAE3E,KAAK,MAAM,CACb,CAAC,EACD,KAAK,cAAc,IAAI,YAAY,EAAA,iBAAiB,QAAS,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,CACnG,CAEA,yBAAyB,EAAc,EAAyB,EAA+B,CAC7F,GAAI,IAAa,EAAU,OAE3B,IAAM,EAAW,EAAA,YAAY,KAAM,CAAI,EAEvC,GAAI,CAAC,EAAU,OAEf,IAAM,EAAS,EAAS,MAAM,CAAQ,EAGnC,OAAO,IAAA,EAAA,EAAA,QAAA,KACQ,EAAS,OAAO,KAAK,EACnC,CACF,IAEA,EAAS,OAAO,MAAQ,EAC5B,CAEA,sBAA6B,CAC3B,KAAK,WAAW,aAChB,KAAK,WAAW,MAAQ,EAAA,eAAe,UACvC,KAAK,cAAc,IAAI,YAAY,EAAA,iBAAiB,WAAY,CAAE,QAAS,GAAO,SAAU,EAAM,CAA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ACxF,CAEA,cAA6B,CAC3B,IAAM,EAAO,KAAK,YAAmC,YAEjD,KAAK,YAAc,GAAK,QAAQ,SAClC,KAAK,WAAW,mBAAqB,EAAI,OAAO,IAAI,EAAA,cAAc,EAEtE,CAEA,gBAA+B,CAC7B,IAAM,EAAS,KAAK,WAAW,eAE1B,GAEL,KAAK,aAAa,CAAM,CAC1B,CAEA,yBAAwC,CACtC,GAAI,KAAK,WAAW,eAAe,SAAW,EAAG,OAEjD,IAAM,EAAqB,KAAK,WAAW,WAE3C,mBAAqB,CACnB,GAAI,CAAC,KAAK,aAAe,IAAuB,KAAK,WAAW,WAAY,OAG5E,IAAM,EAAQ,KAAK,WAAW,eAAe,OAAO,CAAC,EAErD,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAY,CAAE,QAAS,KAAM,eAAgB,CAAC,CAA2C,EAE/F,KAAK,WAAW,MAAM,QAAU,CAC9B,EAAA,eAAe,MAAiB,CAC9B,IAAM,EAAU,EAAS,EAErB,OAAO,GAAY,YAAY,EAAA,UAAU,CAAO,CACtD,CAAC,CACH,CAAC,EAEG,EAAU,eAAe,OAAS,GACpC,KAAK,WAAW,eAAe,KAAK,GAAG,EAAU,cAAc,CAEnE,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"base-element.cjs","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport {\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n type RuntimeContext,\n runWithContext,\n} from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Registered via `onFormReset()` — persists across mount callbacks, unlike `mountCallbacks`. */\n formResetCallbacks: OnFormResetCallback[];\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n formResetCallbacks: [],\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\n/**\n * Phase transitions:\n *\n * ```\n * UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE\n * └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE\n * SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED\n * ```\n *\n * `generation` increments on every disconnect and is captured before an async\n * `setup()` is awaited; if it no longer matches when the promise settles, the\n * element was disconnected (and possibly reconnected) in the meantime and the\n * result is discarded (see `_isStale`).\n *\n * Why this lives on the class instead of a standalone pure reducer: every\n * transition here is triggered by running actual user code (`def.setup()`,\n * `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`\n * — there is no meaningful \"decide the next phase\" step that can be separated\n * from \"run the side-effecting thing that produces the phase change\" without\n * introducing a data-only effect-description layer that this package has no\n * other use for. That's why the methods below stay as direct, readable\n * procedural steps instead of a reducer + effect interpreter.\n */\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.formResetCallbacks = [];\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n /**\n * Native form-association lifecycle callback — the browser calls this on every\n * `formAssociated: true` element inside a `<form>` when that form is reset.\n * Runs every `onFormReset()` callback registered during `setup()`.\n */\n formResetCallback(): void {\n for (const callback of this._component.formResetCallbacks) {\n try {\n callback();\n } catch (error) {\n this._handleSetupError(error, 'form-reset');\n }\n }\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, formResetCallbacks: [], mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n\n return def.setup(setupProps as InferProps<PropInputDefs>);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n this._component.formResetCallbacks.push(...ctx.formResetCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n /**\n * True once the element has disconnected (and possibly reconnected) since\n * `capturedGeneration` was recorded — an in-flight async `setup()` result\n * arriving after that point is for an instance state that no longer exists.\n */\n private _isStale(capturedGeneration: number): boolean {\n return this._component.generation !== capturedGeneration || !this.isConnected;\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (this._isStale(capturedGeneration)) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = {\n element: this,\n formResetCallbacks: [] as typeof this._component.formResetCallbacks,\n mountCallbacks: [] as typeof this._component.mountCallbacks,\n };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n\n if (nestedCtx.formResetCallbacks.length > 0) {\n this._component.formResetCallbacks.push(...nestedCtx.formResetCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"0OA+BA,IAAM,OAA8C,CAClD,mBAAoB,CAAC,EACrB,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAA,eAAe,cACtB,OAAA,EAAA,EAAA,MAAA,CAAc,EACd,eAAgB,IAClB,GA2Ba,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,WAAa,EAAqB,CACzC,CAEA,mBAA0B,EACxB,EAAA,EAAA,QAAA,KAAc,CACR,KAAK,WAAW,QAAU,EAAA,eAAe,eAAe,KAAK,UAAU,EAE3E,KAAK,MAAM,CACb,CAAC,EACD,KAAK,cAAc,IAAI,YAAY,EAAA,iBAAiB,QAAS,CAAE,QAAS,GAAO,SAAU,EAAM,CAAC,CAAC,CACnG,CAEA,yBAAyB,EAAc,EAAyB,EAA+B,CAC7F,GAAI,IAAa,EAAU,OAE3B,IAAM,EAAW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AA,UAAU,CAAO,CACtD,CAAC,CACH,CAAC,EAEG,EAAU,eAAe,OAAS,GACpC,KAAK,WAAW,eAAe,KAAK,GAAG,EAAU,cAAc,EAG7D,EAAU,mBAAmB,OAAS,GACxC,KAAK,WAAW,mBAAmB,KAAK,GAAG,EAAU,kBAAkB,CAE3E,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
|
package/dist/base-element.d.ts
CHANGED
|
@@ -1,7 +1,30 @@
|
|
|
1
1
|
import type { ComponentDefinition } from './component-types';
|
|
2
2
|
import { type PropsDef } from './props';
|
|
3
|
+
/**
|
|
4
|
+
* Phase transitions:
|
|
5
|
+
*
|
|
6
|
+
* ```
|
|
7
|
+
* UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE
|
|
8
|
+
* └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE
|
|
9
|
+
* SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* `generation` increments on every disconnect and is captured before an async
|
|
13
|
+
* `setup()` is awaited; if it no longer matches when the promise settles, the
|
|
14
|
+
* element was disconnected (and possibly reconnected) in the meantime and the
|
|
15
|
+
* result is discarded (see `_isStale`).
|
|
16
|
+
*
|
|
17
|
+
* Why this lives on the class instead of a standalone pure reducer: every
|
|
18
|
+
* transition here is triggered by running actual user code (`def.setup()`,
|
|
19
|
+
* `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`
|
|
20
|
+
* — there is no meaningful "decide the next phase" step that can be separated
|
|
21
|
+
* from "run the side-effecting thing that produces the phase change" without
|
|
22
|
+
* introducing a data-only effect-description layer that this package has no
|
|
23
|
+
* other use for. That's why the methods below stay as direct, readable
|
|
24
|
+
* procedural steps instead of a reducer + effect interpreter.
|
|
25
|
+
*/
|
|
3
26
|
export declare class BaseElement extends HTMLElement {
|
|
4
|
-
static _definition: ComponentDefinition<any
|
|
27
|
+
static _definition: ComponentDefinition<any>;
|
|
5
28
|
static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;
|
|
6
29
|
static formAssociated: boolean;
|
|
7
30
|
static observedAttributes: string[];
|
|
@@ -10,8 +33,20 @@ export declare class BaseElement extends HTMLElement {
|
|
|
10
33
|
connectedCallback(): void;
|
|
11
34
|
attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
|
|
12
35
|
disconnectedCallback(): void;
|
|
36
|
+
/**
|
|
37
|
+
* Native form-association lifecycle callback — the browser calls this on every
|
|
38
|
+
* `formAssociated: true` element inside a `<form>` when that form is reset.
|
|
39
|
+
* Runs every `onFormReset()` callback registered during `setup()`.
|
|
40
|
+
*/
|
|
41
|
+
formResetCallback(): void;
|
|
13
42
|
private _handleSetupError;
|
|
14
43
|
private _runSetup;
|
|
44
|
+
/**
|
|
45
|
+
* True once the element has disconnected (and possibly reconnected) since
|
|
46
|
+
* `capturedGeneration` was recorded — an in-flight async `setup()` result
|
|
47
|
+
* arriving after that point is for an instance state that no longer exists.
|
|
48
|
+
*/
|
|
49
|
+
private _isStale;
|
|
15
50
|
private _runSetupAsync;
|
|
16
51
|
private _applyResult;
|
|
17
52
|
private _init;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-element.d.ts","sourceRoot":"","sources":["../src/base-element.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"base-element.d.ts","sourceRoot":"","sources":["../src/base-element.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAI7D,OAAO,EAAiE,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAC;AAoCvG;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,WAAY,SAAQ,WAAW;IAC1C,MAAM,CAAC,WAAW,EAAE,mBAAmB,CAAC,GAAG,CAAC,CAAC;IAC7C,MAAM,CAAC,mBAAmB,EAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,GAAG,SAAS,CAAC;IACvE,MAAM,CAAC,cAAc,UAAS;IAC9B,MAAM,CAAC,kBAAkB,EAAE,MAAM,EAAE,CAAM;IAEzC,OAAO,CAAC,UAAU,CAAiB;;IAcnC,iBAAiB,IAAI,IAAI;IASzB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI;IAkB9F,oBAAoB,IAAI,IAAI;IAa5B;;;;OAIG;IACH,iBAAiB,IAAI,IAAI;IAUzB,OAAO,CAAC,iBAAiB;IAoBzB,OAAO,CAAC,SAAS;IA0DjB;;;;OAIG;IACH,OAAO,CAAC,QAAQ;YAIF,cAAc;IAwC5B,OAAO,CAAC,YAAY;IAWpB,OAAO,CAAC,KAAK;IAQb,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,cAAc;IAQtB,OAAO,CAAC,uBAAuB;CA8ChC"}
|
package/dist/base-element.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{warn as e}from"./_dev.js";import{OreLifecycleError as t,reportRuntimeError as n}from"./errors.js";import"./types/bindings.js";import{onCleanup as r,runWithContext as i}from"./runtime.js";import{
|
|
1
|
+
import{warn as e}from"./_dev.js";import{OreLifecycleError as t,reportRuntimeError as n}from"./errors.js";import"./types/bindings.js";import{onCleanup as r,runWithContext as i}from"./runtime.js";import{createProps as a,getPropMeta as o}from"./props.js";import{ComponentPhase as s,LIFECYCLE_EVENTS as c}from"./types.js";import{loadStylesheet as l}from"./utils/css.js";import{scope as u,untrack as d}from"@vielzeug/ripple";var f=()=>({formResetCallbacks:[],generation:0,mountCallbacks:[],phase:s.UNINITIALIZED,scope:u(),templateResult:null}),p=class extends HTMLElement{static _definition;static _normalizedPropDefs;static formAssociated=!1;static observedAttributes=[];_component;constructor(){super();let e=this.constructor._definition;e?.shadow!==!1&&this.attachShadow({mode:`open`,...e?.shadow}),this._component=f()}connectedCallback(){d(()=>{this._component.phase===s.UNINITIALIZED&&this._runSetup(),this._init()}),this.dispatchEvent(new CustomEvent(c.CONNECT,{bubbles:!1,composed:!1}))}attributeChangedCallback(e,t,n){if(t===n)return;let r=o(this,e);if(!r)return;let i=r.parse(n);Object.is(d(()=>r.signal.value),i)||(r.signal.value=i)}disconnectedCallback(){this._component.generation++,this._component.phase=s.UNMOUNTED,this.dispatchEvent(new CustomEvent(c.DISCONNECT,{bubbles:!1,composed:!1})),this._component.scope.dispose(),this._component.formResetCallbacks=[],this._component.mountCallbacks=[],this._component.phase=s.UNINITIALIZED,this._component.scope=u(),this._component.templateResult=null}formResetCallback(){for(let e of this._component.formResetCallbacks)try{e()}catch(e){this._handleSetupError(e,`form-reset`)}}_handleSetupError(e,r=`setup`){let i=e instanceof Error?e:Error(String(e)),a=new t(`<${this.localName}> failed during ${this._component.phase} (${r})`,{cause:i,component:this.localName,phase:r}),o=this.constructor._definition;if(o?.onError)try{return o.onError(a,this)}catch{}n(a,this)}_runSetup(){this._component.phase=s.SETUP_RUNNING;let e=this.constructor._definition,t=this.constructor._normalizedPropDefs,n={element:this,formResetCallbacks:[],mountCallbacks:[]};try{let r;if(this._component.scope.run(()=>{r=i(n,()=>{let n=t?a(this,t):{};return e.setup(n)})}),this._component.mountCallbacks.push(...n.mountCallbacks),this._component.formResetCallbacks.push(...n.formResetCallbacks),r!=null&&typeof r.then==`function`){let t=this._component.mountCallbacks.splice(0);this._component.phase=s.LOADING,e.loading&&(this._component.templateResult=e.loading()),this._runSetupAsync(r,t,this._component.generation)}else this._component.templateResult=r??null,this._component.phase=s.SETUP_DONE}catch(e){let t=this._handleSetupError(e);if(t)this._component.templateResult=t,this._component.phase=s.SETUP_DONE;else throw this._component.phase=s.UNINITIALIZED,e}}_isStale(e){return this._component.generation!==e||!this.isConnected}async _runSetupAsync(t,n,r){try{let i=await t;if(this._isStale(r)){e(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);return}this._component.templateResult=i??null,this._component.phase=s.SETUP_DONE,this._component.mountCallbacks.push(...n),i&&this._applyResult(i),this._scheduleMountCallbacks()}catch(t){if(this._isStale(r)){e(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);return}let n=this._handleSetupError(t,`async-setup`);n?(this._component.templateResult=n,this._component.phase=s.SETUP_DONE,this._applyResult(n)):this._component.phase=s.UNINITIALIZED}}_applyResult(e){e&&((this.shadowRoot??this).replaceChildren(e.fragment),this._component.scope.run(()=>{e.apply(r)}))}_init(){this._applyStyles(),this._mountTemplate(),this._component.phase===s.SETUP_DONE&&this._scheduleMountCallbacks()}_applyStyles(){let e=this.constructor._definition;this.shadowRoot&&e?.styles?.length&&(this.shadowRoot.adoptedStyleSheets=e.styles.map(l))}_mountTemplate(){let e=this._component.templateResult;e&&this._applyResult(e)}_scheduleMountCallbacks(){if(this._component.mountCallbacks.length===0)return;let e=this._component.generation;queueMicrotask(()=>{if(this._isStale(e))return;let t=this._component.mountCallbacks.splice(0);for(let e of t)try{let t={element:this,formResetCallbacks:[],mountCallbacks:[]};this._component.scope.run(()=>{i(t,()=>{let t=e();typeof t==`function`&&r(t)})}),t.mountCallbacks.length>0&&this._component.mountCallbacks.push(...t.mountCallbacks),t.formResetCallbacks.length>0&&this._component.formResetCallbacks.push(...t.formResetCallbacks)}catch(e){this._handleSetupError(e,`mounted`)}this._component.mountCallbacks.length>0&&this._scheduleMountCallbacks()})}};export{p as BaseElement};
|
|
2
2
|
//# sourceMappingURL=base-element.js.map
|
package/dist/base-element.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-element.js","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { createContextBag } from './context-bag';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport { type OnMountedCallback, onCleanup, type RuntimeContext, runWithContext } from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any, any, any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n const contextBag = createContextBag(this);\n\n return def.setup(setupProps as InferProps<PropInputDefs>, contextBag);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n // Discard stale results: element disconnected+reconnected since this setup started.\n if (this._component.generation !== capturedGeneration || !this.isConnected) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._component.generation !== capturedGeneration || !this.isConnected) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (!this.isConnected || capturedGeneration !== this._component.generation) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = { element: this, mountCallbacks: [] as typeof this._component.mountCallbacks };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"wdAwBA,IAAM,OAA8C,CAClD,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAe,cACtB,MAAO,EAAO,EACd,eAAgB,IAClB,GAIa,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK,YAAmC,YAEjD,GAAK,SAAW,IAClB,KAAK,aAAa,CAAE,KAAM,OAAQ,GAAI,GAAK,MAA+C,CAAC,EAG7F,KAAK,W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AK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
|
|
1
|
+
{"version":3,"file":"base-element.js","names":[],"sources":["../src/base-element.ts"],"sourcesContent":["import { scope as _scope, type Scope, untrack } from '@vielzeug/ripple';\n\nimport type { ComponentDefinition } from './component-types';\n\nimport { warn } from './_dev';\nimport { type OreErrorPhase, OreLifecycleError, reportRuntimeError } from './errors';\nimport { createProps, getPropMeta, type InferProps, type PropInputDefs, type PropsDef } from './props';\nimport {\n type OnFormResetCallback,\n type OnMountedCallback,\n onCleanup,\n type RuntimeContext,\n runWithContext,\n} from './runtime';\nimport { ComponentPhase, LIFECYCLE_EVENTS } from './types';\nimport { type HTMLResult } from './types/bindings';\nimport { loadStylesheet } from './utils/css';\n\n// ─── Internal component state ─────────────────────────────────────────────────\n\ntype ComponentState = {\n /** Registered via `onFormReset()` — persists across mount callbacks, unlike `mountCallbacks`. */\n formResetCallbacks: OnFormResetCallback[];\n /** Incremented on every disconnect — guards both mount callbacks and async setup results. */\n generation: number;\n mountCallbacks: OnMountedCallback[];\n phase: ComponentPhase;\n scope: Scope;\n templateResult: HTMLResult | null;\n};\n\nconst createComponentState = (): ComponentState => ({\n formResetCallbacks: [],\n generation: 0,\n mountCallbacks: [],\n phase: ComponentPhase.UNINITIALIZED,\n scope: _scope(),\n templateResult: null,\n});\n\n// ─── BaseElement ──────────────────────────────────────────────────────────────\n\n/**\n * Phase transitions:\n *\n * ```\n * UNINITIALIZED ──_runSetup()──┬─(sync result)──► SETUP_DONE\n * └─(promise)──────► LOADING ──(resolves)──► SETUP_DONE\n * SETUP_DONE / LOADING ──disconnectedCallback()──► UNMOUNTED ──(reset)──► UNINITIALIZED\n * ```\n *\n * `generation` increments on every disconnect and is captured before an async\n * `setup()` is awaited; if it no longer matches when the promise settles, the\n * element was disconnected (and possibly reconnected) in the meantime and the\n * result is discarded (see `_isStale`).\n *\n * Why this lives on the class instead of a standalone pure reducer: every\n * transition here is triggered by running actual user code (`def.setup()`,\n * `onMounted` callbacks) inside a reactive `scope.run()` + `runWithContext()`\n * — there is no meaningful \"decide the next phase\" step that can be separated\n * from \"run the side-effecting thing that produces the phase change\" without\n * introducing a data-only effect-description layer that this package has no\n * other use for. That's why the methods below stay as direct, readable\n * procedural steps instead of a reducer + effect interpreter.\n */\nexport class BaseElement extends HTMLElement {\n static _definition: ComponentDefinition<any>;\n static _normalizedPropDefs: PropsDef<Record<never, never>> | undefined;\n static formAssociated = false;\n static observedAttributes: string[] = [];\n\n private _component: ComponentState;\n\n constructor() {\n super();\n\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.shadow !== false) {\n this.attachShadow({ mode: 'open', ...(def?.shadow as Partial<ShadowRootInit> | undefined) });\n }\n\n this._component = createComponentState();\n }\n\n connectedCallback(): void {\n untrack(() => {\n if (this._component.phase === ComponentPhase.UNINITIALIZED) this._runSetup();\n\n this._init();\n });\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.CONNECT, { bubbles: false, composed: false }));\n }\n\n attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {\n if (oldValue === newValue) return;\n\n const propMeta = getPropMeta(this, name);\n\n if (!propMeta) return;\n\n const parsed = propMeta.parse(newValue);\n\n if (\n !Object.is(\n untrack(() => propMeta.signal.value),\n parsed,\n )\n )\n propMeta.signal.value = parsed as never;\n }\n\n disconnectedCallback(): void {\n this._component.generation++;\n this._component.phase = ComponentPhase.UNMOUNTED;\n this.dispatchEvent(new CustomEvent(LIFECYCLE_EVENTS.DISCONNECT, { bubbles: false, composed: false }));\n this._component.scope.dispose();\n // Reset mutable fields for next connect, keeping the same object for stable references\n this._component.formResetCallbacks = [];\n this._component.mountCallbacks = [];\n this._component.phase = ComponentPhase.UNINITIALIZED;\n this._component.scope = _scope();\n this._component.templateResult = null;\n }\n\n /**\n * Native form-association lifecycle callback — the browser calls this on every\n * `formAssociated: true` element inside a `<form>` when that form is reset.\n * Runs every `onFormReset()` callback registered during `setup()`.\n */\n formResetCallback(): void {\n for (const callback of this._component.formResetCallbacks) {\n try {\n callback();\n } catch (error) {\n this._handleSetupError(error, 'form-reset');\n }\n }\n }\n\n private _handleSetupError(error: unknown, phase: OreErrorPhase = 'setup'): HTMLResult | void {\n const err = error instanceof Error ? error : new Error(String(error));\n const oreError = new OreLifecycleError(`<${this.localName}> failed during ${this._component.phase} (${phase})`, {\n cause: err,\n component: this.localName,\n phase,\n });\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (def?.onError) {\n try {\n return def.onError(oreError, this);\n } catch {\n /* fall through */\n }\n }\n\n reportRuntimeError(oreError, this);\n }\n\n private _runSetup(): void {\n this._component.phase = ComponentPhase.SETUP_RUNNING;\n\n const def = (this.constructor as typeof BaseElement)._definition;\n const normalizedPropDefs = (this.constructor as typeof BaseElement)._normalizedPropDefs;\n const ctx: RuntimeContext = { element: this, formResetCallbacks: [], mountCallbacks: [] };\n\n try {\n let setupResult: HTMLResult | null | Promise<HTMLResult | null> | undefined;\n\n this._component.scope.run(() => {\n setupResult = runWithContext(ctx, () => {\n const setupProps = normalizedPropDefs\n ? createProps(this, normalizedPropDefs)\n : ({} as InferProps<PropInputDefs>);\n\n return def.setup(setupProps as InferProps<PropInputDefs>);\n });\n });\n this._component.mountCallbacks.push(...ctx.mountCallbacks);\n this._component.formResetCallbacks.push(...ctx.formResetCallbacks);\n\n if (setupResult != null && typeof (setupResult as Promise<HTMLResult | null>).then === 'function') {\n // Async setup: show loading template immediately, swap when resolved.\n // Store captured mount callbacks; they will be scheduled after the real template mounts.\n const pendingCallbacks = this._component.mountCallbacks.splice(0);\n\n this._component.phase = ComponentPhase.LOADING;\n\n if (def.loading) {\n this._component.templateResult = def.loading();\n }\n\n // Capture the current generation so the async handler can detect staleness:\n // if the element disconnects+reconnects before the promise resolves, generation is\n // incremented and the old promise result must be discarded.\n void this._runSetupAsync(\n setupResult as Promise<HTMLResult | null>,\n pendingCallbacks,\n this._component.generation,\n );\n } else {\n this._component.templateResult = (setupResult as HTMLResult | null) ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n }\n } catch (error) {\n const recoveryTemplate = this._handleSetupError(error);\n\n if (recoveryTemplate) {\n this._component.templateResult = recoveryTemplate;\n this._component.phase = ComponentPhase.SETUP_DONE;\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n throw error;\n }\n }\n }\n\n /**\n * True once the element has disconnected (and possibly reconnected) since\n * `capturedGeneration` was recorded — an in-flight async `setup()` result\n * arriving after that point is for an instance state that no longer exists.\n */\n private _isStale(capturedGeneration: number): boolean {\n return this._component.generation !== capturedGeneration || !this.isConnected;\n }\n\n private async _runSetupAsync(\n promise: Promise<HTMLResult | null>,\n pendingCallbacks: OnMountedCallback[],\n capturedGeneration: number,\n ): Promise<void> {\n try {\n const result = await promise;\n\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup result discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n this._component.templateResult = result ?? null;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._component.mountCallbacks.push(...pendingCallbacks);\n\n if (result) this._applyResult(result);\n\n this._scheduleMountCallbacks();\n } catch (error) {\n if (this._isStale(capturedGeneration)) {\n warn(`<${this.localName}> async setup error discarded — element disconnected before setup resolved.`);\n\n return;\n }\n\n const recovery = this._handleSetupError(error, 'async-setup');\n\n if (recovery) {\n this._component.templateResult = recovery;\n this._component.phase = ComponentPhase.SETUP_DONE;\n this._applyResult(recovery);\n } else {\n this._component.phase = ComponentPhase.UNINITIALIZED;\n }\n }\n }\n\n private _applyResult(result: HTMLResult | null): void {\n if (!result) return;\n\n const host: Element | ShadowRoot = this.shadowRoot ?? this;\n\n host.replaceChildren(result.fragment);\n this._component.scope.run(() => {\n result.apply(onCleanup);\n });\n }\n\n private _init(): void {\n this._applyStyles();\n this._mountTemplate();\n\n // Only schedule mount callbacks once setup is fully complete (not in LOADING state)\n if (this._component.phase === ComponentPhase.SETUP_DONE) this._scheduleMountCallbacks();\n }\n\n private _applyStyles(): void {\n const def = (this.constructor as typeof BaseElement)._definition;\n\n if (this.shadowRoot && def?.styles?.length) {\n this.shadowRoot.adoptedStyleSheets = def.styles.map(loadStylesheet);\n }\n }\n\n private _mountTemplate(): void {\n const result = this._component.templateResult;\n\n if (!result) return;\n\n this._applyResult(result);\n }\n\n private _scheduleMountCallbacks(): void {\n if (this._component.mountCallbacks.length === 0) return;\n\n const capturedGeneration = this._component.generation;\n\n queueMicrotask(() => {\n if (this._isStale(capturedGeneration)) return;\n\n // Snapshot callbacks so in-loop registrations don't extend this iteration.\n const batch = this._component.mountCallbacks.splice(0);\n\n for (const callback of batch) {\n try {\n const nestedCtx = {\n element: this,\n formResetCallbacks: [] as typeof this._component.formResetCallbacks,\n mountCallbacks: [] as typeof this._component.mountCallbacks,\n };\n\n this._component.scope.run(() => {\n runWithContext(nestedCtx, () => {\n const cleanup = callback();\n\n if (typeof cleanup === 'function') onCleanup(cleanup);\n });\n });\n\n if (nestedCtx.mountCallbacks.length > 0) {\n this._component.mountCallbacks.push(...nestedCtx.mountCallbacks);\n }\n\n if (nestedCtx.formResetCallbacks.length > 0) {\n this._component.formResetCallbacks.push(...nestedCtx.formResetCallbacks);\n }\n } catch (error) {\n this._handleSetupError(error, 'mounted');\n }\n }\n\n // If nested onMounted calls registered new callbacks, schedule them with\n // a fresh token check in the next microtask.\n if (this._component.mountCallbacks.length > 0) {\n this._scheduleMountCallbacks();\n }\n });\n }\n}\n"],"mappings":"oaA+BA,IAAM,OAA8C,CAClD,mBAAoB,CAAC,EACrB,WAAY,EACZ,eAAgB,CAAC,EACjB,MAAO,EAAe,cACtB,MAAO,EAAO,EACd,eAAgB,IAClB,GA2Ba,EAAb,cAAiC,WAAY,CAC3C,OAAO,YACP,OAAO,oBACP,OAAO,eAAiB,GACxB,OAAO,mBAA+B,CAAC,EAEvC,WAEA,aAAc,CACZ,MAAM,EAEN,IAAM,EAAO,KAAK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AAO,CAAC,EAErD,IAAK,IAAM,KAAY,EACrB,GAAI,CACF,IAAM,EAAY,CAChB,QAAS,KACT,mBAAoB,CAAC,EACrB,eAAgB,CAAC,CACnB,EAEA,KAAK,WAAW,MAAM,QAAU,CAC9B,EAAe,MAAiB,CAC9B,IAAM,EAAU,EAAS,EAErB,OAAO,GAAY,YAAY,EAAU,CAAO,CACtD,CAAC,CACH,CAAC,EAEG,EAAU,eAAe,OAAS,GACpC,KAAK,WAAW,eAAe,KAAK,GAAG,EAAU,cAAc,EAG7D,EAAU,mBAAmB,OAAS,GACxC,KAAK,WAAW,mBAAmB,KAAK,GAAG,EAAU,kBAAkB,CAE3E,OAAS,EAAO,CACd,KAAK,kBAAkB,EAAO,SAAS,CACzC,CAKE,KAAK,WAAW,eAAe,OAAS,GAC1C,KAAK,wBAAwB,CAEjC,CAAC,CACH,CACF"}
|
|
@@ -1,86 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Public component definition types for ore web components.
|
|
3
3
|
* These are the types consumers interact with when calling define().
|
|
4
|
+
*
|
|
5
|
+
* `setup()` takes only `props` — everything else (lifecycle hooks, bindings,
|
|
6
|
+
* context, slots, emit) is a free function imported from `@vielzeug/ore`
|
|
7
|
+
* (see `runtime.ts`, `host-bind.ts`, `aria.ts`, `context.ts`, `slots.ts`,
|
|
8
|
+
* `utils/emit.ts`) and resolved through the implicit "current component"
|
|
9
|
+
* context rather than threaded through a second `setup()` parameter. This
|
|
10
|
+
* keeps `setup()` a plain function you can call composables from. Note:
|
|
11
|
+
* ore's `watchEffect()` is intentionally not named `watch` — `@vielzeug/ripple`
|
|
12
|
+
* already exports a `watch(source, callback)` with different semantics
|
|
13
|
+
* (explicit source + old/new value pair), so reusing the name here would
|
|
14
|
+
* silently shadow it whenever both are imported in the same file.
|
|
4
15
|
*/
|
|
5
|
-
import type { CleanupFn, EffectCallback, Readable } from '@vielzeug/ripple';
|
|
6
|
-
import type { AriaConfig } from './aria';
|
|
7
|
-
import type { InjectionKey } from './context';
|
|
8
16
|
import type { OreLifecycleError } from './errors';
|
|
9
|
-
import type { BindOptions, HostBindConfig } from './host-bind';
|
|
10
17
|
import type { InferProps, PropsDef } from './props';
|
|
11
|
-
import type { OnMountedCallback } from './runtime';
|
|
12
|
-
import type { ComponentSlots } from './slots';
|
|
13
18
|
import type { HTMLResult } from './types/bindings';
|
|
14
19
|
import type { CSSResult } from './utils/css';
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* The context bag passed as the second argument to `setup()`.
|
|
18
|
-
* Contains everything you need to build a component — bindings, lifecycle hooks,
|
|
19
|
-
* context injection, and slot signals — all in one place.
|
|
20
|
-
*/
|
|
21
|
-
export type SetupContextBag<Emits extends Record<string, unknown> = Record<string, never>, SlotNames extends string = string> = {
|
|
22
|
-
/**
|
|
23
|
-
* Reactively sync ARIA attributes on any element, auto-cleanup on component disconnect.
|
|
24
|
-
* Returns a cleanup function that removes all reactive ARIA bindings.
|
|
25
|
-
*/
|
|
26
|
-
aria: (target: Element, config: AriaConfig) => () => void;
|
|
27
|
-
/**
|
|
28
|
-
* Apply reactive or static bindings to an element's attributes, classes, styles, and events.
|
|
29
|
-
* Defaults to the host element. Pass `options.target` to bind to any other element
|
|
30
|
-
* (e.g. a slotted trigger, an internally-referenced child).
|
|
31
|
-
*/
|
|
32
|
-
bind: (config: HostBindConfig, options?: BindOptions) => () => void;
|
|
33
|
-
/** The component's host element. */
|
|
34
|
-
el: HTMLElement;
|
|
35
|
-
/** Dispatch a typed custom event from the host element. */
|
|
36
|
-
emit: EmitFn<Emits>;
|
|
37
|
-
/**
|
|
38
|
-
* Resolve an injected context value from a providing ancestor.
|
|
39
|
-
* Walks the DOM tree (including shadow boundaries) to find the nearest
|
|
40
|
-
* element that called `ctx.provide()` with the given key.
|
|
41
|
-
*/
|
|
42
|
-
inject: {
|
|
43
|
-
<T>(key: InjectionKey<T>): T | undefined;
|
|
44
|
-
<T>(key: InjectionKey<T>, fallback: T): T;
|
|
45
|
-
};
|
|
46
|
-
/**
|
|
47
|
-
* Register a cleanup function to run on component disconnect.
|
|
48
|
-
* All registered functions run when the element leaves the DOM.
|
|
49
|
-
*/
|
|
50
|
-
onCleanup: (fn: CleanupFn) => void;
|
|
51
|
-
/**
|
|
52
|
-
* Watch a ref signal and run a callback when it resolves to a non-null element.
|
|
53
|
-
* The callback's return value is used as a cleanup function.
|
|
54
|
-
*/
|
|
55
|
-
onElement: <T extends HTMLElement>(ref: Readable<T | null>, callback: (el: T) => CleanupFn | undefined | void) => () => void;
|
|
56
|
-
/**
|
|
57
|
-
* Attach a scoped event listener that is automatically removed on component disconnect.
|
|
58
|
-
* Silently no-ops when `target` is `null` or `undefined`.
|
|
59
|
-
*/
|
|
60
|
-
onEvent: {
|
|
61
|
-
<K extends keyof HTMLElementEventMap>(target: EventTarget | null | undefined, event: K, listener: (e: HTMLElementEventMap[K]) => void, options?: AddEventListenerOptions): void;
|
|
62
|
-
(target: EventTarget | null | undefined, event: string, listener: EventListener, options?: AddEventListenerOptions): void;
|
|
63
|
-
};
|
|
64
|
-
/**
|
|
65
|
-
* Register work to run after the component template mounts to the DOM.
|
|
66
|
-
* Multiple callbacks run in registration order.
|
|
67
|
-
*/
|
|
68
|
-
onMounted: (fn: OnMountedCallback) => void;
|
|
69
|
-
/**
|
|
70
|
-
* Register a context value on the host element, making it available to
|
|
71
|
-
* descendant components via `ctx.inject(key)`.
|
|
72
|
-
*/
|
|
73
|
-
provide: <T>(key: InjectionKey<T>, value: T) => void;
|
|
74
|
-
/** Reactive slot presence / element signals. */
|
|
75
|
-
slots: ComponentSlots<SlotNames>;
|
|
76
|
-
/**
|
|
77
|
-
* Create a reactive effect scoped to the component lifecycle.
|
|
78
|
-
* Automatically cleaned up on component disconnect.
|
|
79
|
-
* Returns a stop function that disposes the effect immediately.
|
|
80
|
-
*/
|
|
81
|
-
watch: (fn: EffectCallback) => () => void;
|
|
82
|
-
};
|
|
83
|
-
export type ComponentDefinition<Props extends Record<string, unknown> = Record<never, never>, Emits extends Record<string, unknown> = Record<string, never>, SlotNames extends string = string> = {
|
|
20
|
+
export type ComponentDefinition<Props extends Record<string, unknown> = Record<never, never>> = {
|
|
84
21
|
formAssociated?: boolean;
|
|
85
22
|
/**
|
|
86
23
|
* Rendered while async `setup()` is still pending.
|
|
@@ -93,7 +30,7 @@ export type ComponentDefinition<Props extends Record<string, unknown> = Record<n
|
|
|
93
30
|
*/
|
|
94
31
|
onError?: (error: OreLifecycleError, element: HTMLElement) => HTMLResult | void;
|
|
95
32
|
props?: PropsDef<Props>;
|
|
96
|
-
setup: (props: InferProps<PropsDef<Props
|
|
33
|
+
setup: (props: InferProps<PropsDef<Props>>) => HTMLResult | null | Promise<HTMLResult | null>;
|
|
97
34
|
/**
|
|
98
35
|
* Shadow DOM configuration. `mode` defaults to `'open'`.
|
|
99
36
|
* Set to `false` to opt out of shadow DOM entirely (light DOM rendering).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-types.d.ts","sourceRoot":"","sources":["../src/component-types.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"component-types.d.ts","sourceRoot":"","sources":["../src/component-types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,mBAAmB,CAAC,KAAK,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI;IAC9F,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,UAAU,CAAC;IAC3B;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,WAAW,KAAK,UAAU,GAAG,IAAI,CAAC;IAChF,KAAK,CAAC,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC;IACxB,KAAK,EAAE,CAAC,KAAK,EAAE,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,KAAK,UAAU,GAAG,IAAI,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IAC9F;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,KAAK,CAAC;IACzC,MAAM,CAAC,EAAE,CAAC,MAAM,GAAG,aAAa,GAAG,SAAS,CAAC,EAAE,CAAC;CACjD,CAAC"}
|
package/dist/context.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./
|
|
1
|
+
const e=require("./_dev.cjs"),t=require("./errors.cjs"),n=require("./runtime.cjs");var r=new WeakMap,i=e=>{let t=[],n=e;for(;n;){n instanceof HTMLElement&&t.push(n);let e=n.getRootNode();n=n.parentElement??(e instanceof ShadowRoot?e.host:null)}return t},a=(t,n,i)=>{let a=r.get(t)??new Map;a.has(n)&&e.warn(`provide(): key already provided on <${t.localName}> — overwriting. Provide a Readable to update it instead.`),a.set(n,i),r.set(t,a)},o=(e,t)=>a(n.getHost(),e,t),s=Symbol(`inject.not_found`),c=new WeakMap,l=(e,t)=>{let n=i(e);for(let e of n){let n=r.get(e);if(n?.has(t))return n.get(t)}return s};function u(e,...t){let r=n.requireSetupContext(`inject`),i=c.get(r);i||(i=new Map,c.set(r,i));let a=e;if(i.has(a)){let e=i.get(a);return e===s?t.length>0?t[0]:void 0:e}let o=l(r.element,e);return i.set(a,o),o===s?t.length>0?t[0]:void 0:o}var d=e=>{let r=u(e,s);if(r!==s)return r;let i=n.getHost();throw new t.OreApiError(t.ORE_ERRORS.injectStrictFailed(String(e),i.localName))};function f(e){return Symbol(e)}exports.createContext=f,exports.inject=u,exports.injectStrict=d,exports.provide=o;
|
|
2
2
|
//# sourceMappingURL=context.cjs.map
|