@kayjs/kay 1.109.0 → 1.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/dist/eslint.js +488 -75
  2. package/editors/zed/extension.toml +2 -2
  3. package/llms/actions-from-islands.md +1 -1
  4. package/llms/build-and-start.md +1 -1
  5. package/llms/checks.md +1 -0
  6. package/llms/component-libraries.md +1 -1
  7. package/llms/components.md +1 -1
  8. package/llms/deprecated-lints.md +1 -1
  9. package/llms/dev-tool.md +1 -1
  10. package/llms/effects.md +1 -0
  11. package/llms/head.md +1 -1
  12. package/llms/images.md +2 -0
  13. package/llms/island-and-form-lints.md +2 -1
  14. package/llms/islands-lazy-components.md +23 -0
  15. package/llms/islands.md +4 -14
  16. package/llms/lints.md +1 -1
  17. package/llms/live-values.md +1 -1
  18. package/llms/navigation-from-code.md +1 -1
  19. package/llms/navigation.md +5 -3
  20. package/llms/performance-lints.md +1 -0
  21. package/llms/prerendering.md +1 -1
  22. package/llms/project-new-and-add.md +1 -1
  23. package/llms/project.md +1 -1
  24. package/llms/templates-elements-slots-snippets.md +4 -4
  25. package/llms/upgrading-archive.md +121 -42
  26. package/llms/upgrading.md +17 -133
  27. package/llms/whats-new-archive.md +31 -31
  28. package/llms/whats-new.md +45 -30
  29. package/llms.txt +3 -2
  30. package/package.json +11 -11
  31. package/src/build/client.ts +10 -8
  32. package/src/build/island-images.ts +277 -0
  33. package/src/build/pipeline.ts +10 -4
  34. package/src/build/static.ts +99 -24
  35. package/src/build/variants.ts +132 -18
  36. package/src/check/env-types.ts +1 -1
  37. package/src/check/project.ts +4 -0
  38. package/src/check/schema-builders.ts +230 -26
  39. package/src/check/shadow-types.ts +3 -3
  40. package/src/commands/upgrade.ts +2 -1
  41. package/src/compiler/allow-comments.ts +38 -2
  42. package/src/compiler/ast.ts +4 -4
  43. package/src/compiler/codegen.ts +4 -4
  44. package/src/compiler/deprecated-lints-1-106.ts +2 -2
  45. package/src/compiler/dom.ts +4 -3
  46. package/src/compiler/hand-parts.ts +36 -8
  47. package/src/compiler/handed-data.ts +15 -0
  48. package/src/compiler/helper-imports.ts +2 -2
  49. package/src/compiler/html.ts +3 -7
  50. package/src/compiler/index.ts +7 -4
  51. package/src/compiler/island-arguments.ts +9 -0
  52. package/src/compiler/island-lints.ts +7 -0
  53. package/src/compiler/items.ts +174 -0
  54. package/src/compiler/jsx.ts +10 -11
  55. package/src/compiler/kay-exports.ts +1 -0
  56. package/src/compiler/lints.ts +6 -7
  57. package/src/compiler/markup.ts +26 -24
  58. package/src/compiler/names.ts +1 -1
  59. package/src/compiler/removed-lints.ts +90 -0
  60. package/src/compiler/rewrite-types.ts +2 -0
  61. package/src/compiler/rewrite.ts +4 -2
  62. package/src/compiler/route-lints.ts +8 -0
  63. package/src/compiler/signal-from-prop.ts +141 -0
  64. package/src/compiler/template-reads.ts +16 -0
  65. package/src/compiler/template-walk.ts +2 -1
  66. package/src/config-shape.ts +4 -1
  67. package/src/config.ts +2 -2
  68. package/src/new.ts +16 -4
  69. package/src/project.ts +3 -3
  70. package/src/runtime/await.server.ts +4 -2
  71. package/src/runtime/checks.ts +14 -2
  72. package/src/runtime/client.ts +5 -9
  73. package/src/runtime/dev-tab-env.ts +28 -3
  74. package/src/runtime/dom-loop.ts +2 -4
  75. package/src/runtime/dom.ts +2 -2
  76. package/src/runtime/html.ts +53 -7
  77. package/src/runtime/image.ts +24 -23
  78. package/src/runtime/index.ts +2 -2
  79. package/src/runtime/island.server.ts +41 -11
  80. package/src/runtime/navigate.ts +14 -0
  81. package/src/runtime/navigation.ts +9 -1
  82. package/src/runtime/page-swap.ts +6 -3
  83. package/src/runtime/reactive.ts +72 -0
  84. package/src/runtime/row-key.ts +4 -0
  85. package/src/runtime/swap-flight.ts +10 -10
  86. package/src/runtime/swap-focus.ts +56 -9
  87. package/src/runtime/swap-kept.ts +97 -29
  88. package/src/runtime/swap-morph.ts +49 -9
  89. package/src/runtime/text-hash.ts +17 -0
  90. package/src/runtime/uid.server.ts +6 -4
  91. package/src/runtime/values.ts +12 -0
  92. package/src/server/client.ts +3 -0
  93. package/src/server/dev.ts +2 -0
  94. package/src/server/image.ts +1 -1
  95. package/src/server/kept-exports.ts +1 -0
  96. package/src/server/render-document.ts +11 -8
  97. package/src/server/render.ts +3 -3
  98. package/types/build/client.d.ts +6 -0
  99. package/types/build/client.d.ts.map +1 -1
  100. package/types/build/island-images.d.ts +45 -0
  101. package/types/build/island-images.d.ts.map +1 -0
  102. package/types/build/pipeline.d.ts.map +1 -1
  103. package/types/build/static.d.ts.map +1 -1
  104. package/types/build/variants.d.ts +9 -1
  105. package/types/build/variants.d.ts.map +1 -1
  106. package/types/check/project.d.ts.map +1 -1
  107. package/types/check/schema-builders.d.ts.map +1 -1
  108. package/types/commands/upgrade.d.ts.map +1 -1
  109. package/types/compiler/allow-comments.d.ts +2 -0
  110. package/types/compiler/allow-comments.d.ts.map +1 -1
  111. package/types/compiler/ast.d.ts +1 -1
  112. package/types/compiler/ast.d.ts.map +1 -1
  113. package/types/compiler/deprecated-lints-1-106.d.ts +2 -2
  114. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
  115. package/types/compiler/deprecated-lints.d.ts +2 -2
  116. package/types/compiler/dom.d.ts.map +1 -1
  117. package/types/compiler/hand-parts.d.ts +6 -3
  118. package/types/compiler/hand-parts.d.ts.map +1 -1
  119. package/types/compiler/handed-data.d.ts +5 -0
  120. package/types/compiler/handed-data.d.ts.map +1 -0
  121. package/types/compiler/html.d.ts.map +1 -1
  122. package/types/compiler/index.d.ts.map +1 -1
  123. package/types/compiler/island-arguments.d.ts +5 -0
  124. package/types/compiler/island-arguments.d.ts.map +1 -1
  125. package/types/compiler/island-lints.d.ts +7 -0
  126. package/types/compiler/island-lints.d.ts.map +1 -1
  127. package/types/compiler/items.d.ts +14 -0
  128. package/types/compiler/items.d.ts.map +1 -1
  129. package/types/compiler/jsx.d.ts.map +1 -1
  130. package/types/compiler/kay-exports.d.ts.map +1 -1
  131. package/types/compiler/lints.d.ts +20 -5
  132. package/types/compiler/lints.d.ts.map +1 -1
  133. package/types/compiler/markup.d.ts +3 -1
  134. package/types/compiler/markup.d.ts.map +1 -1
  135. package/types/compiler/names.d.ts.map +1 -1
  136. package/types/compiler/removed-lints.d.ts +3 -0
  137. package/types/compiler/removed-lints.d.ts.map +1 -0
  138. package/types/compiler/rewrite-types.d.ts +1 -0
  139. package/types/compiler/rewrite-types.d.ts.map +1 -1
  140. package/types/compiler/route-lints.d.ts +8 -0
  141. package/types/compiler/route-lints.d.ts.map +1 -1
  142. package/types/compiler/signal-from-prop.d.ts +4 -0
  143. package/types/compiler/signal-from-prop.d.ts.map +1 -0
  144. package/types/compiler/template-reads.d.ts +1 -0
  145. package/types/compiler/template-reads.d.ts.map +1 -1
  146. package/types/compiler/template-walk.d.ts.map +1 -1
  147. package/types/config-shape.d.ts.map +1 -1
  148. package/types/config.d.ts +3 -1
  149. package/types/config.d.ts.map +1 -1
  150. package/types/new.d.ts.map +1 -1
  151. package/types/project.d.ts +2 -2
  152. package/types/project.d.ts.map +1 -1
  153. package/types/runtime/await.server.d.ts.map +1 -1
  154. package/types/runtime/checks.d.ts +8 -2
  155. package/types/runtime/checks.d.ts.map +1 -1
  156. package/types/runtime/client.d.ts.map +1 -1
  157. package/types/runtime/dev-tab-env.d.ts.map +1 -1
  158. package/types/runtime/dom-loop.d.ts +2 -1
  159. package/types/runtime/dom-loop.d.ts.map +1 -1
  160. package/types/runtime/dom.d.ts +2 -2
  161. package/types/runtime/dom.d.ts.map +1 -1
  162. package/types/runtime/html.d.ts +6 -3
  163. package/types/runtime/html.d.ts.map +1 -1
  164. package/types/runtime/image.d.ts.map +1 -1
  165. package/types/runtime/index.d.ts +2 -2
  166. package/types/runtime/index.d.ts.map +1 -1
  167. package/types/runtime/island.server.d.ts +1 -0
  168. package/types/runtime/island.server.d.ts.map +1 -1
  169. package/types/runtime/navigate.d.ts.map +1 -1
  170. package/types/runtime/navigation.d.ts +4 -0
  171. package/types/runtime/navigation.d.ts.map +1 -1
  172. package/types/runtime/reactive.d.ts +5 -0
  173. package/types/runtime/reactive.d.ts.map +1 -1
  174. package/types/runtime/row-key.d.ts +2 -0
  175. package/types/runtime/row-key.d.ts.map +1 -0
  176. package/types/runtime/swap-flight.d.ts +1 -1
  177. package/types/runtime/swap-flight.d.ts.map +1 -1
  178. package/types/runtime/swap-focus.d.ts +2 -0
  179. package/types/runtime/swap-focus.d.ts.map +1 -1
  180. package/types/runtime/swap-kept.d.ts.map +1 -1
  181. package/types/runtime/swap-morph.d.ts.map +1 -1
  182. package/types/runtime/text-hash.d.ts +2 -0
  183. package/types/runtime/text-hash.d.ts.map +1 -0
  184. package/types/runtime/uid.server.d.ts.map +1 -1
  185. package/types/runtime/values.d.ts +4 -0
  186. package/types/runtime/values.d.ts.map +1 -1
  187. package/types/server/app-stages.d.ts +3 -1
  188. package/types/server/app-stages.d.ts.map +1 -1
  189. package/types/server/app.d.ts +3 -1
  190. package/types/server/app.d.ts.map +1 -1
  191. package/types/server/client.d.ts +2 -0
  192. package/types/server/client.d.ts.map +1 -1
  193. package/types/server/dev.d.ts +1 -0
  194. package/types/server/dev.d.ts.map +1 -1
  195. package/types/server/kept-exports.d.ts.map +1 -1
  196. package/types/server/render-document.d.ts +1 -1
  197. package/types/server/render-document.d.ts.map +1 -1
  198. package/types/server/render.d.ts +2 -2
  199. package/types/server/render.d.ts.map +1 -1
