@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -115,12 +115,10 @@ export function decodeHtmlEntities(str: string): string {
115
115
  })
116
116
  }
117
117
 
118
- export function formatLoc(filename: string, code: string, offset?: number): string {
119
- if (offset === undefined || offset < 0)
120
- return filename
118
+ export function offsetToLineCol(code: string, offset: number): { line: number, col: number } {
121
119
  let line = 1
122
120
  let col = 1
123
- const end = Math.min(offset, code.length)
121
+ const end = Math.min(Math.max(0, offset), code.length)
124
122
  for (let i = 0; i < end; i++) {
125
123
  if (code.charCodeAt(i) === 10) {
126
124
  line++
@@ -130,9 +128,48 @@ export function formatLoc(filename: string, code: string, offset?: number): stri
130
128
  col++
131
129
  }
132
130
  }
131
+ return { line, col }
132
+ }
133
+
134
+ export function formatLoc(filename: string, code: string, offset?: number): string {
135
+ if (offset === undefined || offset < 0)
136
+ return filename
137
+ const { line, col } = offsetToLineCol(code, offset)
133
138
  return `${filename}:${line}:${col}`
134
139
  }
135
140
 
141
+ /** Renders a short source code frame around `offset` with 1 context line before/after and a caret underline. */
142
+ export function formatCodeFrame(code: string, offset: number, endOffset?: number): string {
143
+ if (code.length === 0)
144
+ return ''
145
+ const clamped = Math.min(Math.max(0, offset), code.length)
146
+ const { line, col } = offsetToLineCol(code, clamped)
147
+ const lines = code.split(/\r?\n/)
148
+ const lineIdx = Math.min(line - 1, lines.length - 1)
149
+ const startIdx = Math.max(0, lineIdx - 1)
150
+ const endIdx = Math.min(lines.length - 1, lineIdx + 1)
151
+ const gutterWidth = String(endIdx + 1).length
152
+ const pad = (n: number | '') => String(n).padStart(gutterWidth, ' ')
153
+ const targetLine = lines[lineIdx] ?? ''
154
+ const maxSpan = Math.max(1, targetLine.length - (col - 1))
155
+ const rawSpan = endOffset !== undefined && endOffset > clamped ? endOffset - clamped : 1
156
+ const caretLen = Math.max(1, Math.min(rawSpan, maxSpan))
157
+ const out: string[] = []
158
+ for (let i = startIdx; i <= endIdx; i++) {
159
+ const text = lines[i] ?? ''
160
+ out.push(` ${pad(i + 1)} | ${text}`)
161
+ if (i === lineIdx)
162
+ out.push(` ${pad('')} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(caretLen)}`)
163
+ }
164
+ return out.join('\n')
165
+ }
166
+
167
+ export const DIAGNOSTIC_PREFIX_RE = /^.+:\d+:\d+:\s+(?:error|warning):/
168
+
169
+ export function formatDiagnostic(loc: string, message: string, severity: 'error' | 'warning' = 'error'): string {
170
+ return `${loc}: ${severity}: ${message}`
171
+ }
172
+
136
173
  export function cleanJsxText(raw: string): string {
137
174
  if (!LINE_BREAK_RE.test(raw))
138
175
  return raw
@@ -205,8 +242,12 @@ export function isJsxNode(node: Node | null | undefined): node is JSXElement | J
205
242
  return node?.type === 'JSXElement' || node?.type === 'JSXFragment'
206
243
  }
207
244
 
208
- /** Whether JSX appears anywhere inside `node`, itself included. */
209
- export function containsJsx(node: Node | null | undefined): boolean {
245
+ /** Whether JSX appears anywhere inside `node`, itself included. Uses O(1) lookup when precomputed `jsxNodes` is passed. */
246
+ export function containsJsx(node: Node | null | undefined, jsxNodes?: WeakSet<Node>): boolean {
247
+ if (node === null || node === undefined)
248
+ return false
249
+ if (jsxNodes !== undefined)
250
+ return jsxNodes.has(node)
210
251
  let found = false
211
252
  walk(node, (child) => {
212
253
  if (found)
@@ -219,7 +260,9 @@ export function containsJsx(node: Node | null | undefined): boolean {
219
260
  }
220
261
 
221
262
  /** Whether a BlockStatement directly returns JSX (ignoring nested functions). */
222
- export function blockReturnsJsx(block: BlockStatement): boolean {
263
+ export function blockReturnsJsx(block: BlockStatement, jsxNodes?: WeakSet<Node>): boolean {
264
+ if (jsxNodes !== undefined && !jsxNodes.has(block))
265
+ return false
223
266
  let found = false
224
267
  walk(block, (child) => {
225
268
  if (found)
@@ -231,7 +274,7 @@ export function blockReturnsJsx(block: BlockStatement): boolean {
231
274
  )) {
232
275
  return false
233
276
  }
234
- if (child.type === 'ReturnStatement' && child.argument !== null && containsJsx(child.argument)) {
277
+ if (child.type === 'ReturnStatement' && child.argument !== null && containsJsx(child.argument, jsxNodes)) {
235
278
  found = true
236
279
  return false
237
280
  }
@@ -263,7 +306,7 @@ export interface MapCallMatch {
263
306
  }
264
307
 
265
308
  /** Recognizes `arr.map((item, idx?) => <jsx> | { ... return <jsx> })` identically in SSR and DOM compilers. */
266
- export function matchJsxMapCall(expr: Node): MapCallMatch | undefined {
309
+ export function matchJsxMapCall(expr: Node, jsxNodes?: WeakSet<Node>): MapCallMatch | undefined {
267
310
  if (
268
311
  expr.type !== 'CallExpression'
269
312
  || expr.callee.type !== 'MemberExpression'
@@ -285,7 +328,7 @@ export function matchJsxMapCall(expr: Node): MapCallMatch | undefined {
285
328
  const body = unwrapParens(arg.body)
286
329
  if (isJsxNode(body))
287
330
  return { call: expr, target: expr.callee.object, cb: arg, body, isJsxBody: true, params: arg.params }
288
- if (body.type === 'BlockStatement' && blockReturnsJsx(body))
331
+ if (body.type === 'BlockStatement' && blockReturnsJsx(body, jsxNodes))
289
332
  return { call: expr, target: expr.callee.object, cb: arg, body, isJsxBody: false, params: arg.params }
290
333
  return undefined
291
334
  }
@@ -313,7 +356,7 @@ export type ChildSlotKind =
313
356
  * Single shared child classifier for SSR & DOM codegen.
314
357
  * Both emitters derive exact hydration marker placement (`<!--k[-->...<!--k]-->` vs `<!---->`) from this classification.
315
358
  */
316
- export function classifyJsxChild(child: JSXChild): ChildSlotKind | undefined {
359
+ export function classifyJsxChild(child: JSXChild, jsxNodes?: WeakSet<Node>): ChildSlotKind | undefined {
317
360
  if (child.type === 'JSXText') {
318
361
  const text = cleanJsxText(child.value)
319
362
  return text === '' ? undefined : { kind: 'static-text', text, fromLiteral: false }
@@ -335,7 +378,7 @@ export function classifyJsxChild(child: JSXChild): ChildSlotKind | undefined {
335
378
  ? undefined
336
379
  : { kind: 'static-text', text: expr.value, fromLiteral: true }
337
380
  }
338
- const mapMatch = matchJsxMapCall(expr)
381
+ const mapMatch = matchJsxMapCall(expr, jsxNodes)
339
382
  if (mapMatch !== undefined)
340
383
  return { kind: 'loop', match: mapMatch }
341
384
  if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
@@ -433,10 +476,10 @@ export function mayReturnNode(node: Node): boolean {
433
476
  }
434
477
 
435
478
  /** Shared SSR/DOM check for whether a dynamic expression slot may produce DOM nodes/fragments (requiring balanced `<!--k[-->...<!--k]-->` markers). */
436
- export function isNodeCapableExpr(expr: Expression): boolean {
479
+ export function isNodeCapableExpr(expr: Expression, jsxNodes?: WeakSet<Node>): boolean {
437
480
  const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
438
481
  || (expr.type === 'MemberExpression' && !expr.computed && expr.property.type === 'Identifier' && expr.property.name === 'children')
439
- return isChildrenExpr || containsJsx(expr) || mayReturnNode(expr)
482
+ return isChildrenExpr || containsJsx(expr, jsxNodes) || mayReturnNode(expr)
440
483
  }
441
484
 
442
485
  export type { Program }
@@ -150,9 +150,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
150
150
 
151
151
  const islands = options.islands
152
152
  const emitMarkers = options.emitMarkers ?? options.isIsland ?? analysis.isInteractive
153
+ const jsxNodes = analysis.jsxNodes
153
154
 
154
155
  function compileSubExpression(node: Node): string {
155
- if (!containsJsx(node))
156
+ if (!containsJsx(node, jsxNodes))
156
157
  return code.slice(node.start, node.end)
157
158
 
158
159
  const sub = new SourceEditor(code.slice(node.start, node.end))
@@ -223,7 +224,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
223
224
  return { propEntries, allStaticProps, staticPropsObj, hydrateExpr, staticHydrate }
224
225
  }
225
226
 
226
- function compileChildrenListToStringExpr(children: readonly JSXChild[]): string {
227
+ function compileChildrenListToStringExpr(children: readonly JSXChild[], slotMarkers = emitMarkers): string {
227
228
  const bufVar = `_o${loopCounter++}`
228
229
  const stmts: string[] = []
229
230
  const parts = new StringParts()
@@ -233,7 +234,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
233
234
  parts.clear()
234
235
  }
235
236
  }
236
- emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s))
237
+ emitChildrenIntoBuffer(children, bufVar, parts, flush, s => stmts.push(s), undefined, slotMarkers)
237
238
  if (stmts.length === 0)
238
239
  return parts.toExpr()
239
240
  flush()
@@ -325,9 +326,10 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
325
326
  flushParts: () => void,
326
327
  pushStmt: (stmt: string) => void,
327
328
  rawTextTag?: 'style' | 'script',
329
+ slotMarkers = emitMarkers,
328
330
  ): void {
329
331
  const meaningful = filterMeaningfulChildren(children)
330
- const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c) })).filter(s => s.slot !== undefined)
332
+ const slots = meaningful.map(c => ({ child: c, slot: classifyJsxChild(c, jsxNodes) })).filter(s => s.slot !== undefined)
331
333
  const hasSiblings = slots.length > 1
332
334
  let hadVariableRange = false
333
335
 
@@ -365,7 +367,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
365
367
  }
366
368
 
367
369
  if (slot.kind === 'component' || slot.kind === 'fragment') {
368
- if (emitMarkers && hasSiblings) {
370
+ if (slotMarkers && hasSiblings) {
369
371
  parts.pushStatic('<!--k[-->')
370
372
  emitIntoBuffer(slot.node, bufVar, parts, flushParts, pushStmt)
371
373
  if (!isLast)
@@ -380,7 +382,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
380
382
 
381
383
  if (slot.kind === 'loop') {
382
384
  const { match } = slot
383
- const needsBracket = emitMarkers && (!isLast || hadVariableRange)
385
+ const needsBracket = slotMarkers && (!isLast || hadVariableRange)
384
386
  if (needsBracket)
385
387
  parts.pushStatic('<!--k[-->')
386
388
 
@@ -426,7 +428,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
426
428
  if (slot.kind === 'and-show') {
427
429
  const left = compileSubExpression(slot.expr.left)
428
430
  const right = compileJsxToStringExpr(slot.right)
429
- if (emitMarkers && hasSiblings) {
431
+ if (slotMarkers && hasSiblings) {
430
432
  parts.pushStatic('<!--k[-->')
431
433
  parts.pushExpr(`((${left}) ? (${right}) : "")`)
432
434
  parts.pushStatic('<!--k]-->')
@@ -442,7 +444,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
442
444
  const test = compileSubExpression(slot.expr.test)
443
445
  const cons = compileExpressionAsString(slot.cons)
444
446
  const alt = compileExpressionAsString(slot.alt)
445
- if (emitMarkers && hasSiblings) {
447
+ if (slotMarkers && hasSiblings) {
446
448
  parts.pushStatic('<!--k[-->')
447
449
  parts.pushExpr(`((${test}) ? (${cons}) : (${alt}))`)
448
450
  parts.pushStatic('<!--k]-->')
@@ -457,8 +459,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
457
459
  // Generic expression slot
458
460
  const exprCode = compileSubExpression(slot.expr)
459
461
  const rendered = `${use('esc')}(${exprCode})`
460
- if (isNodeCapableExpr(slot.expr)) {
461
- if (emitMarkers && hasSiblings) {
462
+ if (isNodeCapableExpr(slot.expr, jsxNodes)) {
463
+ if (slotMarkers && hasSiblings) {
462
464
  parts.pushStatic('<!--k[-->')
463
465
  parts.pushExpr(rendered)
464
466
  if (!isLast)
@@ -469,7 +471,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
469
471
  }
470
472
  hadVariableRange = true
471
473
  }
472
- else if (emitMarkers && hasSiblings) {
474
+ else if (slotMarkers && hasSiblings) {
473
475
  parts.pushStatic('<!---->')
474
476
  parts.pushExpr(rendered)
475
477
  if (!isLast)
@@ -532,7 +534,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
532
534
  }
533
535
 
534
536
  const childrenHaveAwait = hasChildren && childNodes.some(c => containsDirectAwait(c))
535
- const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes) : '""'
537
+ const childExpr = hasChildren ? compileChildrenListToStringExpr(childNodes, false) : '""'
536
538
 
537
539
  const islandInfo = islands?.get(tag)
538
540
  if (islandInfo === undefined && islands !== undefined && hydrateExpr !== undefined)
package/src/dev/index.ts CHANGED
@@ -2,12 +2,13 @@
2
2
  // SSE error push, and live config reload.
3
3
 
4
4
  import type { FSWatcher } from 'node:fs'
5
+ import type { BuildCacheStats } from '../build/graph'
5
6
  import type { KayApp } from '../server/index'
6
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
7
8
  import { dirname, join, relative, resolve } from 'node:path'
8
9
  import { clearBuildCache } from '../build/graph'
9
10
  import { build, createBuildCache } from '../build/index'
10
- import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
11
+ import { createAppContext, loadConfig, resolvePlugins, resolveServerConfig, runWithAppContext } from '../plugins/index'
11
12
  import { DEFAULT_MAX_REQUEST_BODY_SIZE } from '../server/http'
12
13
  import { createServer, withCspHashes } from '../server/index'
13
14
 
@@ -167,12 +168,19 @@ function createModuleStore(storeRoot: string) {
167
168
  }
168
169
  }
169
170
 
170
- export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
171
+ export async function devServer(options: DevServerOptions): Promise<{
172
+ url: string
173
+ stop: () => void
174
+ rebuild: () => Promise<void>
175
+ stats: () => BuildCacheStats
176
+ }> {
171
177
  const prevKayDev = process.env.KAY_DEV
172
178
  process.env.KAY_DEV = '1'
173
179
  const root = resolve(options.root)
174
180
  const devRoot = join(root, '.kay-dev')
181
+ let initialConfigFailed = false
175
182
  const initialCfg = await loadConfig(root).catch((err) => {
183
+ initialConfigFailed = true
176
184
  console.warn(`[kay dev] failed to load kay.config.ts: ${err instanceof Error ? err.message : String(err)}`)
177
185
  return {} as Awaited<ReturnType<typeof loadConfig>>
178
186
  })
@@ -188,15 +196,71 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
188
196
  const watchers: FSWatcher[] = []
189
197
  const watchedDirs = new Set<string>()
190
198
  const pluginWatchers: FSWatcher[] = []
199
+ const graphWatchers = new Map<string, FSWatcher>()
191
200
  let activeAssetPrefix = assetPrefix
201
+ let pluginWatchersAttached = false
202
+
203
+ const isInsideDir = (parent: string, target: string): boolean =>
204
+ target === parent || target.startsWith(`${parent}/`) || target.startsWith(`${parent}\\`)
205
+
206
+ function isCoveredByStaticWatchers(dir: string): boolean {
207
+ if (dir === root)
208
+ return false
209
+ for (const base of watchedDirs) {
210
+ if (isInsideDir(base, dir))
211
+ return true
212
+ }
213
+ return false
214
+ }
215
+
216
+ function syncBuildWatchers(watchedFiles: ReadonlySet<string>): void {
217
+ const nextDirs = new Set<string>()
218
+ let realRoot = root
219
+ try {
220
+ realRoot = realpathSync(root)
221
+ }
222
+ catch {}
223
+ for (const file of watchedFiles) {
224
+ if (file.includes('/node_modules/') || file.includes('\\node_modules\\'))
225
+ continue
226
+ if (isInsideDir(devRoot, file) || isInsideDir(join(root, '.kay-cache'), file))
227
+ continue
228
+ const dir = dirname(file)
229
+ // Root is already watched non-recursively for `kay.config.ts`; skip if it's only kay.config.ts itself.
230
+ if (dir === root || dir === realRoot) {
231
+ if (file === join(root, 'kay.config.ts') || file === join(realRoot, 'kay.config.ts'))
232
+ continue
233
+ }
234
+ if (isCoveredByStaticWatchers(dir))
235
+ continue
236
+ nextDirs.add(dir)
237
+ }
238
+ for (const [dir, watcher] of graphWatchers) {
239
+ if (!nextDirs.has(dir)) {
240
+ watcher.close()
241
+ graphWatchers.delete(dir)
242
+ }
243
+ }
244
+ for (const dir of nextDirs) {
245
+ if (graphWatchers.has(dir) || !existsSync(dir))
246
+ continue
247
+ try {
248
+ graphWatchers.set(dir, watch(dir, (_ev, filename) => {
249
+ const name = typeof filename === 'string' ? filename : ''
250
+ scheduleRebuild(srcChangeKind(name))
251
+ }))
252
+ }
253
+ catch {}
254
+ }
255
+ }
192
256
 
193
257
  function refreshPluginWatchers(cfg: Awaited<ReturnType<typeof loadConfig>>): void {
194
258
  for (const w of pluginWatchers)
195
259
  w.close()
196
260
  pluginWatchers.length = 0
197
261
  const seen = new Set<string>(watchedDirs)
198
- const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, dev: true })
199
- for (const plugin of cfg.plugins ?? []) {
262
+ const watchCtx = createAppContext({ root, outDir: devRoot, publicDir, assetPrefix: activeAssetPrefix, site: cfg.site, dev: true })
263
+ for (const plugin of resolvePlugins(cfg.plugins)) {
200
264
  const paths = runWithAppContext(watchCtx, () =>
201
265
  typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? []))
202
266
  for (const p of paths) {
@@ -274,6 +338,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
274
338
  const serverDir = join(root, outDir, 'server')
275
339
  const routeFiles = new Set(manifest.routes.map(r => r.file.replace(/^server\//, '')))
276
340
  const sharedRelFiles = new Set<string>()
341
+ if (manifest.configFile !== undefined)
342
+ sharedRelFiles.add(manifest.configFile.replace(/^server\//, ''))
277
343
  for (const a of manifest.actions) {
278
344
  const rel = a.file.replace(/^server\//, '')
279
345
  if (!routeFiles.has(rel))
@@ -294,8 +360,21 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
294
360
  }
295
361
  const prevApp = currentApp
296
362
  currentApp = nextApp
297
- void prevApp?.dispose?.()
363
+ await prevApp?.dispose?.()
298
364
  lastError = undefined
365
+ syncBuildWatchers(buildCache.watchedFiles)
366
+ if (!pluginWatchersAttached && !initialConfigFailed) {
367
+ pluginWatchersAttached = true
368
+ }
369
+ else if (initialConfigFailed) {
370
+ initialConfigFailed = false
371
+ try {
372
+ const recoveredCfg = await loadConfig(root)
373
+ refreshPluginWatchers(recoveredCfg)
374
+ pluginWatchersAttached = true
375
+ }
376
+ catch {}
377
+ }
299
378
  if (n > 2)
300
379
  rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
301
380
  console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
@@ -397,7 +476,8 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
397
476
  const pingChunk = encoder.encode(': ping\n\n')
398
477
  const pingInterval = setInterval(() => pushToClients(pingChunk), 15_000)
399
478
 
400
- const maxRequestBodySize = options.maxRequestBodySize ?? initialCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
479
+ const runtimeCfg = resolveServerConfig(initialCfg, { maxRequestBodySize: options.maxRequestBodySize })
480
+ const maxRequestBodySize = runtimeCfg.maxRequestBodySize ?? DEFAULT_MAX_REQUEST_BODY_SIZE
401
481
 
402
482
  const server = Bun.serve({
403
483
  port,
@@ -449,7 +529,7 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
449
529
  const ct = res.headers.get('content-type') ?? ''
450
530
  if (ct.includes('text/event-stream'))
451
531
  srv.timeout(request, 0)
452
- if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null) {
532
+ if (ct.includes('text/html') && request.method !== 'HEAD' && res.body !== null && !res.headers.has('content-encoding')) {
453
533
  const headers = new Headers(res.headers)
454
534
  headers.delete('content-length')
455
535
  const existingCsp = headers.get('content-security-policy')
@@ -471,6 +551,9 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
471
551
  pendingCssOnly = false
472
552
  return drainRebuilds()
473
553
  },
554
+ stats() {
555
+ return { ...buildCache.stats }
556
+ },
474
557
  stop() {
475
558
  stopped = true
476
559
  clearTimeout(timer)
@@ -479,6 +562,9 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
479
562
  w.close()
480
563
  for (const w of pluginWatchers)
481
564
  w.close()
565
+ for (const w of graphWatchers.values())
566
+ w.close()
567
+ graphWatchers.clear()
482
568
  server.stop(true)
483
569
  void currentApp?.dispose?.()
484
570
  rmSync(devRoot, { recursive: true, force: true })
package/src/dom/action.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  // Tiny client-side action stub (~300 B gzip, 0 B when no island imports an action).
2
2
 
3
- import type { ActionResult } from '../server/action'
3
+ import type { ReadonlySignal } from '../reactivity/index'
4
+ import type { ActionResult, ServerAction } from '../server/action'
5
+ import { signal } from '../reactivity/index'
4
6
 
5
7
  export interface ClientAction<Input, Output> {
6
8
  /** A FormData input is sent as multipart, so it can carry files. */
@@ -9,6 +11,94 @@ export interface ClientAction<Input, Output> {
9
11
  toString(): string
10
12
  }
11
13
 
14
+ export interface UseActionOptions<Output> {
15
+ /** Reset the submitted `<form>` element after a successful submission (default: false). */
16
+ reset?: boolean | undefined
17
+ /** Called with the typed action `data` when the action succeeds (`res.ok === true`). */
18
+ onSuccess?: ((data: Output, form?: HTMLFormElement) => void | Promise<void>) | undefined
19
+ /** Called when the action fails (`res.ok === false`). */
20
+ onError?: ((result: Extract<ActionResult<Output>, { ok: false }>) => void) | undefined
21
+ }
22
+
23
+ export interface ActionForm<Input, Output> {
24
+ readonly pending: ReadonlySignal<boolean>
25
+ readonly error: ReadonlySignal<string>
26
+ readonly fieldErrors: ReadonlySignal<Record<string, string>>
27
+ readonly data: ReadonlySignal<Output | undefined>
28
+ /** Action URL for progressive `<form action={form.action} method="post">` (or pass the action directly). */
29
+ readonly action: string
30
+ /** Progressive `<form onSubmit={form.onSubmit}>` handler that submits `FormData` via fetch when JS is loaded. */
31
+ readonly onSubmit: (event: SubmitEvent & { currentTarget: HTMLFormElement }) => Promise<ActionResult<Output> | undefined>
32
+ /** Imperatively submit typed input or `FormData` while tracking `pending`, `error`, `fieldErrors`, and `data`. */
33
+ submit(input: Input | FormData, form?: HTMLFormElement): Promise<ActionResult<Output> | undefined>
34
+ /** Clears `error`, `fieldErrors`, and `data`. */
35
+ reset(): void
36
+ }
37
+
38
+ /** Reactive progressive-enhancement form controller for a Kay server `action()`. */
39
+ export function useAction<Input, Output>(
40
+ action: ClientAction<Input, Output> | ServerAction<Input, Output>,
41
+ options: UseActionOptions<Output> = {},
42
+ ): ActionForm<Input, Output> {
43
+ const pending = signal(false)
44
+ const error = signal('')
45
+ const fieldErrors = signal<Record<string, string>>({})
46
+ const data = signal<Output | undefined>(undefined)
47
+
48
+ const submit = async (input: Input | FormData, formEl?: HTMLFormElement): Promise<ActionResult<Output> | undefined> => {
49
+ if (pending.peek())
50
+ return undefined
51
+ pending.value = true
52
+ error.value = ''
53
+ fieldErrors.value = {}
54
+ try {
55
+ const res = await (action as ClientAction<Input, Output>)(input)
56
+ if (!res.ok) {
57
+ fieldErrors.value = res.fieldErrors ?? {}
58
+ error.value = res.error
59
+ options.onError?.(res)
60
+ return res
61
+ }
62
+ data.value = res.data
63
+ if (options.reset && formEl)
64
+ formEl.reset()
65
+ await options.onSuccess?.(res.data, formEl)
66
+ return res
67
+ }
68
+ catch (err) {
69
+ const msg = err instanceof Error ? err.message : String(err)
70
+ error.value = msg
71
+ const failed: Extract<ActionResult<Output>, { ok: false }> = { ok: false, status: 0, error: msg }
72
+ options.onError?.(failed)
73
+ return failed
74
+ }
75
+ finally {
76
+ pending.value = false
77
+ }
78
+ }
79
+
80
+ return {
81
+ pending,
82
+ error,
83
+ fieldErrors,
84
+ data,
85
+ get action() {
86
+ return action.url || String(action)
87
+ },
88
+ onSubmit(event) {
89
+ event.preventDefault()
90
+ const formEl = event.currentTarget
91
+ return submit(new FormData(formEl), formEl)
92
+ },
93
+ submit,
94
+ reset() {
95
+ error.value = ''
96
+ fieldErrors.value = {}
97
+ data.value = undefined
98
+ },
99
+ }
100
+ }
101
+
12
102
  export function actionStub<Input = unknown, Output = unknown>(url: string): ClientAction<Input, Output> {
13
103
  const call = (async (input: Input | FormData): Promise<ActionResult<Output>> => {
14
104
  const isForm = typeof FormData !== 'undefined' && input instanceof FormData
package/src/dom/index.ts CHANGED
@@ -341,7 +341,7 @@ export function setStyle(el: HTMLElement, value: unknown): void {
341
341
 
342
342
  // ---- Delegated events
343
343
 
344
- const delegated = new Set<string>()
344
+ const delegated = new WeakMap<Document, Set<string>>()
345
345
 
346
346
  function dispatchEvent(event: Event): void {
347
347
  const key = `$$${event.type}`
@@ -364,10 +364,15 @@ function dispatchEvent(event: Event): void {
364
364
  export function delegate(events: string[]): void {
365
365
  if (typeof document === 'undefined')
366
366
  return
367
+ let set = delegated.get(document)
368
+ if (set === undefined) {
369
+ set = new Set()
370
+ delegated.set(document, set)
371
+ }
367
372
  for (let i = 0; i < events.length; i++) {
368
373
  const type = events[i]!
369
- if (!delegated.has(type)) {
370
- delegated.add(type)
374
+ if (!set.has(type)) {
375
+ set.add(type)
371
376
  document.addEventListener(type, dispatchEvent)
372
377
  }
373
378
  }
package/src/index.ts CHANGED
@@ -15,7 +15,10 @@ export type { Owner, ReadonlySignal, Signal } from './reactivity/index'
15
15
  export { selector } from './reactivity/selector'
16
16
  export type { Selector } from './reactivity/selector'
17
17
  export { snapshot, store } from './reactivity/store'
18
+ export { useAction } from './dom/action'
19
+ export type { ActionForm, ClientAction, UseActionOptions } from './dom/action'
18
20
  export type { Component, Html, HydrateStrategy, KayChild } from './jsx-runtime'
21
+ export type { ExtractRouteParams, KayLocals, LayoutProps, LoaderData, LoaderFn, NotFoundResult, PageProps, RouteContext } from './server/index'
19
22
 
20
23
  import type { Component, HydrateStrategy } from './jsx-runtime'
21
24