@yaks/preact 0.0.0-stage → 0.2.36

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Jeff Peterson
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
1
+ # @yaks/preact
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Renders graph records as Preact components using the view registry from
4
+ `@yaks/render`. A bundle is one entity's components as a JSON object, including
5
+ its `entity.eid`. A registry associates view names and matching predicates with
6
+ rendering functions. This package stores no entities and persists no edits.
7
+
8
+ Bind a synchronous function that reads bundles, and optionally a subscription,
9
+ into an `Entity` component, then mount it with Preact. This fragment assumes a
10
+ registry from `@yaks/render`, a loaded vocabulary, a bundle map and an
11
+ application subscription function `watch`:
12
+
13
+ ```ts ignore
14
+ import { entity } from '@yaks/preact'
15
+ import { h, render } from 'preact'
16
+
17
+ let Entity = entity({
18
+ registry,
19
+ vocab,
20
+ store: (eid) => bundles.get(eid),
21
+ subscribe: (eid, notify) => watch(eid, notify), // returns an unsubscribe
22
+ })
23
+ render(h(Entity, { eid: 'a', view: 'Tile' }), document.body)
24
+ ```
25
+
26
+ The JSX equivalent is `<Entity eid='a' view='Tile'/>`. Extra props flow to the
27
+ renderer context, including `comp` and `prop` for property views. The component
28
+ re-reads its store on notifications, handles absent bundles, and releases its
29
+ listener when the eid changes or it unmounts. It also reads after subscribing,
30
+ so a change between the first render and subscription is observed. Without a
31
+ subscription, parent renders still re-read the store. Create the bound `Entity`
32
+ once, outside a component's render.
33
+
34
+ `render(registry, bundle, view, vocab, ctx?)` directly builds a Preact node for
35
+ callers that already own the subscription. A missing bundle at `Entity`, or an
36
+ unmatched view, renders nothing. Portable renderers remain pure; native
37
+ components own hooks and state.
38
+
39
+ This package supplies `ctx.render(view, overrides?)` for composing another view
40
+ of the same bundle through the same registry. Overrides merge with the current
41
+ context; props belonging to a native component are preserved. A portable
42
+ `onChange` prop can carry an `Action` object; this package calls its
43
+ `run(bundle, input)` with a checkbox's checked state, or another control's
44
+ value, and passes the resulting patch to `ctx.onPatch(patch, bundle)`. The
45
+ application owns applying that patch. A rejected edit sets and reports the
46
+ control's validity message and calls `ctx.onError(error, bundle)` when supplied;
47
+ a successful edit clears the message. The exported `Events` type describes these
48
+ callbacks. Ordinary event functions pass through unchanged.
49
+
50
+ A native registration uses `{view, match, Render}` and can be typed as
51
+ `ComponentRenderer`. This package builds `h(Render, {e: bundle, ...ctx})`, so
52
+ Preact owns its hooks and its component identity. `Entity` supports native and
53
+ portable registrations in the same registry. A component change resets its state
54
+ and runs its cleanup through ordinary reconciliation.
55
+
56
+ For an application whose entities differ from `Bundle`, register
57
+ `ComponentRenderer<MyEntity>` and call
58
+ `render(registry, bundle, view, vocab, ctx, {e: entity, ...ctx})`. Selection
59
+ reads the bundle; the mounted component receives the original typed entity. A
60
+ native `Render` is never called as an ordinary function.
61
+
62
+ A bound `Entity` given `registry` as a function reads the registry at each
63
+ render, so a replaced registry draws on the next render without binding a new
64
+ `Entity`.
65
+
66
+ ## Drawing a page from a views module
67
+
68
+ A **views module** is a page script that exports `views`, a `@yaks/render`
69
+ registry, the way a package's `/views` facet does. `@yaks/preact/host` exports
70
+ `host`, which imports a views module, binds its registry into an `Entity` and
71
+ draws the page into a root element. The page keeps its client and its page
72
+ graph; the host reads them through the `vocab`, `store` and `subscribe` that
73
+ `entity` takes, and never creates or closes them. This fragment needs a browser
74
+ page, so it is not run here:
75
+
76
+ ```ts ignore
77
+ import { h } from 'preact'
78
+ import { host } from '@yaks/preact/host'
79
+
80
+ let page = await host({
81
+ root: document.querySelector('main')!,
82
+ views: new URL('./views.ts', import.meta.url),
83
+ client: front,
84
+ draw: (Entity) => h(Entity, { eid: 'page', view: 'Page' }),
85
+ })
86
+ ```
87
+
88
+ `draw` returns what the root holds, so the page can wrap the `Entity` in its own
89
+ providers, such as `@yaks/ux`'s `Ux`. `page.registry()` is the registry drawn
90
+ now, and `page.close()` stops following writes and empties the root. A `load`
91
+ option replaces `import()`, for a test that supplies modules itself. A page can
92
+ also supply `vocab`, `store` and `subscribe` separately, with `extend` to adopt
93
+ a larger vocabulary.
94
+
95
+ ### A preview that takes a write in place
96
+
97
+ On a yaks.app draft preview link, each write to the app's draft reaches the page
98
+ as a cancelable `yak-draft` event on `window`, whose `detail.files` names each
99
+ file written, its sha, its address and the page entries its imports reach. When
100
+ a write reaches only the views module, the host cancels the event, so the page
101
+ does not reload, and then:
102
+
103
+ 1. imports the new module from the views module's address with
104
+ `?yak-draft=<sha>` added, so the browser imports it again;
105
+ 2. replaces the registry and draws again into the same root, through the same
106
+ Preact tree; the client, its socket and the page graph are never closed;
107
+ 3. puts back the window's scroll, each scrolled element's scroll, and the
108
+ focused element and its caret, wherever the draw replaced those elements.
109
+
110
+ A portable renderer's output is patched in place, so its elements, focus and
111
+ scroll stay as they are. A native renderer whose `Render` is a new function
112
+ remounts its subtree: Preact runs the old component's cleanup and mounts the new
113
+ one. State kept in the page graph survives the remount; state kept in hooks does
114
+ not. A component that skips its render (`memo`) draws the new renderers the next
115
+ time it renders.
116
+
117
+ A `vocab.json` write fetches the page vocabulary from `api/vocab.json` (override
118
+ with `vocabulary`, relative to the page's base URI). The client adopts it only
119
+ when every existing component keeps its declaration and only new components are
120
+ added. The graph, socket, watches and stored drafts stay open; new renderers
121
+ read the larger vocabulary. A changed or removed declaration reloads instead. A
122
+ write containing both vocabulary and views adopts the vocabulary first. The
123
+ `fetch` option supplies the vocabulary fetch in an in-process check.
124
+
125
+ When the new module throws on import, exports no registry, or throws during its
126
+ first draw, the host keeps the old registry, draws it again and calls the
127
+ event's `reload()`, the reload the page would have had, keeping its scroll and
128
+ typed fields. When writes land faster than their modules import, only the newest
129
+ is drawn. `taken(detail, views)` is the test the host applies: the sha to
130
+ import, or null.
131
+
132
+ A write that names any other file reaches the page's own handling: a stylesheet
133
+ the page links is swapped, and anything else reloads the page. That includes a
134
+ file the views module imports, `vocab.json`, and `index.html`. A change of page
135
+ vocabulary reloads too, since a running page graph keeps the vocabulary it was
136
+ created with.
137
+
138
+ The views module meets the page's own Preact and toolkit instances only when it
139
+ is compiled as its own page entry: load it from the page with
140
+ `<script type="module" src="views.ts"></script>` beside the main script, and do
141
+ not import it from the main script. yaks.app compiles each module script a page
142
+ loads as an entry that imports Preact, Signals and the `@yaks/` packages from
143
+ shared modules, and the new module imports the same shared modules. An app file
144
+ that both the main script and the views module import is bundled into each, so
145
+ keep state in the page graph, not in module variables. Outside a preview link no
146
+ `yak-draft` event arrives, and the host only draws.
147
+
148
+ ## Example
149
+
150
+ From this directory, run `deno task example`, then open the loopback address it
151
+ prints. The example page demonstrates one portable renderer, a function store,
152
+ and a button that updates it through the subscription interface.
153
+
154
+ The example serves TypeScript as individual JavaScript modules using the same
155
+ Sucrase stripping as the application, with an import map pointing at Preact's
156
+ ESM on esm.sh. No bundler or `node_modules` is needed. It runs from this
157
+ repository; it is excluded from publication.
158
+
159
+ ## Compatibility
160
+
161
+ Deno and Node for module loading and rendering with an injected DOM; browsers
162
+ for mounting. Imports `preact` and `preact/hooks`, using the repository's Preact
163
+ 10 version. Both names must resolve to the same Preact instance. A browser can
164
+ map them to esm.sh as the example does. The package itself has no Deno globals
165
+ and never installs a global document.
166
+
167
+ ## Verification
168
+
169
+ `deno task test packages/preact` mounts through Preact using a temporary
170
+ LinkeDOM document, and checks the node example. The host's tests draw a page
171
+ over a `@yaks/client` page graph and dispatch `yak-draft` events on that
172
+ document's window.
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Draw a view into a tree with Preact: the verb a host that paints a tree of
3
+ * its own (@yaks/tui's terminal, @yaks/native's iOS views, a test's
4
+ * document) takes from the renderer, beside @yaks/react's.
5
+ *
6
+ * @module
7
+ */ import { type ComponentChildren, options } from "preact";
8
+ /** Supply the paint scheduler while a host or test owns the document. */ export declare let frames: (schedule: NonNullable<typeof options.requestAnimationFrame>) => () => void;
9
+ /** Run effects on a microtask while a host paints the tree. */ export declare let paintFrames: () => () => void;
10
+ /** Draw `node` into `into`, an element of a tree its host paints itself (an
11
+ * @yaks/dom tree, a test's document), and answer what takes it down. Such a
12
+ * host paints no browser frames, so effects run once the commit's microtasks
13
+ * are done, as a browser's next frame would run them, instead of Preact's
14
+ * fallback a few dozen milliseconds later. */ export declare let draw: (node: ComponentChildren, into: Element) => () => void;
15
+ //# sourceMappingURL=draw.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"draw.d.ts","sources":["../draw.ts"],"names":[],"mappings":"AAAA;;;;;;CAMC,GAED,SAAS,KAAK,iBAAiB,EAAE,OAAO,iBAAoC;AAK5E,uEAAuE,GACvE,OAAO,YAAI,SACT,UAAU,mBAAmB,QAAQ,iCAC9B,IAAI,CAMZ;AAED,6DAA6D,GAC7D,OAAO,YAAI,yBAAwB,IAAI,CAOtC;AAED;;;;4CAI4C,GAC5C,OAAO,YAAI,OAAQ,MAAM,mBAAmB,MAAM,kBAAgB,IAAI,CAerE"}
@@ -0,0 +1,9 @@
1
+ /** Draw a page from a Preact views module and follow its draft. @module */ import { type ComponentChild, type FunctionComponent } from "preact";
2
+ import { type Host as PageHost, type Page as PageOf, type Views as ViewsOf } from "@yaks/render/host";
3
+ import { type EntityProps, type HostRegistry } from "./mod.js";
4
+ export { addressed, type Draft, taken } from "@yaks/render/host";
5
+ export type Views = ViewsOf<HostRegistry>;
6
+ export type Host = PageHost<HostRegistry>;
7
+ export type Page = PageOf<HostRegistry, (Entity: FunctionComponent<EntityProps>) => ComponentChild>;
8
+ /** Bind the views module to the page's store and redraw when it changes. */ export declare let host: (page: Page) => Promise<Host>;
9
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sources":["../host.ts"],"names":[],"mappings":"AAAA,yEAAyE,GACzE,SAAS,KAAK,cAAc,EAAE,KAAK,iBAAiB,iBAAuC;AAC3F,SACE,KAAK,QAAQ,QAAQ,EAErB,KAAK,QAAQ,MAAM,EACnB,KAAK,SAAS,OAAO,iCACc;AACrC,SAEE,KAAK,WAAW,EAChB,KAAK,YAAY,mBAGF;AAEjB,SAAS,SAAS,EAAE,KAAK,KAAK,EAAE,KAAK,iCAAsC;AAC3E,YAAY,QAAQ,QAAQ;AAC5B,YAAY,OAAO,SAAS;AAC5B,YAAY,OAAO,OACjB,eACC,QAAQ,kBAAkB,iBAAiB;AAG9C,0EAA0E,GAC1E,OAAO,YAAI,OAAQ,MAAM,SAAO,QAAQ,MAgBpC"}
package/_dist/mod.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @yaks/preact is the Preact rendering backend for portable renderers. `render`
3
+ * passes Preact's hyperscript to the selected renderer; `entity` binds a
4
+ * registry, a vocabulary and a store into an <Entity eid view/> component. The store remains
5
+ * a function, with an optional per-entity subscription supplied beside it.
6
+ * Missing bundles or unmatched views render nothing. Subscriptions belong to
7
+ * the mounted component and are released when its eid changes or it unmounts.
8
+ *
9
+ * ```ts
10
+ * import { assertEquals } from '@std/assert'
11
+ * import { define } from '@yaks/render'
12
+ * import { loadVocab } from '@yaks/vocab'
13
+ * import { render } from '@yaks/preact'
14
+ *
15
+ * let registry = define([{
16
+ * view: 'Tile', match: true,
17
+ * render: (b, h) => h('p', null, b.entity.eid),
18
+ * }])
19
+ * let node = render(registry, {entity: {eid: 'a'}}, 'Tile', loadVocab([]))!
20
+ * assertEquals(node.type, 'p')
21
+ * assertEquals(node.props.children, ['a'])
22
+ * ```
23
+ *
24
+ * @module
25
+ */ import { type Context as Provided, type FunctionComponent, type VNode } from "preact";
26
+ import { type Bundle, type Context, type Registration, type Renderer, type Selection } from "@yaks/render";
27
+ import { type EntityProps, type Events, type Store, type Subscribe } from "@yaks/render/component";
28
+ export type { EntityProps, Events, Store, Subscribe } from "@yaks/render/component";
29
+ import type { Vocab } from "@yaks/vocab";
30
+ /** A native component; the host mounts it so Preact owns its hooks and identity. */ export type ComponentRenderer<E = Bundle> = Registration & {
31
+ Render: FunctionComponent<Context & Events & {
32
+ e: E;
33
+ }>;
34
+ };
35
+ /** Portable trees and native components share the same selection machinery. */ export type HostRegistry<E = Bundle> = Selection<Renderer | ComponentRenderer<E>>;
36
+ type Node<E = Bundle> = VNode<Record<string, unknown>> | VNode<Context & {
37
+ e: E;
38
+ }>;
39
+ /** The values bound once when an application creates its Entity component. */ export type Options = {
40
+ registry: HostRegistry;
41
+ vocab: Vocab;
42
+ store: Store;
43
+ subscribe?: Subscribe;
44
+ };
45
+ /**
46
+ * Resolve a view and build a Preact node. Native components are passed to h,
47
+ * never invoked directly. Native props default to {e: bundle, ...ctx}; callers
48
+ * with another entity shape supply their typed props as the sixth argument.
49
+ */ export declare function render(registry: Selection<Renderer>, bundle: Bundle, view: string | undefined, vocab: Vocab, ctx?: Context & Events): VNode<Record<string, unknown>> | null;
50
+ export declare function render(registry: HostRegistry, bundle: Bundle, view: string | undefined, vocab: Vocab, ctx?: Context & Events): Node | null;
51
+ export declare function render<E>(registry: HostRegistry<E>, bundle: Bundle, view: string | undefined, vocab: Vocab, ctx: Context & Events, props: Context & {
52
+ e: E;
53
+ }): Node<E> | null;
54
+ /** The vocabulary the host has most recently merged into its page graph. */ export declare let Vocabulary: Provided<Vocab | undefined>;
55
+ /**
56
+ * A registry provided above an Entity replaces the one it was bound with, and
57
+ * a new value draws every Entity below it again even when its props are the
58
+ * same, which a top-level `render` with the same props does not promise:
59
+ * `@preact/signals` skips a component holding hook state whose props are
60
+ * unchanged. The page host swaps a written views module in through it
61
+ * (./host.ts).
62
+ */ export declare let Registry: Provided<HostRegistry | undefined>;
63
+ /**
64
+ * Bind the application once: `let Entity = entity({registry, vocab, store,
65
+ * subscribe})`, then mount `<Entity eid='a' view='Tile'/>` through Preact.
66
+ * A notification re-reads the store even if it mutated a bundle in place.
67
+ */ export declare let entity: ({}: Options) => FunctionComponent<EntityProps>;
68
+ //# sourceMappingURL=mod.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.d.ts","sources":["../mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,SAEE,KAAK,WAAW,QAAQ,EAExB,KAAK,iBAAiB,EAEtB,KAAK,KAAK,iBACe;AAE3B,SACE,KAAK,MAAM,EACX,KAAK,OAAO,EAEZ,KAAK,YAAY,EAEjB,KAAK,QAAQ,EAGb,KAAK,SAAS,4BACgB;AAChC,SAEE,KAAK,WAAW,EAChB,KAAK,MAAM,EACX,KAAK,KAAK,EACV,KAAK,SAAS,sCAC0B;AAC1C,cACE,WAAW,EACX,MAAM,EACN,KAAK,EACL,SAAS,sCAC+B;AAC1C,cAAc,KAAK,2BAAgC;AAEnD,kFAAkF,GAClF,YAAY,kBAAkB,IAAI,UAAU;EAC1C,QAAQ,kBAAkB,UAAU;IAAW,GAAG;;;AAGpD,6EAA6E,GAC7E,YAAY,aAAa,IAAI,UAAU,UACrC,WAAW,kBAAkB;KAE1B,KAAK,IAAI,UACV,MAAM,OAAO,MAAM,EAAE,OAAO,KAC5B,MAAM;EAAY,GAAG;;AAEzB,4EAA4E,GAC5E,YAAY;EACV,UAAU;EACV,OAAO;EACP,OAAO;EACP,YAAY;;AAgBd;;;;CAIC,GACD,OAAO,iBAAS,OACd,UAAU,UAAU,SAAS,EAC7B,QAAQ,MAAM,EACd,MAAM,MAAM,GAAG,SAAS,EACxB,OAAO,KAAK,EACZ,MAAM,UAAU,MAAM,GACrB,MAAM,OAAO,MAAM,EAAE,OAAO,KAAK,IAAI;AACxC,OAAO,iBAAS,OACd,UAAU,YAAY,EACtB,QAAQ,MAAM,EACd,MAAM,MAAM,GAAG,SAAS,EACxB,OAAO,KAAK,EACZ,MAAM,UAAU,MAAM,GACrB,OAAO,IAAI;AACd,OAAO,iBAAS,OAAO,GACrB,UAAU,aAAa,EAAE,EACzB,QAAQ,MAAM,EACd,MAAM,MAAM,GAAG,SAAS,EACxB,OAAO,KAAK,EACZ,KAAK,UAAU,MAAM,EACrB,OAAO;EAAY,GAAG;CAAG,GACxB,KAAK,KAAK,IAAI;AA2CjB,0EAA0E,GAC1E,OAAO,YAAI,YAAY,SAAS,QAAQ,SAAS,EAErC;AAEZ;;;;;;;CAOC,GACD,OAAO,YAAI,UAAU,SAAS,eAAe,SAAS,EAE1C;AAEZ;;;;CAIC,GACD,OAAO,YAAI,SACT,IAAuC,OAAO,KAC7C,kBAAkB,aAuBpB"}
@@ -0,0 +1,4 @@
1
+ /** Package aliases for a view selected to run on Preact. */ export declare let aliases: Record<string, string>;
2
+ /** The renderer modules an app can import from its host. */ export declare let modules: Record<string, object>;
3
+ /** Draw a component loaded from a Preact app into a host's tree. */ export declare let paint: <Props extends object>(view: unknown, props: Props, into: Element) => () => void;
4
+ //# sourceMappingURL=renderer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer.d.ts","sources":["../renderer.ts"],"names":[],"mappings":"AAUA,0DAA0D,GAC1D,OAAO,YAAI,SAAS,OAAO,MAAM,EAAE,MAAM,EAAiC;AAE1E,0DAA0D,GAC1D,OAAO,YAAI,SAAS,OAAO,MAAM,EAAE,MAAM,EAQxC;AAED,kEAAkE,GAClE,OAAO,YAAI,QAAS,cAAc,MAAM,EACtC,MAAM,OAAO,EACb,OAAO,OACP,MAAM,kBACC,IAAI,CACqD"}
@@ -0,0 +1,2 @@
1
+ /** Settle updates when repository tests use Preact compatibility. @module */ export { act } from "preact/test-utils";
2
+ //# sourceMappingURL=test-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-utils.d.ts","sources":["../test-utils.ts"],"names":[],"mappings":"AAAA,2EAA2E,GAE3E,SAAS,GAAG,4BAAuC"}
package/client.ts ADDED
@@ -0,0 +1,34 @@
1
+ /** Preact compatibility roots for a host that paints its own tree. @module */
2
+
3
+ import {
4
+ createRoot as create,
5
+ hydrateRoot as hydrate,
6
+ } from 'npm:preact@10.29.7/compat/client'
7
+ import { paintFrames } from './draw.ts'
8
+
9
+ let root = (open: () => ReturnType<typeof create>) => {
10
+ let release = paintFrames()
11
+ try {
12
+ let { render, unmount } = open()
13
+ return {
14
+ render,
15
+ unmount() {
16
+ try {
17
+ unmount()
18
+ } finally {
19
+ release()
20
+ }
21
+ },
22
+ }
23
+ } catch (error) {
24
+ release()
25
+ throw error
26
+ }
27
+ }
28
+
29
+ /** Mount a Preact compatibility view into the host's tree. */
30
+ export let createRoot: typeof create = (...args) => root(() => create(...args))
31
+
32
+ /** Attach a Preact compatibility view to the existing tree. */
33
+ export let hydrateRoot: typeof hydrate = (...args) =>
34
+ root(() => hydrate(...args))
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"tasks":{"example":"deno run --allow-read --allow-net=127.0.0.1 example/serve.ts"},"publish":{"exclude":["**/*_test.ts","testing.ts","example/"]},"name":"@yaks/preact","version":"0.2.36","license":"Apache-2.0","description":"Renders registry-selected views with Preact and binds them to an entity store with subscriptions scoped to mounted components.","exports":{".":"./mod.ts","./host":"./host.ts","./draw":"./draw.ts","./renderer":"./renderer.ts","./test-utils":"./test-utils.ts"},"imports":{"@yaks/preact":"./mod.ts","@yaks/preact/host":"./host.ts","@yaks/preact/draw":"./draw.ts","@yaks/preact/renderer":"./renderer.ts","@yaks/preact/test-utils":"./test-utils.ts"}}
package/draw.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Draw a view into a tree with Preact: the verb a host that paints a tree of
3
+ * its own (@yaks/tui's terminal, @yaks/native's iOS views, a test's
4
+ * document) takes from the renderer, beside @yaks/react's.
5
+ *
6
+ * @module
7
+ */ import { options, render } from "preact";
8
+ let mounted = 0;
9
+ let restore = ()=>{};
10
+ /** Supply the paint scheduler while a host or test owns the document. */ export let frames = (schedule)=>{
11
+ let prior = options.requestAnimationFrame;
12
+ options.requestAnimationFrame = schedule;
13
+ return ()=>{
14
+ options.requestAnimationFrame = prior;
15
+ };
16
+ };
17
+ /** Run effects on a microtask while a host paints the tree. */ export let paintFrames = ()=>{
18
+ if (mounted++ == 0) {
19
+ restore = options.requestAnimationFrame ? ()=>{} : frames(queueMicrotask);
20
+ }
21
+ return ()=>{
22
+ if (--mounted == 0) restore();
23
+ };
24
+ };
25
+ /** Draw `node` into `into`, an element of a tree its host paints itself (an
26
+ * @yaks/dom tree, a test's document), and answer what takes it down. Such a
27
+ * host paints no browser frames, so effects run once the commit's microtasks
28
+ * are done, as a browser's next frame would run them, instead of Preact's
29
+ * fallback a few dozen milliseconds later. */ export let draw = (node, into)=>{
30
+ let release = paintFrames();
31
+ try {
32
+ render(node, into);
33
+ } catch (error) {
34
+ release();
35
+ throw error;
36
+ }
37
+ return ()=>{
38
+ try {
39
+ render(null, into);
40
+ } finally{
41
+ release();
42
+ }
43
+ };
44
+ };
45
+ //# sourceMappingURL=draw.js.map
package/draw.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"draw.js","sources":["./draw.ts"],"names":[],"mappings":"AAAA;;;;;;CAMC,GAED,SAAiC,OAAO,EAAE,MAAM,iBAA4B;AAE5E,IAAI,UAAU;AACd,IAAI,UAAU,KAAO;AAErB,uEAAuE,GACvE,OAAO,IAAI,SAAS,CAClB;EAEA,IAAI,QAAQ,QAAQ,qBAAqB;EACzC,QAAQ,qBAAqB,GAAG;EAChC,OAAO;IACL,QAAQ,qBAAqB,GAAG;EAClC;AACF,EAAC;AAED,6DAA6D,GAC7D,OAAO,IAAI,cAAc;EACvB,IAAI,aAAa,GAAG;IAClB,UAAU,QAAQ,qBAAqB,GAAG,KAAO,IAAI,OAAO;EAC9D;EACA,OAAO;IACL,IAAI,EAAE,WAAW,GAAG;EACtB;AACF,EAAC;AAED;;;;4CAI4C,GAC5C,OAAO,IAAI,OAAO,CAAC,MAAyB;EAC1C,IAAI,UAAU;EACd,IAAI;IACF,OAAO,MAAM;EACf,EAAE,OAAO,OAAO;IACd;IACA,MAAM;EACR;EACA,OAAO;IACL,IAAI;MACF,OAAO,MAAM;IACf,SAAU;MACR;IACF;EACF;AACF,EAAC"}
package/draw.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Draw a view into a tree with Preact: the verb a host that paints a tree of
3
+ * its own (@yaks/tui's terminal, @yaks/native's iOS views, a test's
4
+ * document) takes from the renderer, beside @yaks/react's.
5
+ *
6
+ * @module
7
+ */
8
+
9
+ import { type ComponentChildren, options, render } from 'preact'
10
+
11
+ let mounted = 0
12
+ let restore = () => {}
13
+
14
+ /** Supply the paint scheduler while a host or test owns the document. */
15
+ export let frames = (
16
+ schedule: NonNullable<typeof options.requestAnimationFrame>,
17
+ ): () => void => {
18
+ let prior = options.requestAnimationFrame
19
+ options.requestAnimationFrame = schedule
20
+ return () => {
21
+ options.requestAnimationFrame = prior
22
+ }
23
+ }
24
+
25
+ /** Run effects on a microtask while a host paints the tree. */
26
+ export let paintFrames = (): () => void => {
27
+ if (mounted++ == 0) {
28
+ restore = options.requestAnimationFrame ? () => {} : frames(queueMicrotask)
29
+ }
30
+ return () => {
31
+ if (--mounted == 0) restore()
32
+ }
33
+ }
34
+
35
+ /** Draw `node` into `into`, an element of a tree its host paints itself (an
36
+ * @yaks/dom tree, a test's document), and answer what takes it down. Such a
37
+ * host paints no browser frames, so effects run once the commit's microtasks
38
+ * are done, as a browser's next frame would run them, instead of Preact's
39
+ * fallback a few dozen milliseconds later. */
40
+ export let draw = (node: ComponentChildren, into: Element): () => void => {
41
+ let release = paintFrames()
42
+ try {
43
+ render(node, into)
44
+ } catch (error) {
45
+ release()
46
+ throw error
47
+ }
48
+ return () => {
49
+ try {
50
+ render(null, into)
51
+ } finally {
52
+ release()
53
+ }
54
+ }
55
+ }
package/host.js ADDED
@@ -0,0 +1,20 @@
1
+ /** Draw a page from a Preact views module and follow its draft. @module */ import { h, render } from "preact";
2
+ import { host as followed } from "@yaks/render/host";
3
+ import { entity, Registry, Vocabulary } from "./mod.js";
4
+ export { addressed, taken } from "@yaks/render/host";
5
+ /** Bind the views module to the page's store and redraw when it changes. */ export let host = (page)=>followed(page, (root, bound, registry, view)=>{
6
+ let Entity = entity({
7
+ ...bound,
8
+ registry
9
+ });
10
+ root.replaceChildren();
11
+ return {
12
+ draw: (next, words)=>render(h(Vocabulary.Provider, {
13
+ value: words
14
+ }, h(Registry.Provider, {
15
+ value: next
16
+ }, view(Entity))), root),
17
+ close: ()=>render(null, root)
18
+ };
19
+ });
20
+ //# sourceMappingURL=host.js.map
package/host.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sources":["./host.ts"],"names":[],"mappings":"AAAA,yEAAyE,GACzE,SAAsD,CAAC,EAAE,MAAM,iBAA4B;AAC3F,SAEE,QAAQ,QAAQ,iCAGmB;AACrC,SACE,MAAM,EAGN,QAAQ,EACR,UAAU,mBACK;AAEjB,SAAS,SAAS,EAAc,KAAK,iCAAsC;AAQ3E,0EAA0E,GAC1E,OAAO,IAAI,OAAO,CAAC,OACjB,SAAS,MAAM,CAAC,MAAM,OAAO,UAAU;IACrC,IAAI,SAAS,OAAO;MAAE,GAAG,KAAK;MAAE;IAAS;IACzC,KAAK,eAAe;IACpB,OAAO;MACL,MAAM,CAAC,MAAM,QACX,OACE,EACE,WAAW,QAAQ,EACnB;UAAE,OAAO;QAAM,GACf,EAAE,SAAS,QAAQ,EAAE;UAAE,OAAO;QAAK,GAAG,KAAK,WAE7C;MAEJ,OAAO,IAAM,OAAO,MAAM;IAC5B;EACF,GAAE"}
package/host.ts ADDED
@@ -0,0 +1,42 @@
1
+ /** Draw a page from a Preact views module and follow its draft. @module */
2
+ import { type ComponentChild, type FunctionComponent, h, render } from 'preact'
3
+ import {
4
+ type Host as PageHost,
5
+ host as followed,
6
+ type Page as PageOf,
7
+ type Views as ViewsOf,
8
+ } from '@yaks/render/host'
9
+ import {
10
+ entity,
11
+ type EntityProps,
12
+ type HostRegistry,
13
+ Registry,
14
+ Vocabulary,
15
+ } from './mod.js'
16
+
17
+ export { addressed, type Draft, taken } from '@yaks/render/host'
18
+ export type Views = ViewsOf<HostRegistry>
19
+ export type Host = PageHost<HostRegistry>
20
+ export type Page = PageOf<
21
+ HostRegistry,
22
+ (Entity: FunctionComponent<EntityProps>) => ComponentChild
23
+ >
24
+
25
+ /** Bind the views module to the page's store and redraw when it changes. */
26
+ export let host = (page: Page): Promise<Host> =>
27
+ followed(page, (root, bound, registry, view) => {
28
+ let Entity = entity({ ...bound, registry })
29
+ root.replaceChildren()
30
+ return {
31
+ draw: (next, words) =>
32
+ render(
33
+ h(
34
+ Vocabulary.Provider,
35
+ { value: words },
36
+ h(Registry.Provider, { value: next }, view(Entity)),
37
+ ),
38
+ root,
39
+ ),
40
+ close: () => render(null, root),
41
+ }
42
+ })
package/mod.js ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @yaks/preact is the Preact rendering backend for portable renderers. `render`
3
+ * passes Preact's hyperscript to the selected renderer; `entity` binds a
4
+ * registry, a vocabulary and a store into an <Entity eid view/> component. The store remains
5
+ * a function, with an optional per-entity subscription supplied beside it.
6
+ * Missing bundles or unmatched views render nothing. Subscriptions belong to
7
+ * the mounted component and are released when its eid changes or it unmounts.
8
+ *
9
+ * ```ts
10
+ * import { assertEquals } from '@std/assert'
11
+ * import { define } from '@yaks/render'
12
+ * import { loadVocab } from '@yaks/vocab'
13
+ * import { render } from '@yaks/preact'
14
+ *
15
+ * let registry = define([{
16
+ * view: 'Tile', match: true,
17
+ * render: (b, h) => h('p', null, b.entity.eid),
18
+ * }])
19
+ * let node = render(registry, {entity: {eid: 'a'}}, 'Tile', loadVocab([]))!
20
+ * assertEquals(node.type, 'p')
21
+ * assertEquals(node.props.children, ['a'])
22
+ * ```
23
+ *
24
+ * @module
25
+ */ import { createContext, h } from "preact";
26
+ import { useContext, useLayoutEffect, useState } from "preact/hooks";
27
+ import { rendering, resolve } from "@yaks/render";
28
+ import { committed } from "@yaks/render/component";
29
+ // The shared child contract admits readonly arrays; Preact reads the same
30
+ // structure but declares mutable arrays. Keep that type adaptation at the host.
31
+ let hyperscript = (bundle, ctx)=>(tag, props, ...children)=>{
32
+ props = committed(props, bundle, ctx);
33
+ return children.length ? h(tag, props, children) : h(tag, props);
34
+ };
35
+ export function render(registry, bundle, view, vocab, ctx = {}, props) {
36
+ let renderer = resolve(registry, bundle, view, vocab, ctx);
37
+ if (!renderer) return null;
38
+ let context = {
39
+ ...ctx,
40
+ render: (view, overrides)=>{
41
+ let next = {
42
+ ...ctx,
43
+ ...overrides
44
+ };
45
+ return render(registry, bundle, view, vocab, next, {
46
+ ...props,
47
+ ...next,
48
+ e: props ? props.e : bundle
49
+ });
50
+ }
51
+ };
52
+ if ('Render' in renderer) {
53
+ // Without explicit props the public overload requires E to be Bundle.
54
+ return h(renderer.Render, {
55
+ ...context,
56
+ ...props,
57
+ render: context.render,
58
+ e: props ? props.e : bundle
59
+ });
60
+ }
61
+ return rendering(renderer, context)?.(bundle, hyperscript(bundle, ctx), {
62
+ ...context,
63
+ vocab
64
+ }) ?? null;
65
+ }
66
+ /** The vocabulary the host has most recently merged into its page graph. */ export let Vocabulary = createContext(undefined);
67
+ /**
68
+ * A registry provided above an Entity replaces the one it was bound with, and
69
+ * a new value draws every Entity below it again even when its props are the
70
+ * same, which a top-level `render` with the same props does not promise:
71
+ * `@preact/signals` skips a component holding hook state whose props are
72
+ * unchanged. The page host swaps a written views module in through it
73
+ * (./host.ts).
74
+ */ export let Registry = createContext(undefined);
75
+ /**
76
+ * Bind the application once: `let Entity = entity({registry, vocab, store,
77
+ * subscribe})`, then mount `<Entity eid='a' view='Tile'/>` through Preact.
78
+ * A notification re-reads the store even if it mutated a bundle in place.
79
+ */ export let entity = ({ registry, vocab, store, subscribe })=>({ eid, view, ...ctx })=>{
80
+ let now = useContext(Registry) ?? registry;
81
+ let words = useContext(Vocabulary) ?? vocab;
82
+ let [, revision] = useState(0);
83
+ let refresh = ()=>revision((n)=>n + 1);
84
+ useLayoutEffect(()=>{
85
+ if (!subscribe) return;
86
+ let active = true;
87
+ let off = subscribe(eid, ()=>{
88
+ if (active) refresh();
89
+ });
90
+ // A store may move between the render read and subscribing, including
91
+ // mutating the same object. Re-read once after the listener is installed.
92
+ refresh();
93
+ return ()=>{
94
+ active = false;
95
+ off();
96
+ };
97
+ }, [
98
+ eid
99
+ ]);
100
+ let bundle = store(eid);
101
+ if (!bundle) return null;
102
+ return render(now, bundle, view, words, ctx);
103
+ };
104
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GAED,SAGE,aAAa,EAEb,CAAC,iBAEwB;AAC3B,SAAS,UAAU,EAAE,eAAe,EAAE,QAAQ,uBAAkC;AAChF,SAOE,SAAS,EACT,OAAO,4BAEuB;AAChC,SACE,SAAS,sCAK+B;AA8B1C,0EAA0E;AAC1E,gFAAgF;AAChF,IAAI,cAAc,CAChB,QACA,MAEF,CAAC,KAAK,OAAO,GAAG;IACd,QAAQ,UAAU,OAAO,QAAQ;IACjC,OAAO,SAAS,MAAM,GAClB,EAA2B,KAAK,OAAO,YACvC,EAA2B,KAAK;EACtC;AA6BA,OAAO,SAAS,OACd,QAAyB,EACzB,MAAc,EACd,IAAwB,EACxB,KAAY,EACZ,MAAwB,CAAC,CAAC,EAC1B,KAA0B;EAE1B,IAAI,WAAW,QAAQ,UAAU,QAAQ,MAAM,OAAO;EACtD,IAAI,CAAC,UAAU,OAAO;EACtB,IAAI,UAA2C;IAC7C,GAAG,GAAG;IACN,QAAQ,CAAC,MAAM;MACb,IAAI,OAAO;QAAE,GAAG,GAAG;QAAE,GAAG,SAAS;MAAC;MAClC,OAAO,OACL,UACA,QACA,MACA,OACA,MACA;QAAE,GAAG,KAAK;QAAE,GAAG,IAAI;QAAE,GAAG,QAAQ,MAAM,CAAC,GAAG;MAAY;IAE1D;EACF;EACA,IAAI,YAAY,UAAU;IACxB,sEAAsE;IACtE,OAAO,EACL,SAAS,MAAM,EACf;MACE,GAAG,OAAO;MACV,GAAG,KAAK;MACR,QAAQ,QAAQ,MAAM;MACtB,GAAG,QAAQ,MAAM,CAAC,GAAG;IACvB;EAEJ;EACA,OAAO,UAAU,UAAU,WAAW,QAAQ,YAAY,QAAQ,MAAM;IACtE,GAAG,OAAO;IACV;EACF,MAAM;AACR;AAEA,0EAA0E,GAC1E,OAAO,IAAI,aAA0C,cAEnD,WAAU;AAEZ;;;;;;;CAOC,GACD,OAAO,IAAI,WAA+C,cAExD,WAAU;AAEZ;;;;CAIC,GACD,OAAO,IAAI,SAAS,CAClB,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,SAAS,EAAW,GAEhD,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,KAAK;IACpB,IAAI,MAAM,WAAW,aAAa;IAClC,IAAI,QAAQ,WAAW,eAAe;IACtC,IAAI,GAAG,SAAS,GAAG,SAAS;IAC5B,IAAI,UAAU,IAAM,SAAS,CAAC,IAAM,IAAI;IACxC,gBAAgB;MACd,IAAI,CAAC,WAAW;MAChB,IAAI,SAAS;MACb,IAAI,MAAM,UAAU,KAAK;QACvB,IAAI,QAAQ;MACd;MACA,sEAAsE;MACtE,0EAA0E;MAC1E;MACA,OAAO;QACL,SAAS;QACT;MACF;IACF,GAAG;MAAC;KAAI;IACR,IAAI,SAAS,MAAM;IACnB,IAAI,CAAC,QAAQ,OAAO;IACpB,OAAO,OAAO,KAAK,QAAQ,MAAM,OAAO;EAC1C,EAAC"}
package/mod.ts ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * @yaks/preact is the Preact rendering backend for portable renderers. `render`
3
+ * passes Preact's hyperscript to the selected renderer; `entity` binds a
4
+ * registry, a vocabulary and a store into an <Entity eid view/> component. The store remains
5
+ * a function, with an optional per-entity subscription supplied beside it.
6
+ * Missing bundles or unmatched views render nothing. Subscriptions belong to
7
+ * the mounted component and are released when its eid changes or it unmounts.
8
+ *
9
+ * ```ts
10
+ * import { assertEquals } from '@std/assert'
11
+ * import { define } from '@yaks/render'
12
+ * import { loadVocab } from '@yaks/vocab'
13
+ * import { render } from '@yaks/preact'
14
+ *
15
+ * let registry = define([{
16
+ * view: 'Tile', match: true,
17
+ * render: (b, h) => h('p', null, b.entity.eid),
18
+ * }])
19
+ * let node = render(registry, {entity: {eid: 'a'}}, 'Tile', loadVocab([]))!
20
+ * assertEquals(node.type, 'p')
21
+ * assertEquals(node.props.children, ['a'])
22
+ * ```
23
+ *
24
+ * @module
25
+ */
26
+
27
+ import {
28
+ type ComponentChildren,
29
+ type Context as Provided,
30
+ createContext,
31
+ type FunctionComponent,
32
+ h,
33
+ type VNode,
34
+ } from 'preact'
35
+ import { useContext, useLayoutEffect, useState } from 'preact/hooks'
36
+ import {
37
+ type Bundle,
38
+ type Context,
39
+ type H,
40
+ type Registration,
41
+ type RenderContext,
42
+ type Renderer,
43
+ rendering,
44
+ resolve,
45
+ type Selection,
46
+ } from '@yaks/render'
47
+ import {
48
+ committed,
49
+ type EntityProps,
50
+ type Events,
51
+ type Store,
52
+ type Subscribe,
53
+ } from '@yaks/render/component'
54
+ export type {
55
+ EntityProps,
56
+ Events,
57
+ Store,
58
+ Subscribe,
59
+ } from '@yaks/render/component'
60
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
61
+
62
+ /** A native component; the host mounts it so Preact owns its hooks and identity. */
63
+ export type ComponentRenderer<E = Bundle> = Registration & {
64
+ Render: FunctionComponent<Context & Events & { e: E }>
65
+ }
66
+
67
+ /** Portable trees and native components share the same selection machinery. */
68
+ export type HostRegistry<E = Bundle> = Selection<
69
+ Renderer | ComponentRenderer<E>
70
+ >
71
+ type Node<E = Bundle> =
72
+ | VNode<Record<string, unknown>>
73
+ | VNode<Context & { e: E }>
74
+
75
+ /** The values bound once when an application creates its Entity component. */
76
+ export type Options = {
77
+ registry: HostRegistry
78
+ vocab: Vocab
79
+ store: Store
80
+ subscribe?: Subscribe
81
+ }
82
+
83
+ // The shared child contract admits readonly arrays; Preact reads the same
84
+ // structure but declares mutable arrays. Keep that type adaptation at the host.
85
+ let hyperscript = <E>(
86
+ bundle: Bundle,
87
+ ctx: Events,
88
+ ): H<Node<E>> =>
89
+ (tag, props, ...children) => {
90
+ props = committed(props, bundle, ctx)
91
+ return children.length
92
+ ? h<Record<string, unknown>>(tag, props, children as ComponentChildren)
93
+ : h<Record<string, unknown>>(tag, props)
94
+ }
95
+
96
+ /**
97
+ * Resolve a view and build a Preact node. Native components are passed to h,
98
+ * never invoked directly. Native props default to {e: bundle, ...ctx}; callers
99
+ * with another entity shape supply their typed props as the sixth argument.
100
+ */
101
+ export function render(
102
+ registry: Selection<Renderer>,
103
+ bundle: Bundle,
104
+ view: string | undefined,
105
+ vocab: Vocab,
106
+ ctx?: Context & Events,
107
+ ): VNode<Record<string, unknown>> | null
108
+ export function render(
109
+ registry: HostRegistry,
110
+ bundle: Bundle,
111
+ view: string | undefined,
112
+ vocab: Vocab,
113
+ ctx?: Context & Events,
114
+ ): Node | null
115
+ export function render<E>(
116
+ registry: HostRegistry<E>,
117
+ bundle: Bundle,
118
+ view: string | undefined,
119
+ vocab: Vocab,
120
+ ctx: Context & Events,
121
+ props: Context & { e: E },
122
+ ): Node<E> | null
123
+ export function render<E>(
124
+ registry: HostRegistry<E>,
125
+ bundle: Bundle,
126
+ view: string | undefined,
127
+ vocab: Vocab,
128
+ ctx: Context & Events = {},
129
+ props?: Context & { e: E },
130
+ ): Node<E> | null {
131
+ let renderer = resolve(registry, bundle, view, vocab, ctx)
132
+ if (!renderer) return null
133
+ let context: RenderContext<Node<E>> & Events = {
134
+ ...ctx,
135
+ render: (view, overrides) => {
136
+ let next = { ...ctx, ...overrides }
137
+ return render(
138
+ registry,
139
+ bundle,
140
+ view,
141
+ vocab,
142
+ next,
143
+ { ...props, ...next, e: props ? props.e : bundle as E },
144
+ )
145
+ },
146
+ }
147
+ if ('Render' in renderer) {
148
+ // Without explicit props the public overload requires E to be Bundle.
149
+ return h(
150
+ renderer.Render,
151
+ {
152
+ ...context,
153
+ ...props,
154
+ render: context.render,
155
+ e: props ? props.e : bundle as E,
156
+ },
157
+ )
158
+ }
159
+ return rendering(renderer, context)?.(bundle, hyperscript(bundle, ctx), {
160
+ ...context,
161
+ vocab,
162
+ }) ?? null
163
+ }
164
+
165
+ /** The vocabulary the host has most recently merged into its page graph. */
166
+ export let Vocabulary: Provided<Vocab | undefined> = createContext<
167
+ Vocab | undefined
168
+ >(undefined)
169
+
170
+ /**
171
+ * A registry provided above an Entity replaces the one it was bound with, and
172
+ * a new value draws every Entity below it again even when its props are the
173
+ * same, which a top-level `render` with the same props does not promise:
174
+ * `@preact/signals` skips a component holding hook state whose props are
175
+ * unchanged. The page host swaps a written views module in through it
176
+ * (./host.ts).
177
+ */
178
+ export let Registry: Provided<HostRegistry | undefined> = createContext<
179
+ HostRegistry | undefined
180
+ >(undefined)
181
+
182
+ /**
183
+ * Bind the application once: `let Entity = entity({registry, vocab, store,
184
+ * subscribe})`, then mount `<Entity eid='a' view='Tile'/>` through Preact.
185
+ * A notification re-reads the store even if it mutated a bundle in place.
186
+ */
187
+ export let entity = (
188
+ { registry, vocab, store, subscribe }: Options,
189
+ ): FunctionComponent<EntityProps> =>
190
+ ({ eid, view, ...ctx }) => {
191
+ let now = useContext(Registry) ?? registry
192
+ let words = useContext(Vocabulary) ?? vocab
193
+ let [, revision] = useState(0)
194
+ let refresh = () => revision((n) => n + 1)
195
+ useLayoutEffect(() => {
196
+ if (!subscribe) return
197
+ let active = true
198
+ let off = subscribe(eid, () => {
199
+ if (active) refresh()
200
+ })
201
+ // A store may move between the render read and subscribing, including
202
+ // mutating the same object. Re-read once after the listener is installed.
203
+ refresh()
204
+ return () => {
205
+ active = false
206
+ off()
207
+ }
208
+ }, [eid])
209
+ let bundle = store(eid)
210
+ if (!bundle) return null
211
+ return render(now, bundle, view, words, ctx)
212
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@yaks/preact",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/preact",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./host": {
12
+ "types": "./_dist/host.d.ts",
13
+ "default": "./host.js"
14
+ },
15
+ "./draw": {
16
+ "types": "./_dist/draw.d.ts",
17
+ "default": "./draw.js"
18
+ },
19
+ "./renderer": {
20
+ "types": "./_dist/renderer.d.ts",
21
+ "default": "./renderer.js"
22
+ },
23
+ "./test-utils": {
24
+ "types": "./_dist/test-utils.d.ts",
25
+ "default": "./test-utils.js"
26
+ }
27
+ },
28
+ "license": "Apache-2.0",
29
+ "dependencies": {
30
+ "@yaks/render": "0.2.36",
31
+ "@yaks/vocab": "0.2.36",
32
+ "preact": "10.29.7"
33
+ },
34
+ "description": "Renders registry-selected views with Preact and binds them to an entity store with subscriptions scoped to mounted components.",
35
+ "repository": "https://github.com/yak-sh/yak.git"
36
+ }
package/renderer.js ADDED
@@ -0,0 +1,21 @@
1
+ /** The module names the Preact renderer supplies to an app. @module */ import manifest from './package.json' with {
2
+ type: 'json'
3
+ };
4
+ import * as preact from "preact";
5
+ import * as hooks from "preact/hooks";
6
+ import * as compat from "preact/compat";
7
+ import * as client from "preact/compat/client";
8
+ import * as jsx from "preact/jsx-runtime";
9
+ import { draw } from "./draw.js";
10
+ /** Package aliases for a view selected to run on Preact. */ export let aliases = manifest.yaksRenderer.aliases;
11
+ /** The renderer modules an app can import from its host. */ export let modules = {
12
+ preact,
13
+ 'preact/hooks': hooks,
14
+ 'preact/compat': compat,
15
+ 'preact/compat/client': client,
16
+ 'preact/jsx-runtime': jsx,
17
+ react: compat,
18
+ 'react/jsx-runtime': jsx
19
+ };
20
+ /** Draw a component loaded from a Preact app into a host's tree. */ export let paint = (view, props, into)=>draw(preact.h(view, props), into);
21
+ //# sourceMappingURL=renderer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"renderer.js","sources":["./renderer.ts"],"names":[],"mappings":"AAAA,qEAAqE,GAErE,OAAO,cAAc,sBAAsB;EAAE,MAAM;AAAO,EAAC;AAC3D,YAAY,qBAAgC;AAC5C,YAAY,0BAAqC;AACjD,YAAY,4BAAuC;AACnD,YAAY,mCAA8C;AAC1D,YAAY,8BAAyC;AACrD,SAAS,IAAI,oBAAmB;AAEhC,0DAA0D,GAC1D,OAAO,IAAI,UAAkC,SAAS,YAAY,CAAC,OAAO,CAAA;AAE1E,0DAA0D,GAC1D,OAAO,IAAI,UAAkC;EAC3C;EACA,gBAAgB;EAChB,iBAAiB;EACjB,wBAAwB;EACxB,sBAAsB;EACtB,OAAO;EACP,qBAAqB;AACvB,EAAC;AAED,kEAAkE,GAClE,OAAO,IAAI,QAAQ,CACjB,MACA,OACA,OAEA,KAAK,OAAO,CAAC,CAAC,MAAqC,QAAQ,MAAK"}
package/renderer.ts ADDED
@@ -0,0 +1,31 @@
1
+ /** The module names the Preact renderer supplies to an app. @module */
2
+
3
+ import manifest from './package.json' with { type: 'json' }
4
+ import * as preact from 'preact'
5
+ import * as hooks from 'preact/hooks'
6
+ import * as compat from 'preact/compat'
7
+ import * as client from 'preact/compat/client'
8
+ import * as jsx from 'preact/jsx-runtime'
9
+ import { draw } from './draw.js'
10
+
11
+ /** Package aliases for a view selected to run on Preact. */
12
+ export let aliases: Record<string, string> = manifest.yaksRenderer.aliases
13
+
14
+ /** The renderer modules an app can import from its host. */
15
+ export let modules: Record<string, object> = {
16
+ preact,
17
+ 'preact/hooks': hooks,
18
+ 'preact/compat': compat,
19
+ 'preact/compat/client': client,
20
+ 'preact/jsx-runtime': jsx,
21
+ react: compat,
22
+ 'react/jsx-runtime': jsx,
23
+ }
24
+
25
+ /** Draw a component loaded from a Preact app into a host's tree. */
26
+ export let paint = <Props extends object>(
27
+ view: unknown,
28
+ props: Props,
29
+ into: Element,
30
+ ): () => void =>
31
+ draw(preact.h(view as preact.ComponentType<Props>, props), into)
package/test-utils.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Settle updates when repository tests use Preact compatibility. @module */ export { act } from "preact/test-utils";
2
+ //# sourceMappingURL=test-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-utils.js","sources":["./test-utils.ts"],"names":[],"mappings":"AAAA,2EAA2E,GAE3E,SAAS,GAAG,4BAAuC"}
package/test-utils.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Settle updates when repository tests use Preact compatibility. @module */
2
+
3
+ export { act } from 'preact/test-utils'