@@ -31,11 +31,12 @@ export { formKey } from './action'
31
31
  export { escape, escapeAttribute } from './escape'
32
32
  export { head } from './head'
33
33
  export { loadScope } from './load-scope'
34
- export { memo, untrack } from './reactive'
34
+ export { memo, param, untrack } from './reactive'
35
35
  export { html, isRendered } from './rendered'
36
-
37
36
  export type { Html } from './rendered'
38
- export { checkedMarkup, componentClass, handParts, merge, omit, partClass, partHanded, partsClass, spreadWith } from './values'
37
+
38
+ export { rowKey } from './row-key'
39
+ export { checkedMarkup, componentClass, handParts, merge, omit, partClass, partHanded, partProps, spreadWith } from './values'
39
40
 
40
41
  // Leads the markup of a `try` block the server rendered its `catch` block for.
41
42
  export const FAILED_MARKER = `<!--${FAILED}-->`
@@ -572,7 +573,7 @@ export function show<T>(value: T, render: (value: () => Truthy<T>) => string, fa
572
573
 
573
574
  // A `for`: each row's markup, or the fallback's when there is nothing to list.
574
575
  // In an island a row reads its item, and a keyed row its index, through functions, as the browser build of the same template does.
575
- export function loop<T>(each: Iterable<T> | null | undefined | false, render: (item: T | (() => T), index: number | (() => number)) => string, fallback?: () => string, accessors?: 'keyed' | 'positional'): string {
576
+ export function loop<T>(each: Iterable<T> | null | undefined | false, render: (item: T | (() => T), index: number | (() => number)) => string, fallback?: () => string, accessors?: 'keyed' | 'positional', key?: (item: T, index: number) => unknown): string {
576
577
  if (each == null || each === false)
577
578
  return fallback?.() ?? ''
578
579
 
@@ -584,16 +585,61 @@ export function loop<T>(each: Iterable<T> | null | undefined | false, render: (i
584
585
  return fieldMarks.marking === undefined ? markup : markedList(each, markup)
585
586
  }
586
587
 
587
- return fieldMarks.marking === undefined ? rows(list, render, accessors) : markedList(each, rows(list, render, accessors))
588
+ return fieldMarks.marking === undefined ? rows(list, render, accessors, key) : markedList(each, rows(list, render, accessors, key))
589
+ }
590
+
591
+ // The keys of the keyed loops being drawn, outermost first, where an island with no `key` or `id` of its own takes its identity from, so a swap pairs it with its own copy when a sibling row goes.
592
+ const loopKeys: (string | undefined)[] = []
593
+
594
+ export function loopIdentity(): string | undefined {
595
+ if (loopKeys.length === 0 || loopKeys.includes(undefined))
596
+ return undefined
597
+
598
+ return loopKeys.length === 1 ? loopKeys[0] : JSON.stringify(loopKeys)
599
+ }
600
+
601
+ // Renders again, later, with the keyed loops it is drawn in: an `await` block settles after its row was drawn, and an island in it still takes the row's key as its identity.
602
+ export function keepLoopKeys(): <T>(render: () => T) => T {
603
+ const kept = [...loopKeys]
604
+
605
+ return (render) => {
606
+ const outer = loopKeys.splice(0, loopKeys.length, ...kept)
607
+
608
+ try {
609
+ return render()
610
+ }
611
+ finally {
612
+ loopKeys.splice(0, loopKeys.length, ...outer)
613
+ }
614
+ }
615
+ }
616
+
617
+ function drawRow<T>(render: (item: T | (() => T), index: number | (() => number)) => string, accessors: 'keyed' | 'positional' | undefined, item: T, index: number): string {
618
+ return accessors === undefined ? render(item, index) : render(() => item, accessors === 'keyed' ? () => index : index)
588
619
  }
589
620
 
590
- function rows<T>(each: readonly T[], render: (item: T | (() => T), index: number | (() => number)) => string, accessors?: 'keyed' | 'positional'): string {
621
+ function rows<T>(each: readonly T[], render: (item: T | (() => T), index: number | (() => number)) => string, accessors?: 'keyed' | 'positional', key?: (item: T, index: number) => unknown): string {
591
622
  let markup = ''
592
623
 
593
624
  for (let index = 0; index < each.length; index++) {
594
625
  const item = each[index]!
595
626
 
596
- markup += accessors === undefined ? render(item, index) : render(() => item, accessors === 'keyed' ? () => index : index)
627
+ if (key === undefined) {
628
+ markup += drawRow(render, accessors, item, index)
629
+
630
+ continue
631
+ }
632
+
633
+ const value = key(item, index)
634
+
635
+ loopKeys.push(typeof value === 'string' || typeof value === 'number' ? String(value) : undefined)
636
+
637
+ try {
638
+ markup += drawRow(render, accessors, item, index)
639
+ }
640
+ finally {
641
+ loopKeys.pop()
642
+ }
597
643
  }
598
644
 
599
645
  return markup
@@ -1,7 +1,10 @@
1
1
  import { KayError } from './kay-error'
2
2
  import { kayLog } from './log'
3
+ import { textHash } from './text-hash'
3
4
 
4
5
  declare const KAY_BROWSER: true | undefined
6
+ declare const KAY_STATIC_EXPORT: true | undefined
7
+ declare const KAY_STATIC_REMOTE: readonly string[] | undefined
5
8
 
6
9
  // The widths an image is resized to unless `images.widths` says otherwise, the only ones the image route makes: a fixed ladder keeps how many files one image can turn into bounded.
7
10
  export const IMAGE_WIDTHS = [320, 640, 960, 1280, 1920, 2560] as const
@@ -94,7 +97,7 @@ const requestedRemote = new Map<string, Map<string, ImageVariant>>()
94
97
  let remoteListed: ((src: string) => boolean) | undefined
95
98
  // Whether it leaves out the host of an image on another host, which then keeps its own URL, set with it.
96
99
  let unlistedCheck: ((src: string, caller: string) => boolean) | undefined
97
- // Set on the server, which records the variants pages ask for and links the files a static export wrote: the browser asks the route.
100
+ // Set on the server, which records the variants pages ask for and links the files a static export wrote: the browser asks the route, except in a static export's bundle, which links the files itself (`exportedVariantUrl`).
98
101
  let serverVariantUrl: typeof recordedVariantUrl | undefined
99
102
  // Whether `images.resolve` looks sources up, which the browser reads off the page.
100
103
  let resolved: boolean | undefined
@@ -265,25 +268,7 @@ export function requestedRemoteVariants(): { src: string, name: string, variant:
265
268
 
266
269
  // Named after a hash of the URL.
267
270
  export function remoteVariantName(src: string, variant: ImageVariant): string {
268
- return `remote-${urlHash(src)}${variantSuffix(variant)}`
269
- }
270
-
271
- // cyrb53, 53 bits of a string's hash in base 36.
272
- function urlHash(text: string): string {
273
- let h1 = 0xDEADBEEF
274
- let h2 = 0x41C6CE57
275
-
276
- for (let index = 0; index < text.length; index++) {
277
- const code = text.charCodeAt(index)
278
-
279
- h1 = Math.imul(h1 ^ code, 2654435761)
280
- h2 = Math.imul(h2 ^ code, 1597334677)
281
- }
282
-
283
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
284
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
285
-
286
- return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
271
+ return `remote-${textHash(src)}${variantSuffix(variant)}`
287
272
  }
288
273
 
289
274
  function currentMaxDensity(): number {
@@ -568,7 +553,7 @@ export function imageUrl(src: string, width: number, aspect?: Aspect, quality?:
568
553
  function variantUrl(src: string, variant: ImageVariant): string {
569
554
  const query = variant === 'card' ? 'card' : `w=${variant.width}${variant.aspect ? `&crop=${aspectKey(variant.aspect)}` : ''}${variant.quality === undefined ? '' : `&q=${variant.quality}`}`
570
555
 
571
- return serverVariantUrl?.(src, variant) ?? `${IMAGE_ROUTE}?src=${encodeURIComponent(src)}&${query}`
556
+ return serverVariantUrl?.(src, variant) ?? (typeof KAY_STATIC_EXPORT === 'undefined' ? undefined : exportedVariantUrl(src, variant)) ?? `${IMAGE_ROUTE}?src=${encodeURIComponent(src)}&${query}`
572
557
  }
573
558
 
574
559
  // The file of a variant a static export wrote, recording the variants pages ask for beyond the ladder; nothing where the route serves it.
@@ -583,15 +568,31 @@ function recordedVariantUrl(src: string, variant: ImageVariant): string | undefi
583
568
  }
584
569
 
585
570
  if (src.startsWith(IMPORTED) && (asked || variantFiles)) {
586
- const name = decodeURIComponent(src.slice(IMPORTED.length).replace(QUERY, ''))
571
+ const name = importedName(src)
587
572
 
588
573
  // The ladder is written for every imported image, the rest only for those a page asks for.
589
574
  if (asked)
590
575
  requested.set(name, (requested.get(name) ?? new Map<string, ImageVariant>()).set(variantSuffix(variant), variant))
591
576
 
592
577
  if (variantFiles)
593
- return `${VARIANTS}${encodeURIComponent(`${name.replace(EXTENSION, '')}${variantSuffix(variant)}`)}`
578
+ return variantFile(name, variant)
594
579
  }
595
580
 
596
581
  return undefined
597
582
  }
583
+
584
+ function importedName(src: string): string {
585
+ return decodeURIComponent(src.slice(IMPORTED.length).replace(QUERY, ''))
586
+ }
587
+
588
+ function variantFile(name: string, variant: ImageVariant): string {
589
+ return `${VARIANTS}${encodeURIComponent(`${name.replace(EXTENSION, '')}${variantSuffix(variant)}`)}`
590
+ }
591
+
592
+ // In the browser of a static export, which has no route: the file the build wrote of an imported image, the one the server HTML links, and of a remote image whose URL the build fetched. Any other image keeps its own URL. Only the export's bundle holds it, a server-rendered app's does not.
593
+ function exportedVariantUrl(src: string, variant: ImageVariant): string | undefined {
594
+ if (src.startsWith(IMPORTED))
595
+ return variantFile(importedName(src), variant)
596
+
597
+ return REMOTE.test(src) && typeof KAY_STATIC_REMOTE !== 'undefined' && KAY_STATIC_REMOTE.includes(src) ? `${VARIANTS}${remoteVariantName(src, variant)}` : src
598
+ }
@@ -9,7 +9,7 @@ export { announce } from './announce'
9
9
  export type { ErrorShape } from './api-error'
10
10
  export { localPath, withBase } from './base'
11
11
  export { byteCount } from './byte-count'
12
- export type { ApiRoutesOf, AwaitProps, Bindable, BindableMark, BoundProp, BoundValue, CheckedComputedHtml, CheckedHref, CheckedHtml, Deferred, ExtensionServersOf, FunctionProp, HandedPart, HandedSignal, HandsPart, HydrateWhen, Inferred, IslandAsks, IslandBrand, IslandComponent, IslandOptions, IslandProp, Locals, LocalsOf, PartClass, PlainIslandProp, Redirect, Register, RouteParams, SafeHtml, ServerOfModule, SlotCall, TemplateHelpers, Truthy, UnkeyedRows, Unmatched, UnresolvedParameter } from './checks'
12
+ export type { ApiRoutesOf, AwaitProps, Bindable, BindableMark, BoundProp, BoundValue, CheckedComputedHtml, CheckedHref, CheckedHtml, Deferred, ExtensionServersOf, FunctionProp, HandedPart, HandedSignal, HandsPart, HydrateWhen, Inferred, IslandAsked, IslandAsks, IslandBrand, IslandComponent, IslandOptions, IslandProp, Locals, LocalsOf, PartClass, PlainIslandProp, Redirect, Register, RouteParams, SafeHtml, ServerOfModule, SlotCall, TemplateHelpers, Truthy, UnkeyedRows, Unmatched, UnresolvedParameter } from './checks'
13
13
  // The names `kay` exports. What this file defines itself is in `core.ts`, so a build imports the module holding a name rather than this one, which an entry importing it would take every name's module along with.
14
14
  export * from './core'
15
15
  export type { DescribeOptions } from './described'
@@ -61,7 +61,7 @@ export type { QueuedJob } from './queue-jobs'
61
61
  export { jobs } from './queue-jobs'
62
62
  export { randomId } from './random-id'
63
63
  export type { SignalOptions } from './reactive'
64
- export { batch, flush, memo, onCleanup, root, untrack } from './reactive'
64
+ export { batch, flush, followed, memo, onCleanup, root, untrack } from './reactive'
65
65
  export { reactiveMap, reactiveSet } from './reactive-collections'
66
66
  export type { Recipe, RecipeConfig, RecipeProps, WidenedProps } from './recipe'
67
67
  export { recipe } from './recipe'
@@ -9,7 +9,7 @@ import { BUTTON_FORM_KEY } from './button-form'
9
9
  import { escapeAttribute, quotedAttribute } from './escape'
10
10
  import { withFieldMarks } from './fields'
11
11
  import { headMark, setsIslandTitle } from './head'
12
- import { child, omit, prerendering } from './html'
12
+ import { child, loopIdentity, omit, prerendering } from './html'
13
13
  import { noteLives } from './live-value'
14
14
  import { localeState } from './locale-state'
15
15
  import { TITLED_ATTRIBUTE } from './markers'
@@ -22,6 +22,23 @@ import { ACTION_PREFIX, encodeValue, unsendable } from './wire'
22
22
 
23
23
  // Island roots render synchronously, so a counter is enough to tell whether a component already sits inside one.
24
24
  let depth = 0
25
+ // The layout file whose own markup is rendering, none inside the page or a block it fills: the islands it draws are marked with it, as a navigation keeping that layout keeps them.
26
+ let layout: string | undefined
27
+
28
+ // Renders `run` as the markup of `file`, a layout, or of the page for none.
29
+ export function inLayout<T>(file: string | undefined, run: () => T): T {
30
+ const outer = layout
31
+
32
+ layout = file
33
+
34
+ try {
35
+ return run()
36
+ }
37
+ finally {
38
+ layout = outer
39
+ }
40
+ }
41
+
25
42
  // The islands of the page being rendered: it ships the entry when it holds any, and preloads the chunks of those hydrating right away.
26
43
  let rendered: RenderedIslands | undefined
27
44
 
@@ -166,6 +183,18 @@ function persistKey(wanted: IslandOptions['persist'], id: string): string | unde
166
183
  return wanted === false || wanted === '' ? undefined : wanted
167
184
  }
168
185
 
186
+ // What tells an island from the others of its component when no `persist` does: the `key` or `id` its use gives, a string or a number, else the key of the keyed loop it is drawn in, so a swap pairs it with its own copy when a sibling goes away.
187
+ function identityOf(persist: string | undefined, props: object): string | undefined {
188
+ for (const name of persist === undefined ? ['key', 'id'] as const : []) {
189
+ const value = (props as Record<string, unknown>)[name]
190
+
191
+ if (typeof value === 'string' || typeof value === 'number')
192
+ return String(value)
193
+ }
194
+
195
+ return persist === undefined ? loopIdentity() : undefined
196
+ }
197
+
169
198
  // Whether a `hydrate` makes the island wait, `media(...)` needing a query to wait for.
170
199
  function isWaiting(when: string | undefined, id: string): boolean {
171
200
  if (when?.startsWith('media(') === true && (!when.endsWith(')') || when.slice(6, -1).trim() === ''))
@@ -217,14 +246,15 @@ export function island<P extends object>(id: string, component: ((props: P) => J
217
246
  return browserOnly ? renderedHtml('') as unknown as JSX.Element : component!(own)
218
247
 
219
248
  // Rendered here, in the parent, so an island among them is one of its own; unmarked in edit mode, as the island's own markup is.
220
- // A `persist` island's slots stay in the DOM across a same-URL swap, so their ids come from its key as its own do, not from the page's count.
221
- const ids = persist === undefined ? undefined : islandPrefix(persist)
222
- const slots = withFieldMarks(undefined, () => ids === undefined ? staticSlots(own) : withIds(`${ids}s-`, () => withSlotIslands(`${ids}i`, () => staticSlots(own))))
249
+ // Any island may stay in the DOM across a swap, so its ids and those of its slots come from its key, a `persist` one's own else its component's (and its layout's) with its index among them, not from its place in the page, which a render adding another island would shift under the one kept.
250
+ const identity = identityOf(persist, own)
251
+ const ids = islandPrefix(persist ?? [layout, id, identity].filter(part => part !== undefined).join('\0'))
252
+ const slots = withFieldMarks(undefined, () => withIds(`${ids}s-`, () => withSlotIslands(`${ids}i`, () => staticSlots(own))))
223
253
  const given = slots.length === 0 ? own : withSlots(own, slots)
224
254
  const serialized = withFieldMarks(undefined, () => serializeProps(`${id} ${why}`, own, slots))
225
255
 
226
256
  // The browser counts the island's ids from it again as it hydrates.
227
- const prefix = ids ?? islandPrefix()
257
+ const prefix = ids
228
258
 
229
259
  depth++
230
260
 
@@ -266,7 +296,7 @@ export function island<P extends object>(id: string, component: ((props: P) => J
266
296
  const lazies = lazyAttribute(keys, waits)
267
297
  // A page rendered once is shown at every query: the browser draws this island afresh from the address it is opened at, rather than claiming markup made for the default one.
268
298
  const byQuery = queried && prerendering() && !browserOnly ? ' data-query' : ''
269
- const markup: Html = renderedHtml(`<slot data-component="${escapeAttribute(id)}" data-props=${quotedAttribute(serialized)}${lazies}${cause === undefined ? '' : ` data-why=${quotedAttribute(cause)}`}${marked}${titled}${shipped}${browserOnly ? ' data-client' : ''}${byQuery}${count === 0 ? '' : ` data-uid="${escapeAttribute(prefix)}"`}${persist === undefined ? '' : ` data-persist="${escapeAttribute(persist)}"`}${chunk === undefined ? '' : ` data-chunk="${escapeAttribute(chunk)}"`}>${html}</slot>`)
299
+ const markup: Html = renderedHtml(`<slot data-component="${escapeAttribute(id)}" data-props=${quotedAttribute(serialized)}${lazies}${cause === undefined ? '' : ` data-why=${quotedAttribute(cause)}`}${marked}${titled}${shipped}${browserOnly ? ' data-client' : ''}${byQuery}${count === 0 ? '' : ` data-uid="${escapeAttribute(prefix)}"`}${persist === undefined ? '' : ` data-persist="${escapeAttribute(persist)}"`}${layout === undefined ? '' : ` data-layout="${escapeAttribute(layout)}"`}${identity === undefined ? '' : ` data-key="${escapeAttribute(identity)}"`}${chunk === undefined ? '' : ` data-chunk="${escapeAttribute(chunk)}"`}>${html}</slot>`)
270
300
 
271
301
  return markup as unknown as JSX.Element
272
302
  }
@@ -280,7 +310,7 @@ export function island<P extends object>(id: string, component: ((props: P) => J
280
310
  return carryFailed(component, render) as IslandComponent<P>
281
311
  }
282
312
 
283
- // Whether a use of an island that follows no live value, whose `island()` call lists the props that make it interactive, turns none of them on: no listed prop has a value (or a default) that is on, the use asks for no hydration of its own, and none of its props is a function, which an island refuses to send and the use is told of as before.
313
+ // Whether a use of an island that follows no live value, whose `island()` call lists the props that make it interactive, turns none of them on: no listed prop has a value (or a default) that is on, the use asks for no hydration of its own, and none of its props is a promise or markup. A function, a block taking parameters among them, does not keep a use an island: a use turning none of the listed props on renders on the server, which calls it.
284
314
  function staysPlain(depth: number, client: boolean, lives: readonly unknown[], props: object, asks: IslandAsks | undefined): boolean {
285
315
  const wants = asks?.interactive
286
316
 
@@ -291,8 +321,8 @@ function staysPlain(depth: number, client: boolean, lives: readonly unknown[], p
291
321
  if (key === 'hydrate' || key === 'persist' || (key === 'render' && (props as { render?: unknown }).render === 'client') || key === USE_FALLBACK)
292
322
  return false
293
323
 
294
- // What an island would refuse to send, or send for the browser to finish (a promise), keeps the use an island.
295
- if (!descriptor.get && (typeof descriptor.value === 'function' || isThenable(descriptor.value) || holdsMarkup(descriptor.value)))
324
+ // What an island would send for the browser to finish (a promise, an action) keeps the use an island.
325
+ if (!descriptor.get && (isThenable(descriptor.value) || holdsMarkup(descriptor.value) || isAction(descriptor.value)))
296
326
  return false
297
327
  }
298
328
 
@@ -307,12 +337,12 @@ function isThenable(value: unknown): boolean {
307
337
  return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'then') === 'function'
308
338
  }
309
339
 
310
- // Whether the props could cross to the browser, so a use that an island would refuse is still told of it.
340
+ // Whether the props, a function aside, could cross to the browser, so a use that an island would refuse is still told of it.
311
341
  function sendable(props: object): boolean {
312
342
  const plain: Record<string, unknown> = {}
313
343
 
314
344
  for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(props))) {
315
- if (!descriptor.get)
345
+ if (!descriptor.get && typeof descriptor.value !== 'function')
316
346
  plain[key] = descriptor.value
317
347
  }
318
348
 
@@ -72,6 +72,12 @@ export function startNavigation(given: NavigationHooks): void {
72
72
  window.addEventListener('click', onClick)
73
73
  ;(document as { _$kf?: typeof onClick })._$kf = onClick
74
74
  document.addEventListener('focusin', onFocus)
75
+ document.addEventListener('toggle', onToggle, true)
76
+
77
+ // What each `details` of the first load shows is what the server served, as a swap records it for the ones it brings.
78
+ for (const details of document.querySelectorAll('details'))
79
+ navigation.opened.set(details, details.open)
80
+
75
81
  window.addEventListener('popstate', onPopState)
76
82
  // `pagehide` saves the scroll for a full load only: back or forward between entries of this document fires `popstate` once the entry already changed, too late to save the one left, so the entry is kept up to date as the page scrolls.
77
83
  window.addEventListener('scroll', onScroll, { passive: true })
@@ -90,6 +96,14 @@ async function loadFormSubmits(): Promise<typeof import('./form-submits')> {
90
96
  return typeof KAY_NAV_ENTRY === 'undefined' ? formsModule ??= import('./form-submits') : Promise.reject(new Error('unreachable'))
91
97
  }
92
98
 
99
+ // Notes what a `details` showed before its visitor first toggled it, which a refresh compares with the server's.
100
+ function onToggle(event: Event): void {
101
+ const details = event.target
102
+
103
+ if (details instanceof HTMLDetailsElement && !navigation.written.delete(details) && !navigation.opened.has(details))
104
+ navigation.opened.set(details, !details.open)
105
+ }
106
+
93
107
  // Until the forms' listener runs, which then takes the forms a swap brings or a focus lands in itself.
94
108
  function wakeShownForms(): void {
95
109
  if (!formsListen && document.forms.length > 0)
@@ -53,6 +53,10 @@ export interface Swap {
53
53
  saved?: [number, number] | undefined
54
54
  // The element focused before, found again by id or name once swapped: a traversal sets it between entries of one path, which keep the focus.
55
55
  focused?: Element | null
56
+ // Where the focused element sat among the fields of its name before the swap, set as it begins, for the nearest one to take the focus when the swap removes it.
57
+ place?: number | undefined
58
+ // The id of the focused element's nearest ancestor having one, so a row the swap removes is told from a field rendered afresh: the removed one's typed text goes nowhere.
59
+ row?: string | undefined
56
60
  // What the focused text field held when the swap began, so the keys typed in it while the page was fetched are told from the text the server rendered.
57
61
  held?: string | undefined
58
62
  // A form the server refused a post of, and the control focused in it, by their index among the page's forms and the form's controls.
@@ -117,7 +121,11 @@ export const navigation: {
117
121
  traversed?: (state: unknown) => boolean
118
122
  // Development: set while `kay dev` refreshes the page for an edit, where a field the edit leaves as it was keeps what was typed into it.
119
123
  typed?: boolean
120
- } = { shown: '', at: 0, page: 0, current: 0, released: false, loads: 0 }
124
+ // What a `details` the visitor toggled showed as `open` in the render the server gave, noted at its first toggle: a refresh leaves its state to the visitor while the server's stays that.
125
+ opened: WeakMap<Element, boolean>
126
+ // The `details` whose `open` a swap just wrote, so the `toggle` it fires is not taken for the visitor's.
127
+ written: WeakSet<Element>
128
+ } = { shown: '', at: 0, page: 0, current: 0, released: false, loads: 0, opened: new WeakMap(), written: new WeakSet() }
121
129
 
122
130
  // Run once a swap to another path is shown: what an action streams to a caller no island owns closes there.
123
131
  export const leaving = new Set<() => void>()
@@ -7,7 +7,7 @@ import { NAVIGATION_ENTRY } from './navigation-entry'
7
7
  import { forgetPageData } from './page-data'
8
8
  import { abandon, HTML, ownOrigin, pageFor, pageTimeout } from './swap-fetch'
9
9
  import { bounded, CHUNK_TIMEOUT_MS, ENTRY_SCRIPT, inFlight, LATE, policyOf } from './swap-flight'
10
- import { keepTyped, moveFocus, watchTyped } from './swap-focus'
10
+ import { keepTyped, moveFocus, placeOf, rowOf, watchTyped } from './swap-focus'
11
11
  import { mergeHead, runnable, scriptMarkup, swapRoot } from './swap-head'
12
12
  import { checkKept, heldLate, holding, swapBody } from './swap-kept'
13
13
  import { MISSING } from './swap-morph'
@@ -19,7 +19,7 @@ export { CHUNK_TIMEOUT_MS } from './swap-flight'
19
19
  export { TRANSITION_TIMEOUT_MS } from './swap-transition'
20
20
 
21
21
  // The page swap itself, which `./navigate` loads once a visitor is about to follow a link, and `./forms` once a form is posted.
22
- // The body's content becomes the next page's, morphed so what renders again stays the same element, islands kept only by `persist` or a refresh.
22
+ // The body's content becomes the next page's, morphed so what renders again stays the same element, islands kept by `persist`, a match in the same place, or a refresh.
23
23
  // Everything else follows one rule: what the server served changes as the next page serves it, what a script changed or added since stays the script's. The served state is `served` for `<html>`, read from the server's meta, each head element's own `_$s` for the head, and none for `<body>`, which the server writes bare.
24
24
  // Its parts: the fetch in `./swap-fetch`, `<html>` and the head in `./swap-head`, the body's islands and what they keep in `./swap-kept` (a deferred server island's render in the lazy `./swap-held`), the morph in `./swap-morph`, the focus in `./swap-focus`, view transitions in `./swap-transition`, and the policy and what the swaps under way share in `./swap-flight`.
25
25
 
@@ -439,7 +439,10 @@ async function showPage(page: FetchedPage, hash: string, swap: Swap, isCurrent:
439
439
 
440
440
  root()
441
441
  head.commit()
442
- inFlight.typing = process.env.NODE_ENV !== 'production' && navigation.typed === true
442
+ inFlight.typing = swap.intent === 'refresh' || (process.env.NODE_ENV !== 'production' && navigation.typed === true)
443
+
444
+ swap.place = placeOf(swap.focused)
445
+ swap.row = rowOf(swap.focused)
443
446
 
444
447
  try {
445
448
  swapBody(next, policy, held, left)
@@ -853,3 +853,75 @@ export function withSetter<T>(read: () => T, write: (value: T) => void): Signal<
853
853
 
854
854
  return Object.assign(read, { set })
855
855
  }
856
+
857
+ interface Argument {
858
+ value: unknown
859
+ read: () => unknown
860
+ taken: boolean
861
+ }
862
+
863
+ interface Following {
864
+ args: Argument[]
865
+ // The first place in the block's arguments not read yet: a block takes its arguments in order, so one drawn inside it finds them taken.
866
+ next: number
867
+ }
868
+
869
+ // The arguments being drawn by `followed`, which a block's parameters take while the block runs.
870
+ let following: Following | undefined
871
+
872
+ function follow<Drawn>(reads: (() => unknown)[], draw: (...values: never[]) => Drawn): Drawn {
873
+ const values = untrack(() => reads.map(read => read()))
874
+ const first = values[0]
875
+
876
+ if (typeof first !== 'object' || first === null)
877
+ return draw(...reads.map(read => read()) as never[])
878
+
879
+ const outer = following
880
+
881
+ // An item that leaves while the block still reads it is read as it was.
882
+ const args = values.map((value, place): Argument => ({ value, read: place === 0 ? () => reads[0]!() ?? first : reads[place]!, taken: false }))
883
+
884
+ following = { args, next: 0 }
885
+
886
+ try {
887
+ const drawn = untrack(() => draw(...values as never[]))
888
+
889
+ // What the block did not read through its parameters is its value as of the draw, so the block is drawn again when that changes. A draw that throws is the error, whatever these reads do.
890
+ for (const arg of args.filter(one => !one.taken))
891
+ arg.read()
892
+
893
+ return drawn
894
+ }
895
+ finally {
896
+ following = outer
897
+ }
898
+ }
899
+
900
+ // kept: free, a call of the page's own draw.
901
+ // Draws what a block shows for one item of a keyed list once, though the item is replaced by a copy under the same key: the block gets the item as it is, and what it reads of its parameter, where it is used, is the current item each time, so its nodes keep, and a field in them its focus.
902
+ // A call made from a template would track the item it is handed and draw the block again on each replacement. Anything but an object is drawn as a call is, again when it changes, and so is a block that reads its parameter as it was handed.
903
+ export function followed<Item, Drawn, Rest extends unknown[] = []>(read: () => Item, draw: (item: Item, ...rest: Rest) => Drawn, ...others: { [Place in keyof Rest]: () => Rest[Place] }): Drawn {
904
+ return follow([read, ...others], draw as unknown as (...values: never[]) => Drawn)
905
+ }
906
+
907
+ // A block's parameter as an accessor, which the compiled block reads through: the current value when `followed` gave it at this place in the arguments, else the value it was called with.
908
+ export function param<Value>(value: Value, place = 0): () => Value {
909
+ const at = following
910
+ // The item is found by what it is wherever the block takes it; the other arguments by their place, once each.
911
+ const arg = at?.args.find((one, at0) => at0 === 0 ? one.value === value : at0 === place && at0 >= at.next && Object.is(one.value, value))
912
+
913
+ if (arg === undefined)
914
+ return () => value
915
+
916
+ if (arg !== at!.args[0])
917
+ at!.next = place + 1
918
+
919
+ arg.taken = true
920
+
921
+ return arg.read as () => Value
922
+ }
923
+
924
+ // A `slot` called with names or paths: the block, when the component was given one, draws once for the item of the first argument, each of the others read in place by a block that takes it through `param`, and drawn again when one it does not takes changes.
925
+ export function slotCall(block: ((...args: never[]) => unknown) | undefined, first: () => unknown, ...rest: (() => unknown)[]): unknown {
926
+ return block === undefined ? undefined : follow([first, ...rest], block)
927
+ }
@@ -0,0 +1,4 @@
1
+ // The key of a row whose `for` names none: the item's `id` when it has one, else the item itself, so a copy of an item is a new row.
2
+ export function rowKey(item: unknown): unknown {
3
+ return typeof item === 'object' && item !== null && 'id' in item ? item.id : item
4
+ }
@@ -8,20 +8,20 @@ export interface Policy {
8
8
  scroll: 'top' | 'saved' | 'keep'
9
9
  // What gets focus: the new page's autofocus field or heading, its title announced, the element focused before, or the refused form's field.
10
10
  focus: 'page' | 'kept' | 'refused'
11
- // The islands kept: those marked `persist`, or besides them every one whose component and props did not change.
12
- islands: 'persist' | 'unchanged'
11
+ // The islands kept: those marked `persist`, besides them those of a layout the next page has too (`layout`) or any island of the same component in the same place (`all`), each taking the next page's props in place.
12
+ islands: 'layout' | 'all'
13
13
  // Whether the page changes through a view transition, once its stylesheets opt in.
14
14
  transition: boolean
15
15
  }
16
16
 
17
17
  const POLICIES: Record<Intent, Policy> = {
18
- visit: { history: 'push', scroll: 'top', focus: 'page', islands: 'persist', transition: true },
19
- query: { history: 'push', scroll: 'keep', focus: 'kept', islands: 'persist', transition: true },
20
- traverse: { history: 'none', scroll: 'saved', focus: 'page', islands: 'persist', transition: true },
21
- refresh: { history: 'none', scroll: 'keep', focus: 'kept', islands: 'unchanged', transition: false },
22
- redirect: { history: 'replace', scroll: 'keep', focus: 'kept', islands: 'persist', transition: true },
23
- refusal: { history: 'none', scroll: 'keep', focus: 'refused', islands: 'persist', transition: true },
24
- error: { history: 'none', scroll: 'top', focus: 'page', islands: 'persist', transition: true },
18
+ visit: { history: 'push', scroll: 'top', focus: 'page', islands: 'layout', transition: true },
19
+ query: { history: 'push', scroll: 'keep', focus: 'kept', islands: 'layout', transition: true },
20
+ traverse: { history: 'none', scroll: 'saved', focus: 'page', islands: 'layout', transition: true },
21
+ refresh: { history: 'none', scroll: 'keep', focus: 'kept', islands: 'all', transition: false },
22
+ redirect: { history: 'replace', scroll: 'keep', focus: 'kept', islands: 'layout', transition: true },
23
+ refusal: { history: 'none', scroll: 'keep', focus: 'refused', islands: 'layout', transition: true },
24
+ error: { history: 'none', scroll: 'top', focus: 'page', islands: 'layout', transition: true },
25
25
  }
26
26
 
27
27
  // What the swaps under way share, which each one reads before it acts: `navigation.current` is the token of the latest one started, which every swap that is not it gives way to.
@@ -36,7 +36,7 @@ export const inFlight: {
36
36
  late?: LateParts | undefined
37
37
  // The click listener of the view transition running, at most one.
38
38
  transition?: ((event: MouseEvent) => void) | undefined
39
- // Whether the commit under way keeps what was typed into the fields the next page renders as they were, which `kay dev` asks of a refresh for an edit.
39
+ // Whether the commit under way keeps what the visitor changed (a field's value, a `details`' `open`) where the server's render did not change it: a refresh does, and so does `kay dev` for an edit.
40
40
  typing: boolean
41
41
  // The selects the commit under way found renamed, whose options show what the next page renders.
42
42
  renamed: Set<Element>