@krate/runtime 0.4.0-rc.4 → 0.4.0-rc.6
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/dist/class-helpers.d.ts +4 -4
- package/dist/class-helpers.js +5 -5
- package/dist/context.d.ts +18 -1
- package/dist/context.js +27 -7
- package/dist/dev-overlay.d.ts +22 -0
- package/dist/dev-overlay.js +145 -8
- package/dist/dev-overlay.test.js +41 -10
- package/dist/dom.js +5 -5
- package/dist/error-overlay.d.ts +1 -1
- package/dist/error-overlay.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/krate-dev.js +124 -7
- package/dist/krate-hydrate.js +1 -1
- package/dist/krate-runtime.js +1 -1
- package/dist/reconcile.js +25 -21
- package/dist/reconcile.test.d.ts +1 -0
- package/dist/reconcile.test.js +47 -0
- package/dist/router.js +6 -6
- package/dist/server-jsx-runtime.js +1 -1
- package/dist/server-renderer.js +42 -18
- package/dist/server.d.ts +1 -0
- package/dist/server.js +44 -13
- package/dist/server.test.d.ts +1 -0
- package/dist/server.test.js +48 -0
- package/dist/signal.d.ts +44 -10
- package/dist/signal.js +22 -15
- package/package.json +1 -1
package/dist/server-renderer.js
CHANGED
|
@@ -1,11 +1,27 @@
|
|
|
1
|
-
// @krate/runtime/server-renderer
|
|
1
|
+
// @krate/runtime/server-renderer - Node.js HTTP server for SSR/ISR/Streaming
|
|
2
2
|
// Receives render requests from the Go server and returns HTML.
|
|
3
3
|
import http from "node:http";
|
|
4
|
+
import cluster from "node:cluster";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import vm from "node:vm";
|
|
7
8
|
import { pathToFileURL } from "node:url";
|
|
8
9
|
import { renderToString } from "./server.js";
|
|
10
|
+
// Cluster across cores: page/region rendering is independent per request, so N
|
|
11
|
+
// workers scale it past a single core. Krate sets KRATE_SSR_WORKERS from
|
|
12
|
+
// ssr.rendererWorkers. Region/ISR caches are per-worker and ISR disk persistence
|
|
13
|
+
// is disabled when clustered (the primary never serves).
|
|
14
|
+
const SSR_WORKERS = Math.max(1, parseInt(process.env.KRATE_SSR_WORKERS || "1", 10) || 1);
|
|
15
|
+
const isClusterPrimary = SSR_WORKERS > 1 && cluster.isPrimary;
|
|
16
|
+
if (isClusterPrimary) {
|
|
17
|
+
for (let i = 0; i < SSR_WORKERS; i++)
|
|
18
|
+
cluster.fork();
|
|
19
|
+
cluster.on("exit", (worker) => {
|
|
20
|
+
console.log(`[krate-ssr] worker ${worker.process.pid} exited; restarting`);
|
|
21
|
+
cluster.fork();
|
|
22
|
+
});
|
|
23
|
+
console.log(`[krate-ssr] primary supervising ${SSR_WORKERS} workers`);
|
|
24
|
+
}
|
|
9
25
|
// Force TCP_NODELAY on socket to prevent Nagle buffering chunks together.
|
|
10
26
|
// Must be called BEFORE the first write for it to take effect.
|
|
11
27
|
function setupStream(res) {
|
|
@@ -14,7 +30,7 @@ function setupStream(res) {
|
|
|
14
30
|
socket.setNoDelay(true);
|
|
15
31
|
}
|
|
16
32
|
}
|
|
17
|
-
//
|
|
33
|
+
// ISR Cache (variant-aware, SWR, persisted)
|
|
18
34
|
// A page's cache key is the route plus its per-request variant (params +
|
|
19
35
|
// query). Two dynamic-route requests (e.g. /video/a and /video/b) render
|
|
20
36
|
// different HTML, so they must never share a cache slot.
|
|
@@ -117,7 +133,7 @@ function withRenderTimeout(p) {
|
|
|
117
133
|
p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
|
|
118
134
|
});
|
|
119
135
|
}
|
|
120
|
-
// ISR cache persistence
|
|
136
|
+
// ISR cache persistence - survives renderer restarts so a bounce doesn't
|
|
121
137
|
// cold-render every ISR variant. Written debounced (coalesced) to the build
|
|
122
138
|
// output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
|
|
123
139
|
let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
|
|
@@ -126,6 +142,10 @@ function isrCachePath() {
|
|
|
126
142
|
return isrCacheFile || path.join(root, "dist", ".krate", "isr-cache.json");
|
|
127
143
|
}
|
|
128
144
|
function scheduleIsrPersist() {
|
|
145
|
+
// Clustered: multiple workers would race on the same cache file; keep the ISR
|
|
146
|
+
// cache in memory only.
|
|
147
|
+
if (SSR_WORKERS > 1)
|
|
148
|
+
return;
|
|
129
149
|
if (persistTimer)
|
|
130
150
|
clearTimeout(persistTimer);
|
|
131
151
|
persistTimer = setTimeout(() => {
|
|
@@ -156,7 +176,7 @@ function loadIsrCache() {
|
|
|
156
176
|
console.error("[krate-ssr] ISR cache load failed:", err.message);
|
|
157
177
|
}
|
|
158
178
|
}
|
|
159
|
-
//
|
|
179
|
+
// Page Module Loader
|
|
160
180
|
const moduleCache = new Map();
|
|
161
181
|
async function loadPageModule(page) {
|
|
162
182
|
// Prefer pre-compiled server bundle over raw source
|
|
@@ -184,7 +204,7 @@ async function loadPageModule(page) {
|
|
|
184
204
|
throw err;
|
|
185
205
|
}
|
|
186
206
|
}
|
|
187
|
-
//
|
|
207
|
+
// Renderer
|
|
188
208
|
let manifest = null;
|
|
189
209
|
let projectRoot = "";
|
|
190
210
|
function findPage(route) {
|
|
@@ -213,7 +233,7 @@ function buildProps(req) {
|
|
|
213
233
|
props.query = req.query;
|
|
214
234
|
return props;
|
|
215
235
|
}
|
|
216
|
-
// renderFresh renders a page component and
|
|
236
|
+
// renderFresh renders a page component and - for ISR pages - stores the result.
|
|
217
237
|
// Extracted so background revalidation shares exactly the same render path.
|
|
218
238
|
async function renderFresh(page, req) {
|
|
219
239
|
try {
|
|
@@ -275,7 +295,7 @@ function revalidateInBackground(page, req) {
|
|
|
275
295
|
// keeping the entries in place. This is the non-destructive counterpart of
|
|
276
296
|
// /__krate/ssr/revalidate (which clears a route). The Go server's periodic ISR
|
|
277
297
|
// timer calls this so cached pages stay fresh without evicting dynamic
|
|
278
|
-
// variants
|
|
298
|
+
// variants - eviction would turn a request that should be a HIT into a MISS.
|
|
279
299
|
const inFlightRouteRefreshes = new Map();
|
|
280
300
|
function refreshRouteVariants(page) {
|
|
281
301
|
const running = inFlightRouteRefreshes.get(page.route);
|
|
@@ -344,12 +364,11 @@ async function renderPage(req) {
|
|
|
344
364
|
response.cacheStatus = "miss";
|
|
345
365
|
return response;
|
|
346
366
|
}
|
|
347
|
-
//
|
|
348
|
-
//
|
|
367
|
+
// Region rendering (static-first)
|
|
349
368
|
// The Go server owns the page: it serves the build-time static shell with the
|
|
350
|
-
//
|
|
369
|
+
// <!-suspense:ID-> markers and baked fallbacks, then asks the sidecar to render
|
|
351
370
|
// ONLY the page's dynamic regions. Each region is rendered by its compiled
|
|
352
|
-
// runtime component bundle (server-components/<Name>.runtime.js
|
|
371
|
+
// runtime component bundle (server-components/<Name>.runtime.js - an IIFE that
|
|
353
372
|
// defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
|
|
354
373
|
// so nothing is re-derived at request time.
|
|
355
374
|
const runtimeBundleCache = new Map();
|
|
@@ -512,7 +531,7 @@ function extractTitle(html) {
|
|
|
512
531
|
const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
|
|
513
532
|
return match ? match[1].trim() : "";
|
|
514
533
|
}
|
|
515
|
-
//
|
|
534
|
+
// HTTP Server
|
|
516
535
|
const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
|
|
517
536
|
const manifestPath = process.env.KRATE_MANIFEST || "";
|
|
518
537
|
const root = process.env.KRATE_ROOT || process.cwd();
|
|
@@ -623,7 +642,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
623
642
|
}
|
|
624
643
|
return;
|
|
625
644
|
}
|
|
626
|
-
//
|
|
645
|
+
// /__krate/regions - render ONLY a page's dynamic regions
|
|
627
646
|
// One NDJSON frame per region, written as its own chunk so the Go server
|
|
628
647
|
// forwards each region progressively and splices it into the static shell.
|
|
629
648
|
// The Go server sends the splice markers it parsed from the shell; the
|
|
@@ -671,7 +690,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
671
690
|
writeJsonLine(res, await renderRegion(page, region, renderReq));
|
|
672
691
|
}
|
|
673
692
|
else {
|
|
674
|
-
// Unknown region id
|
|
693
|
+
// Unknown region id - keep the baked content by sending no frame.
|
|
675
694
|
writeJsonLine(res, { type: "skip", id: r.id });
|
|
676
695
|
}
|
|
677
696
|
}
|
|
@@ -685,7 +704,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
685
704
|
res.end();
|
|
686
705
|
return;
|
|
687
706
|
}
|
|
688
|
-
//
|
|
707
|
+
// Direct page requests (non-proxied)
|
|
689
708
|
// Collect request headers
|
|
690
709
|
const headers = {};
|
|
691
710
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
@@ -742,6 +761,11 @@ const server = http.createServer(async (req, res) => {
|
|
|
742
761
|
res.writeHead(result.status, headers_extra);
|
|
743
762
|
res.end(result.html);
|
|
744
763
|
});
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
}
|
|
764
|
+
if (isClusterPrimary) {
|
|
765
|
+
// The primary only supervises; workers own the listening socket.
|
|
766
|
+
}
|
|
767
|
+
else {
|
|
768
|
+
server.listen(PORT, () => {
|
|
769
|
+
console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
|
|
770
|
+
});
|
|
771
|
+
}
|
package/dist/server.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export declare function onMount(_fn: () => void): void;
|
|
|
6
6
|
interface RawHTML {
|
|
7
7
|
__raw: string;
|
|
8
8
|
}
|
|
9
|
+
export declare function goComponent(name: string, tier: string, baked: Record<string, string> | null | undefined, props: Record<string, any> | undefined, revalidate?: number): JSXNode;
|
|
9
10
|
type JSXNode = string | number | boolean | null | undefined | JSXNode[] | JSXElement | RawHTML;
|
|
10
11
|
interface JSXElement {
|
|
11
12
|
type: string | Function;
|
package/dist/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
// @krate/runtime/server
|
|
1
|
+
// @krate/runtime/server - Server-side rendering runtime
|
|
2
2
|
// Provides the same API as the client runtime but renders to HTML strings.
|
|
3
|
-
//
|
|
3
|
+
// Signal (server: returns initial value, no reactivity)
|
|
4
4
|
export function createSignal(initial) {
|
|
5
5
|
let value = initial;
|
|
6
6
|
const read = () => value;
|
|
@@ -10,7 +10,7 @@ export function createSignal(initial) {
|
|
|
10
10
|
return [read, write];
|
|
11
11
|
}
|
|
12
12
|
export function createEffect(_fn) {
|
|
13
|
-
// No-op on server
|
|
13
|
+
// No-op on server - effects only run on client
|
|
14
14
|
return () => { };
|
|
15
15
|
}
|
|
16
16
|
export function createMemo(fn) {
|
|
@@ -33,6 +33,37 @@ export function onMount(_fn) {
|
|
|
33
33
|
// and crash.
|
|
34
34
|
}
|
|
35
35
|
function raw(html) { return { __raw: html }; }
|
|
36
|
+
// goComponent is the SSR bridge for Go-authored components (see the compiler's
|
|
37
|
+
// server-bundle esbuild plugin). A server-tier component inlines its build-time
|
|
38
|
+
// baked HTML when the call site was annotated with __krateGoId; otherwise (and
|
|
39
|
+
// always for runtime-tier) it emits a marker the Go server resolves by calling
|
|
40
|
+
// the Go host at request time. revalidate is the component file's cache window,
|
|
41
|
+
// carried in the marker so the Go server needn't look it up by name.
|
|
42
|
+
export function goComponent(name, tier, baked, props, revalidate = 0) {
|
|
43
|
+
const p = props || {};
|
|
44
|
+
const id = p.__krateGoId;
|
|
45
|
+
if (tier === "server" && baked && id && Object.prototype.hasOwnProperty.call(baked, id)) {
|
|
46
|
+
return raw(baked[id]);
|
|
47
|
+
}
|
|
48
|
+
const rest = {};
|
|
49
|
+
for (const k in p) {
|
|
50
|
+
if (k !== "__krateGoId" && k !== "children")
|
|
51
|
+
rest[k] = p[k];
|
|
52
|
+
}
|
|
53
|
+
if (p.children != null) {
|
|
54
|
+
const kids = renderToString(p.children);
|
|
55
|
+
if (kids !== "")
|
|
56
|
+
rest["children"] = kids;
|
|
57
|
+
}
|
|
58
|
+
return raw("<!--krate-go:" + name + ":" + (revalidate > 0 ? revalidate : 0) + ":" + base64url(JSON.stringify(rest)) + "-->");
|
|
59
|
+
}
|
|
60
|
+
function base64url(s) {
|
|
61
|
+
const bytes = new TextEncoder().encode(s);
|
|
62
|
+
let bin = "";
|
|
63
|
+
for (let i = 0; i < bytes.length; i++)
|
|
64
|
+
bin += String.fromCharCode(bytes[i]);
|
|
65
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
66
|
+
}
|
|
36
67
|
export function Fragment(_props) {
|
|
37
68
|
return _props.children ?? [];
|
|
38
69
|
}
|
|
@@ -46,7 +77,7 @@ export function jsx(type, props, _key) {
|
|
|
46
77
|
return { type, props: rest, children: childArray };
|
|
47
78
|
}
|
|
48
79
|
export const jsxs = jsx;
|
|
49
|
-
//
|
|
80
|
+
// HTML Rendering
|
|
50
81
|
const VOID_ELEMENTS = new Set([
|
|
51
82
|
"area", "base", "br", "col", "embed", "hr", "img", "input",
|
|
52
83
|
"link", "meta", "param", "source", "track", "wbr",
|
|
@@ -114,7 +145,7 @@ function renderElement(el) {
|
|
|
114
145
|
const inner = children.map(renderNode).join("");
|
|
115
146
|
return `<${tag}${attrs}>${inner}</${tag}>`;
|
|
116
147
|
}
|
|
117
|
-
//
|
|
148
|
+
// Streaming SSR via Suspense
|
|
118
149
|
// Use globalThis for boundary counter so it's shared between the unbundled
|
|
119
150
|
// server-renderer and esbuild-bundled page components (each gets its own copy).
|
|
120
151
|
export function setStreamingResolved(v) {
|
|
@@ -144,24 +175,24 @@ export function Suspense(props) {
|
|
|
144
175
|
return raw(`<span data-suspense="${id}">${fallback}</span>` +
|
|
145
176
|
`<template data-suspense="${id}">${inner}</template>`);
|
|
146
177
|
}
|
|
147
|
-
//
|
|
148
|
-
// Head
|
|
178
|
+
// Built-in Components (server stubs)
|
|
179
|
+
// Head - renders children into the page head at build time.
|
|
149
180
|
// On the server, we just render children; the build pipeline extracts them.
|
|
150
181
|
export function Head(props) {
|
|
151
182
|
return props.children ?? "";
|
|
152
183
|
}
|
|
153
|
-
// Script
|
|
184
|
+
// Script - renders a <script> tag.
|
|
154
185
|
export function Script(props) {
|
|
155
186
|
if (props.src) {
|
|
156
187
|
return `<script src="${escapeHTML(props.src)}"></script>`;
|
|
157
188
|
}
|
|
158
189
|
return `<script>${props.children ?? ""}</script>`;
|
|
159
190
|
}
|
|
160
|
-
// Style
|
|
191
|
+
// Style - renders a <style> tag.
|
|
161
192
|
export function Style(props) {
|
|
162
193
|
return `<style>${props.children ?? ""}</style>`;
|
|
163
194
|
}
|
|
164
|
-
// Link
|
|
195
|
+
// Link - renders an <a> tag wired for SPA navigation (server renderer).
|
|
165
196
|
export function Link(props) {
|
|
166
197
|
const { href = "", prefetch, replace, scroll, children, ...rest } = props;
|
|
167
198
|
const attrs = [];
|
|
@@ -195,7 +226,7 @@ export function Link(props) {
|
|
|
195
226
|
const inner = children != null ? renderNode(children) : "";
|
|
196
227
|
return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
|
|
197
228
|
}
|
|
198
|
-
// Image
|
|
229
|
+
// Image - renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
|
|
199
230
|
export function Image(props) {
|
|
200
231
|
const { src = "", alt = "", width, height, ...rest } = props;
|
|
201
232
|
const attrs = [];
|
|
@@ -209,11 +240,11 @@ export function Image(props) {
|
|
|
209
240
|
attrs.push(`height="${height}"`);
|
|
210
241
|
return raw(`<img ${attrs.join(" ")} />`);
|
|
211
242
|
}
|
|
212
|
-
// Icon
|
|
243
|
+
// Icon - renders an empty span placeholder (Go compiler handles SVG fetching at build time).
|
|
213
244
|
export function Icon(_props) {
|
|
214
245
|
return raw("<span></span>");
|
|
215
246
|
}
|
|
216
|
-
// SyntaxHighlight
|
|
247
|
+
// SyntaxHighlight - renders a <pre><code> block (Go compiler handles chroma highlighting at build time).
|
|
217
248
|
export function SyntaxHighlight(props) {
|
|
218
249
|
const lang = props.lang || "";
|
|
219
250
|
const code = props.children != null ? String(props.children) : "";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { jsx, renderToString, goComponent } from './server';
|
|
3
|
+
describe('renderToString', () => {
|
|
4
|
+
it('renders nested elements and escapes text', () => {
|
|
5
|
+
const node = jsx('div', { class: 'x', children: [jsx('span', { children: 'a & b' })] });
|
|
6
|
+
expect(renderToString(node)).toBe('<div class="x"><span>a & b</span></div>');
|
|
7
|
+
});
|
|
8
|
+
it('renders void elements without a close tag', () => {
|
|
9
|
+
expect(renderToString(jsx('img', { src: '/x.png', alt: 'y' }))).toBe('<img src="/x.png" alt="y">');
|
|
10
|
+
});
|
|
11
|
+
it('invokes function components', () => {
|
|
12
|
+
const Comp = () => jsx('p', { children: 'hi' });
|
|
13
|
+
expect(renderToString(jsx(Comp, {}))).toBe('<p>hi</p>');
|
|
14
|
+
});
|
|
15
|
+
it('drops event and internal props', () => {
|
|
16
|
+
const node = jsx('button', { onClick: () => undefined, children: 'x' });
|
|
17
|
+
expect(renderToString(node)).toBe('<button>x</button>');
|
|
18
|
+
});
|
|
19
|
+
it('omits null/false-valued attributes', () => {
|
|
20
|
+
expect(renderToString(jsx('input', { disabled: false, value: null }))).toBe('<input>');
|
|
21
|
+
expect(renderToString(jsx('input', { disabled: true }))).toBe('<input disabled>');
|
|
22
|
+
});
|
|
23
|
+
it('passes raw HTML through without escaping', () => {
|
|
24
|
+
expect(renderToString({ __raw: '<b>hi</b>' })).toBe('<b>hi</b>');
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
describe('goComponent', () => {
|
|
28
|
+
it('inlines baked HTML for an annotated server-tier call site', () => {
|
|
29
|
+
const baked = { 'gc3_5_Badge': '<span class="badge">Hi</span>' };
|
|
30
|
+
const node = goComponent('Badge', 'server', baked, { __krateGoId: 'gc3_5_Badge', label: 'Hi' });
|
|
31
|
+
expect(renderToString(node)).toBe('<span class="badge">Hi</span>');
|
|
32
|
+
});
|
|
33
|
+
it('emits a marker for runtime-tier calls, encoding props + children', () => {
|
|
34
|
+
const node = goComponent('Clock', 'runtime', null, { zone: 'UTC', children: ['a ', jsx('b', { children: 'c' })] }, 45);
|
|
35
|
+
const html = renderToString(node);
|
|
36
|
+
const m = html.match(/^<!--krate-go:Clock:(\d+):([A-Za-z0-9_-]+)-->$/);
|
|
37
|
+
expect(m).not.toBeNull();
|
|
38
|
+
expect(m[1]).toBe('45');
|
|
39
|
+
const b64 = m[2].replace(/-/g, '+').replace(/_/g, '/');
|
|
40
|
+
const payload = JSON.parse(Buffer.from(b64, 'base64').toString('utf8'));
|
|
41
|
+
expect(payload.zone).toBe('UTC');
|
|
42
|
+
expect(payload.children).toBe('a <b>c</b>');
|
|
43
|
+
});
|
|
44
|
+
it('falls back to a marker when a server call site is not in the baked map', () => {
|
|
45
|
+
const node = goComponent('Badge', 'server', {}, { __krateGoId: 'missing', label: 'Hi' });
|
|
46
|
+
expect(renderToString(node)).toMatch(/^<!--krate-go:Badge:0:/);
|
|
47
|
+
});
|
|
48
|
+
});
|
package/dist/signal.d.ts
CHANGED
|
@@ -42,7 +42,7 @@ export interface CSSPrimitiveOptions<T extends string | number> extends CSSARIAO
|
|
|
42
42
|
* every `createCSSChoice` declaration at build time into hidden radio inputs +
|
|
43
43
|
* `:has()` CSS, so it is **never** emitted to the client at runtime. Reading the
|
|
44
44
|
* getter as JSX text (`{tab()}`) compiles to a live value driven by the
|
|
45
|
-
* inherited `--krate-current` custom property
|
|
45
|
+
* inherited `--krate-current` custom property - still zero JS. Custom `vars`
|
|
46
46
|
* publish more inheritable properties for computed text/themes.
|
|
47
47
|
*
|
|
48
48
|
* If a component cannot be compiled to CSS the build does not fall back; it
|
|
@@ -53,7 +53,7 @@ export interface CSSPrimitiveOptions<T extends string | number> extends CSSARIAO
|
|
|
53
53
|
* (`{ options, as, aria, vars, label }`). When omitted, the compiler infers
|
|
54
54
|
* options from every literal the setter is called with.
|
|
55
55
|
*/
|
|
56
|
-
export declare function createCSSChoice<T extends string | number>(initial: T, _options?: readonly T[] | CSSPrimitiveOptions<T>):
|
|
56
|
+
export declare function createCSSChoice<T extends string | number>(initial: T, _options?: readonly T[] | CSSPrimitiveOptions<T>): CSSScope<T>;
|
|
57
57
|
/**
|
|
58
58
|
* Zero-JS boolean state (a single checkbox). Compiler-erased like
|
|
59
59
|
* `createCSSChoice`; the runtime body only exists so type-checking and any
|
|
@@ -65,23 +65,31 @@ export declare function createCSSToggle(initial: boolean, _options?: CSSARIAOpti
|
|
|
65
65
|
on?: string;
|
|
66
66
|
off?: string;
|
|
67
67
|
};
|
|
68
|
-
}):
|
|
68
|
+
}): CSSScope<boolean>;
|
|
69
69
|
/**
|
|
70
70
|
* Zero-JS independent boolean flags (`createCSSFlags(['a','b'])`). Returns a
|
|
71
71
|
* getter object keyed by flag name plus a setter. Compiler-erased like
|
|
72
72
|
* `createCSSChoice`.
|
|
73
73
|
*/
|
|
74
|
+
export type CSSFlagsScope<K extends string> = [
|
|
75
|
+
Record<K, () => boolean>,
|
|
76
|
+
(flag: K, value: boolean) => void
|
|
77
|
+
] & {
|
|
78
|
+
trigger: (flag: K) => Record<string, unknown>;
|
|
79
|
+
panel: (flag: K) => Record<string, unknown>;
|
|
80
|
+
close: () => Record<string, unknown>;
|
|
81
|
+
};
|
|
74
82
|
export declare function createCSSFlags<K extends string>(flags: readonly K[], _options?: CSSARIAOptions & {
|
|
75
83
|
vars?: Record<string, Partial<Record<K, string>>>;
|
|
76
|
-
}):
|
|
84
|
+
}): CSSFlagsScope<K>;
|
|
77
85
|
/**
|
|
78
|
-
* Zero-JS optional radio group (`createCSSGroup`)
|
|
86
|
+
* Zero-JS optional radio group (`createCSSGroup`) - an accordion, disclosure,
|
|
79
87
|
* dialog, menu, or popover. `null` means "closed". Compiler-erased like the
|
|
80
88
|
* other CSS primitives; the runtime body is a type-checking shim only.
|
|
81
89
|
*/
|
|
82
|
-
export declare function createCSSGroup<T extends string | number>(initial: T | null, _options?: readonly T[] | CSSPrimitiveOptions<T>):
|
|
90
|
+
export declare function createCSSGroup<T extends string | number>(initial: T | null, _options?: readonly T[] | CSSPrimitiveOptions<T>): CSSScope<T | null>;
|
|
83
91
|
/**
|
|
84
|
-
* Zero-JS discrete range (`createCSSRange`)
|
|
92
|
+
* Zero-JS discrete range (`createCSSRange`) - a stepped slider, stepper, or
|
|
85
93
|
* progress indicator. Values are integers from `min` to `max` by `step`.
|
|
86
94
|
* Compiler-erased; the runtime body is a type-checking shim only.
|
|
87
95
|
*/
|
|
@@ -89,7 +97,33 @@ export declare function createCSSRange(initial: number, _options: CSSARIAOptions
|
|
|
89
97
|
min?: number;
|
|
90
98
|
max?: number;
|
|
91
99
|
step?: number;
|
|
92
|
-
}):
|
|
100
|
+
}): CSSScope<number>;
|
|
101
|
+
/**
|
|
102
|
+
* A first-class CSS-scope handle. It is the `[getter, setter]` tuple returned by
|
|
103
|
+
* the CSS primitives (so destructuring keeps working) with helpers that the Krate
|
|
104
|
+
* compiler expands inline, anywhere in any component:
|
|
105
|
+
*
|
|
106
|
+
* ```tsx
|
|
107
|
+
* const tab = createCSSChoice('a', ['a', 'b']);
|
|
108
|
+
* <button {...tab.trigger('a')}>A</button>
|
|
109
|
+
* <div {...tab.panel('a')}>Panel A</div>
|
|
110
|
+
* <button {...tab.close()}>Close</button>
|
|
111
|
+
* ```
|
|
112
|
+
*
|
|
113
|
+
* The helpers return a marker spread at runtime; the compiler rewrites them to
|
|
114
|
+
* the `<label for>` / `:has()`-toggled wrapper markup. A handle is a plain
|
|
115
|
+
* value, so it can be passed to child components as a prop.
|
|
116
|
+
*/
|
|
117
|
+
export type CSSScope<T> = [() => T, (next: T) => void] & {
|
|
118
|
+
/** Spread on the trigger element; selects `value`. */
|
|
119
|
+
trigger: (value?: T) => Record<string, unknown>;
|
|
120
|
+
/** Spread on a panel element; shows it when `value` is selected. */
|
|
121
|
+
panel: (value?: T) => Record<string, unknown>;
|
|
122
|
+
/** Spread on an element that closes the scope (groups/dialogs/popovers). */
|
|
123
|
+
close: () => Record<string, unknown>;
|
|
124
|
+
/** The current selected value (live, via `--krate-current`). */
|
|
125
|
+
current: () => T;
|
|
126
|
+
};
|
|
93
127
|
/** Actions destructured from a `createCSSStack` result. */
|
|
94
128
|
export interface CSSStackActions<K extends string> {
|
|
95
129
|
push: (node: K) => void;
|
|
@@ -97,7 +131,7 @@ export interface CSSStackActions<K extends string> {
|
|
|
97
131
|
clear: () => void;
|
|
98
132
|
}
|
|
99
133
|
/**
|
|
100
|
-
* Zero-JS navigation stack (`createCSSStack`)
|
|
134
|
+
* Zero-JS navigation stack (`createCSSStack`) - a declared tree of nested
|
|
101
135
|
* panels for drill-down menus and multi-level drawers. The compiler infers the
|
|
102
136
|
* tree from where each literal `push('node')` appears; `top()` reads the
|
|
103
137
|
* deepest open node. Compiler-erased; the runtime body is a shim only.
|
|
@@ -113,7 +147,7 @@ export declare function onMount(fn: () => void): void;
|
|
|
113
147
|
export declare function createMemo<T>(fn: () => T): () => T;
|
|
114
148
|
/**
|
|
115
149
|
* Reducer state primitive: a `createSignal` whose setter applies a reducer.
|
|
116
|
-
* Returns `[getter, dispatch]`
|
|
150
|
+
* Returns `[getter, dispatch]` - the getter contract matches `createSignal`, so
|
|
117
151
|
* compiler slot bindings read it as `getter()` and hydration treats it like any
|
|
118
152
|
* other signal. Used both directly and as the lowering target for React's
|
|
119
153
|
* `useReducer`.
|
package/dist/signal.js
CHANGED
|
@@ -57,7 +57,7 @@ export function disposeAll() {
|
|
|
57
57
|
* every `createCSSChoice` declaration at build time into hidden radio inputs +
|
|
58
58
|
* `:has()` CSS, so it is **never** emitted to the client at runtime. Reading the
|
|
59
59
|
* getter as JSX text (`{tab()}`) compiles to a live value driven by the
|
|
60
|
-
* inherited `--krate-current` custom property
|
|
60
|
+
* inherited `--krate-current` custom property - still zero JS. Custom `vars`
|
|
61
61
|
* publish more inheritable properties for computed text/themes.
|
|
62
62
|
*
|
|
63
63
|
* If a component cannot be compiled to CSS the build does not fall back; it
|
|
@@ -69,7 +69,7 @@ export function disposeAll() {
|
|
|
69
69
|
* options from every literal the setter is called with.
|
|
70
70
|
*/
|
|
71
71
|
export function createCSSChoice(initial, _options) {
|
|
72
|
-
return createSignal(initial);
|
|
72
|
+
return withScopeHelpers(createSignal(initial));
|
|
73
73
|
}
|
|
74
74
|
/**
|
|
75
75
|
* Zero-JS boolean state (a single checkbox). Compiler-erased like
|
|
@@ -78,13 +78,8 @@ export function createCSSChoice(initial, _options) {
|
|
|
78
78
|
* `--krate-current` property ("on"/"off").
|
|
79
79
|
*/
|
|
80
80
|
export function createCSSToggle(initial, _options) {
|
|
81
|
-
return createSignal(initial);
|
|
81
|
+
return withScopeHelpers(createSignal(initial));
|
|
82
82
|
}
|
|
83
|
-
/**
|
|
84
|
-
* Zero-JS independent boolean flags (`createCSSFlags(['a','b'])`). Returns a
|
|
85
|
-
* getter object keyed by flag name plus a setter. Compiler-erased like
|
|
86
|
-
* `createCSSChoice`.
|
|
87
|
-
*/
|
|
88
83
|
export function createCSSFlags(flags, _options) {
|
|
89
84
|
const getters = {};
|
|
90
85
|
for (const flag of flags) {
|
|
@@ -94,26 +89,38 @@ export function createCSSFlags(flags, _options) {
|
|
|
94
89
|
// No-op: the compiler compiles flags to checkboxes, so this body is only a
|
|
95
90
|
// type-checking/server-evaluation shim.
|
|
96
91
|
const set = (_flag, _value) => { };
|
|
97
|
-
|
|
92
|
+
const scope = [getters, set];
|
|
93
|
+
scope.trigger = (flag) => ({ 'data-krate-scope': 'trigger', value: flag });
|
|
94
|
+
scope.panel = (flag) => ({ 'data-krate-scope': 'panel', value: flag });
|
|
95
|
+
scope.close = () => ({ 'data-krate-scope': 'close' });
|
|
96
|
+
return scope;
|
|
98
97
|
}
|
|
99
98
|
/**
|
|
100
|
-
* Zero-JS optional radio group (`createCSSGroup`)
|
|
99
|
+
* Zero-JS optional radio group (`createCSSGroup`) - an accordion, disclosure,
|
|
101
100
|
* dialog, menu, or popover. `null` means "closed". Compiler-erased like the
|
|
102
101
|
* other CSS primitives; the runtime body is a type-checking shim only.
|
|
103
102
|
*/
|
|
104
103
|
export function createCSSGroup(initial, _options) {
|
|
105
|
-
return createSignal(initial);
|
|
104
|
+
return withScopeHelpers(createSignal(initial));
|
|
106
105
|
}
|
|
107
106
|
/**
|
|
108
|
-
* Zero-JS discrete range (`createCSSRange`)
|
|
107
|
+
* Zero-JS discrete range (`createCSSRange`) - a stepped slider, stepper, or
|
|
109
108
|
* progress indicator. Values are integers from `min` to `max` by `step`.
|
|
110
109
|
* Compiler-erased; the runtime body is a type-checking shim only.
|
|
111
110
|
*/
|
|
112
111
|
export function createCSSRange(initial, _options) {
|
|
113
|
-
return createSignal(initial);
|
|
112
|
+
return withScopeHelpers(createSignal(initial));
|
|
113
|
+
}
|
|
114
|
+
function withScopeHelpers(result) {
|
|
115
|
+
const scope = result;
|
|
116
|
+
scope.trigger = (value) => ({ 'data-krate-scope': 'trigger', value });
|
|
117
|
+
scope.panel = (value) => ({ 'data-krate-scope': 'panel', value });
|
|
118
|
+
scope.close = () => ({ 'data-krate-scope': 'close' });
|
|
119
|
+
scope.current = () => result[0]();
|
|
120
|
+
return scope;
|
|
114
121
|
}
|
|
115
122
|
/**
|
|
116
|
-
* Zero-JS navigation stack (`createCSSStack`)
|
|
123
|
+
* Zero-JS navigation stack (`createCSSStack`) - a declared tree of nested
|
|
117
124
|
* panels for drill-down menus and multi-level drawers. The compiler infers the
|
|
118
125
|
* tree from where each literal `push('node')` appears; `top()` reads the
|
|
119
126
|
* deepest open node. Compiler-erased; the runtime body is a shim only.
|
|
@@ -314,7 +321,7 @@ export function createMemo(fn) {
|
|
|
314
321
|
}
|
|
315
322
|
/**
|
|
316
323
|
* Reducer state primitive: a `createSignal` whose setter applies a reducer.
|
|
317
|
-
* Returns `[getter, dispatch]`
|
|
324
|
+
* Returns `[getter, dispatch]` - the getter contract matches `createSignal`, so
|
|
318
325
|
* compiler slot bindings read it as `getter()` and hydration treats it like any
|
|
319
326
|
* other signal. Used both directly and as the lowering target for React's
|
|
320
327
|
* `useReducer`.
|