@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
@@ -15,10 +15,50 @@ interface Typed { value: string, start: number | null, end: number | null, direc
15
15
 
16
16
  const noteOf = (field: Field): Typed => ({ value: field.value, start: field.selectionStart, end: field.selectionEnd, direction: field.selectionDirection ?? 'none' })
17
17
 
18
- function byName(element: Element | null): Element | null {
18
+ // The element's place in document order among the fields of its name, read before a swap removes it.
19
+ export function placeOf(element: Element | null | undefined): number | undefined {
19
20
  const name = element?.getAttribute('name') ?? ''
20
21
 
21
- return name === '' ? null : document.getElementsByName(name)[0] ?? null
22
+ return name === '' || !element?.isConnected ? undefined : Array.from<Element>(document.getElementsByName(name)).indexOf(element)
23
+ }
24
+
25
+ // The time stamp kay writes into a form of an action with `minTime`, new on every render, so it tells no row apart (`STAMP_FIELD` in action-form.ts, kept apart as form-protect.ts does).
26
+ const STAMP_FIELD = 'kay_since'
27
+
28
+ // What a form is by: its id, else its action with the hidden fields it posts, which a row's form carries its key in.
29
+ function formKey(form: HTMLFormElement): string | undefined {
30
+ const id = form.getAttribute('id')
31
+
32
+ if (id !== null && id !== '')
33
+ return `#${id}`
34
+
35
+ const hidden = Array.from(form.querySelectorAll<HTMLInputElement>(`input[type=hidden]:not([name="${STAMP_FIELD}"])`), input => `${input.name}=${input.value}`)
36
+
37
+ return hidden.length === 0 ? undefined : `${form.getAttribute('action')}?${hidden.join('&')}`
38
+ }
39
+
40
+ // The element's row in a list, read before a swap removes it: its form's key, else the id of its nearest ancestor having one. A row no longer on the page is a field removed, not one rendered afresh. A row with neither tells the two apart no better than before.
41
+ export function rowOf(element: Element | null | undefined): string | undefined {
42
+ const form = element?.closest('form')
43
+ const id = element?.parentElement?.closest('[id]:not([id=""])')?.getAttribute('id')
44
+
45
+ return (form ? formKey(form) : undefined) ?? (id !== null && id !== undefined && id !== '' ? `#${id}` : undefined)
46
+ }
47
+
48
+ function rowKept(row: string): boolean {
49
+ return row.startsWith('#') ? document.getElementById(row.slice(1)) !== null : Array.from(document.forms).some(form => formKey(form) === row)
50
+ }
51
+
52
+ // The field of the name nearest to where the removed one was: the one now at its place, else the last. None without a place.
53
+ function byName(element: Element | null, place: number | undefined): Element | null {
54
+ const name = element?.getAttribute('name') ?? ''
55
+
56
+ if (name === '' || place === undefined)
57
+ return null
58
+
59
+ const fields = document.getElementsByName(name)
60
+
61
+ return fields[Math.max(0, Math.min(place, fields.length - 1))] ?? null
22
62
  }
23
63
 
24
64
  // The element focused before, found again on a refreshed page or on Back and Forward between entries of one path; on a new page, the element its hash points at, else its autofocus field, its heading or its main, so a screen reader starts there, the title announced. Back and Forward skip the autofocus field, which the visitor left already, and a position an entry saved leaves the hash alone, as it does the scroll.
@@ -38,11 +78,14 @@ export async function moveFocus(swap: Swap, policy: Policy, hash: string): Promi
38
78
  if (before?.isConnected)
39
79
  return
40
80
 
41
- const again = before?.id !== undefined && before.id !== '' ? document.getElementById(before.id) : byName(before)
81
+ const again = before?.id !== undefined && before.id !== '' ? document.getElementById(before.id) : byName(before, swap.place)
42
82
 
43
83
  if (again instanceof HTMLElement) {
44
84
  again.focus({ preventScroll: true })
45
- carryCaret(before, again, swap.held)
85
+
86
+ // The text of a field removed with its row is no one else's.
87
+ if (swap.row === undefined || rowKept(swap.row))
88
+ carryCaret(before, again, swap.held)
46
89
  }
47
90
 
48
91
  return
@@ -94,6 +137,7 @@ function carryCaret(from: Element | null, to: HTMLElement, held: string | undefi
94
137
  // The island hears the kept keys once it has hydrated, by this field's own listener so that no path of the swap can drop them: the text is put back if hydration wrote the server's over it, and `input` fires either way. The latest text typed meanwhile is the one kept, and the bound of 30 s ends the wait for an island that never hydrates.
95
138
  function replayOnHydrate(field: Field, island: Island): void {
96
139
  let typed = noteOf(field)
140
+ const place = placeOf(field)
97
141
  const heard = new AbortController()
98
142
  let timer: ReturnType<typeof setTimeout> | undefined
99
143
  const end = () => {
@@ -112,7 +156,7 @@ function replayOnHydrate(field: Field, island: Island): void {
112
156
  end()
113
157
 
114
158
  if (island.isConnected)
115
- putBack(found(field), { ...typed, replay: true })
159
+ putBack(found(field, place), { ...typed, replay: true })
116
160
  }, { signal: heard.signal, once: true })
117
161
  }
118
162
 
@@ -172,8 +216,8 @@ function putBack(now: Element | null, typed: Typed | undefined): void {
172
216
  }
173
217
 
174
218
  // The field itself, or the one hydration put in its place.
175
- function found(field: Field, id = field.id): Element | null {
176
- return field.isConnected ? field : (id === '' ? null : document.getElementById(id)) ?? byName(field)
219
+ function found(field: Field, place: number | undefined, id = field.id): Element | null {
220
+ return field.isConnected ? field : (id === '' ? null : document.getElementById(id)) ?? byName(field, place)
177
221
  }
178
222
 
179
223
  // Keys typed into an island's field after the swap and before the island hydrated land in the server's markup, which hydration then writes its own value over. Called as the swap hands the body to hydration, it notes them as they come into the focused field and puts them back once its island has hydrated, however late a `visible` or `idle` one is, with `input` fired so the island hears them, the caret after them. A newer swap, or a bound of 30 s (an island that never hydrates, or whose hydration failed, as the event fires only on success), ends the watch with nothing restored.
@@ -189,6 +233,7 @@ export function watchTyped(): void {
189
233
  return
190
234
 
191
235
  const id = field.id
236
+ const place = placeOf(field)
192
237
  let typed: Typed | undefined
193
238
  const note = (event: Event) => {
194
239
  if (event.target === field)
@@ -208,7 +253,7 @@ export function watchTyped(): void {
208
253
  timer = setTimeout(end, WATCH_BOUND_MS)
209
254
  island.addEventListener(HYDRATED, () => {
210
255
  end()
211
- putBack(found(field, id), typed)
256
+ putBack(found(field, place, id), typed)
212
257
  }, { once: true, signal: heard.signal })
213
258
  }
214
259
 
@@ -216,6 +261,7 @@ export function watchTyped(): void {
216
261
  export function keepTyped(part: ParentNode): void {
217
262
  for (const island of part.querySelectorAll<Island>(ISLAND)) {
218
263
  let field: Field | undefined
264
+ let place: number | undefined
219
265
  let typed: Typed | undefined
220
266
  const heard = new AbortController()
221
267
  const timer = setTimeout(() => heard.abort(), WATCH_BOUND_MS)
@@ -224,13 +270,14 @@ export function keepTyped(part: ParentNode): void {
224
270
  island.addEventListener('input', (event) => {
225
271
  if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
226
272
  field = event.target
273
+ place = placeOf(field)
227
274
  typed = noteOf(field)
228
275
  }
229
276
  }, { ...options, capture: true })
230
277
  island.addEventListener(HYDRATED, () => {
231
278
  clearTimeout(timer)
232
279
  heard.abort()
233
- putBack(field ? found(field) : null, typed)
280
+ putBack(field ? found(field, place) : null, typed)
234
281
  }, { ...options, once: true })
235
282
  }
236
283
  }
@@ -2,12 +2,15 @@ import type { Policy } from './swap-flight'
2
2
  import { ISLAND } from './markers'
3
3
  import { moves, place } from './move'
4
4
  import { navigation } from './navigation'
5
+ import { inFlight } from './swap-flight'
5
6
  import { runnable, scriptMarkup } from './swap-head'
6
7
  import { KEPT, MISSING, morphChildren, scoped, UNIT } from './swap-morph'
7
8
  import { decodeServerValue } from './wire'
8
9
 
9
10
  const PERSISTENT = 'slot[data-persist]'
10
11
  const SERVER_ISLAND = 'slot[data-kay-server]'
12
+ // The islands a layout rendered, which a navigation keeping the layout keeps.
13
+ const LAYOUT_ISLAND = `${ISLAND}[data-layout]`
11
14
  // What a script put in the body to outlive every page, a live region an announcer fills for one: the next body never holds it, so the morph leaves it where it is, never moved, as a live region taken out and put back may go unread.
12
15
  const LASTING = ':scope > [data-kay-keep]'
13
16
 
@@ -83,6 +86,7 @@ export function swapBody(next: Document, policy: Policy, held: Held | undefined,
83
86
  const body = document.adoptNode(next.body)
84
87
  const old = document.body
85
88
  const focused = heldFocus()
89
+ const release = holdScroll(policy)
86
90
 
87
91
  const kept = new Set<Element>()
88
92
  // What the server left to the page as it is, found by its id by the caller before anything moved.
@@ -92,7 +96,8 @@ export function swapBody(next: Document, policy: Policy, held: Held | undefined,
92
96
  const scrolls = new Map<Element, readonly [left: number, top: number]>()
93
97
 
94
98
  // Read before the first move, and only when the next page has an island to keep, so every read shares one layout instead of forcing one after each move.
95
- const candidates = policy.islands === 'unchanged' ? `${PERSISTENT},${ISLAND}` : PERSISTENT
99
+ const matching = policy.islands === 'all' ? ISLAND : LAYOUT_ISLAND
100
+ const candidates = `${PERSISTENT},${matching}`
96
101
 
97
102
  for (const root of [...body.querySelector(candidates) ? old.querySelectorAll(candidates) : [], ...lives]) {
98
103
  for (const element of [root, ...root.querySelectorAll('*')]) {
@@ -132,37 +137,11 @@ export function swapBody(next: Document, policy: Policy, held: Held | undefined,
132
137
  markCurrent(live, placeholder)
133
138
  keep(placeholder, live)
134
139
 
135
- const props = placeholder.dataset.props
136
-
137
- // What the next page gives it, which it reads from now on, or once it hydrates.
138
- if (props !== live.dataset.props) {
139
- if (props === undefined)
140
- delete live.dataset.props
141
- else
142
- live.dataset.props = props
143
-
144
- live._$p?.(props === undefined ? {} : decodeServerValue(props) as object)
145
- }
140
+ givePropsOf(live, placeholder)
146
141
  }
147
142
  }
148
143
 
149
- if (policy.islands === 'unchanged') {
150
- const unchanged = [...old.querySelectorAll<KeptIsland>(ISLAND)]
151
-
152
- for (const placeholder of body.querySelectorAll<HTMLElement>(ISLAND)) {
153
- // One in the static slot of an island kept went along with it, or away with the copy it replaced.
154
- if (!body.contains(placeholder) || standIns.has(placeholder) || [...kept].some(island => island.contains(placeholder)))
155
- continue
156
-
157
- const index = unchanged.findIndex(live => old.contains(live) && live.dataset.component === placeholder.dataset.component && live.dataset.props === placeholder.dataset.props && live.dataset.slots === placeholder.dataset.slots && (live.dataset.slots === undefined || (live._$h ?? live.innerHTML) === placeholder.innerHTML))
158
-
159
- if (index !== -1) {
160
- const [live] = unchanged.splice(index, 1)
161
-
162
- keep(placeholder, live!)
163
- }
164
- }
165
- }
144
+ keepMatched(old, body, matching, standIns, keep)
166
145
 
167
146
  // Every island left is taken away, as the morph never keeps one.
168
147
  navigation.hooks!.dispose(old)
@@ -199,6 +178,8 @@ export function swapBody(next: Document, policy: Policy, held: Held | undefined,
199
178
  finally {
200
179
  scoped.on = false
201
180
  parking?.remove()
181
+
182
+ release()
202
183
  }
203
184
 
204
185
  for (const [element, [left, top]] of scrolls) {
@@ -209,6 +190,12 @@ export function swapBody(next: Document, policy: Policy, held: Held | undefined,
209
190
  if (focused && document.activeElement !== focused.element && [...kept].some(island => island.contains(focused.element)))
210
191
  focused.restore()
211
192
 
193
+ // What each `details` shows now is what the server served: the visitor's toggle, which a refresh compares with it, comes after, and a toggle event the markup's own opening fires is not one.
194
+ for (const details of document.querySelectorAll('details')) {
195
+ if (!inFlight.typing || !navigation.opened.has(details))
196
+ navigation.opened.set(details, details.open)
197
+ }
198
+
212
199
  // A drawer or a menu left open closes as the page changes, as it would on a page loaded afresh.
213
200
  for (const popover of opened) {
214
201
  if (popover.isConnected && popover instanceof HTMLElement && popover.matches(':popover-open'))
@@ -222,6 +209,87 @@ export function swapBody(next: Document, policy: Policy, held: Held | undefined,
222
209
  }
223
210
  }
224
211
 
212
+ // Chrome's scroll anchoring follows an anchor node the morph moves or drops, and lands the window elsewhere, the end of a list of rows for one: it is off while the morph runs, and a position a refresh keeps is put back after, which the returned function does.
213
+ function holdScroll(policy: Policy): () => void {
214
+ const root = document.documentElement
215
+ const anchoring = root.style.overflowAnchor
216
+ const styled = root.hasAttribute('style')
217
+ const { scrollX: x, scrollY: y } = window
218
+
219
+ root.style.overflowAnchor = 'none'
220
+
221
+ return () => {
222
+ // Reading the scroll forces the layout while anchoring is still off, which is what keeps it from adjusting.
223
+ if (policy.scroll === 'keep' && (scrollX !== x || scrollY !== y))
224
+ scrollTo({ left: x, top: y, behavior: 'instant' })
225
+
226
+ if (anchoring !== '')
227
+ root.style.overflowAnchor = anchoring
228
+ else
229
+ root.style.removeProperty('overflow-anchor')
230
+
231
+ // An emptied style still leaves `style=""`, which the next swap reads as a script's change to <html>.
232
+ if (!styled && root.getAttribute('style') === '')
233
+ root.removeAttribute('style')
234
+ }
235
+ }
236
+
237
+ // An island of the next page that has its match among those of this one, the same component in the same place, stays and takes the new props: what the visitor did in it is its own.
238
+ function keepMatched(old: Element, body: Element, matching: string, standIns: ReadonlyMap<Element, Element>, keep: (placeholder: Element, live: Element) => void): void {
239
+ const live = new Map<string, KeptIsland[]>()
240
+
241
+ // Only the islands of the page itself take part: one in another's static slot goes where its parent goes.
242
+ for (const island of old.querySelectorAll<KeptIsland>(matching)) {
243
+ if (island.dataset.persist !== undefined || island.parentElement?.closest(ISLAND))
244
+ continue
245
+
246
+ const place = placeOf(island)
247
+ const list = live.get(place)
248
+
249
+ if (list)
250
+ list.push(island)
251
+ else
252
+ live.set(place, [island])
253
+ }
254
+
255
+ if (live.size === 0)
256
+ return
257
+
258
+ for (const placeholder of body.querySelectorAll<HTMLElement>(matching)) {
259
+ // One in the static slot of an island kept went along with it, or away with the copy it replaced.
260
+ if (placeholder.dataset.persist !== undefined || !body.contains(placeholder) || standIns.has(placeholder) || placeholder.parentElement?.closest(ISLAND))
261
+ continue
262
+
263
+ const match = live.get(placeOf(placeholder))?.shift()
264
+
265
+ if (match && old.contains(match) && match.dataset.slots === placeholder.dataset.slots && (match.dataset.slots === undefined || (match._$h ?? match.innerHTML) === placeholder.innerHTML)) {
266
+ markCurrent(match, placeholder)
267
+ keep(placeholder, match)
268
+ givePropsOf(match, placeholder)
269
+ }
270
+ }
271
+ }
272
+
273
+ // Where an island stands among the others, which the next page's copy of it is paired by: its layout, component and `key` or `id`, then in order.
274
+ function placeOf(island: HTMLElement): string {
275
+ return `${island.dataset.layout ?? ''}\0${island.dataset.component}\0${island.dataset.key ?? ''}`
276
+ }
277
+
278
+ // What the next page gives a kept island, which it reads from now on, or once it hydrates.
279
+ function givePropsOf(live: KeptIsland, next: HTMLElement): void {
280
+ const props = next.dataset.props
281
+
282
+ if (props === live.dataset.props)
283
+ return
284
+
285
+ if (props === undefined)
286
+ delete live.dataset.props
287
+ else
288
+ live.dataset.props = props
289
+
290
+ live._$p?.(props === undefined ? {} : decodeServerValue(props) as object)
291
+ }
292
+
225
293
  const KAY_MARKS = new Set<string | null>([null, 'page', 'true'])
226
294
 
227
295
  // The marks of the next page's copy of an island kept, a link to the page now shown, `aria-current`, carried over to the links of the one that lives on, found by their place and address: those that differ are left, as the island renders them itself, and so is a value kay never writes (`step`, `false`), which an island setting its own holds.
@@ -1,8 +1,9 @@
1
1
  import { ISLAND } from './markers'
2
+ import { navigation } from './navigation'
2
3
  import { inFlight } from './swap-flight'
3
4
 
4
5
  const NOTHING: ReadonlySet<Node> = new Set()
5
- // What the morph never keeps across pages: islands are kept by `persist` or a refresh alone, and a script or a template is put in afresh.
6
+ // What the morph never keeps across pages: islands are kept by `persist`, a match in the same place or a refresh, never morphed, and a script or a template is put in afresh.
6
7
  const OPAQUE = `${ISLAND},slot[data-kay-server],script,template`
7
8
  // The tags OPAQUE can match, so the selector is only matched for them.
8
9
  const OPAQUE_TAGS = new Set(['slot', 'script', 'template'])
@@ -37,9 +38,9 @@ function alike(live: Node, next: Node): boolean {
37
38
  return live.id === other.id && live.getAttribute('class') === other.getAttribute('class') && (!OPAQUE_TAGS.has(live.localName) || (!live.matches(OPAQUE) && !other.matches(OPAQUE)))
38
39
  }
39
40
 
40
- // Whether a field keeps what was typed into it: it is the same field and the edit left what the server renders in it as it was, so only a visitor changed it.
41
+ // Whether a field keeps what was typed into it: it is the same field and the render left what the server renders in it as it was, so only a visitor changed it.
41
42
  function typedKept(live: Element, other: Element): boolean {
42
- if (process.env.NODE_ENV === 'production' || !inFlight.typing)
43
+ if (!inFlight.typing)
43
44
  return false
44
45
 
45
46
  if (live instanceof HTMLInputElement && other instanceof HTMLInputElement)
@@ -72,6 +73,37 @@ function holdTabStop(element: Element): void {
72
73
  }, { once: true, signal: held.signal })
73
74
  }
74
75
 
76
+ // Whether a `details` the visitor toggled keeps its state: the render leaves what the server wrote as `open` when the visitor toggled it, so only the visitor changed it. One the server changed takes the server's, and is the visitor's again from its next toggle.
77
+ function keepsOpen(live: Element, other: Element): boolean {
78
+ if (!(live instanceof HTMLDetailsElement))
79
+ return false
80
+
81
+ // A swap that keeps nothing of the visitor's leaves what it served as the new baseline.
82
+ if (!inFlight.typing) {
83
+ navigation.opened.delete(live)
84
+
85
+ return false
86
+ }
87
+
88
+ const served = navigation.opened.get(live)
89
+
90
+ if (served === undefined)
91
+ return false
92
+
93
+ if (other.hasAttribute('open') === served)
94
+ return true
95
+
96
+ navigation.opened.delete(live)
97
+
98
+ return false
99
+ }
100
+
101
+ // A change the morph makes to `open`, whose `toggle` event is not the visitor's.
102
+ function wrote(live: Element, name: string): void {
103
+ if (name === 'open' && live instanceof HTMLDetailsElement)
104
+ navigation.written.add(live)
105
+ }
106
+
75
107
  // Makes the live node read as the next one, keeping it and each child of it the next page renders again.
76
108
  function morph(live: Node, next: Node): void {
77
109
  if (!(live instanceof Element)) {
@@ -89,29 +121,37 @@ function morph(live: Node, next: Node): void {
89
121
  // Read before the attributes and the children become the next page's, which the defaults come from.
90
122
  const typed = typedKept(live, other)
91
123
 
92
- if (process.env.NODE_ENV !== 'production' && inFlight.typing && live instanceof HTMLSelectElement && live.name !== (other as HTMLSelectElement).name)
124
+ if (inFlight.typing && live instanceof HTMLSelectElement && live.name !== (other as HTMLSelectElement).name)
93
125
  inFlight.renamed.add(live)
94
126
 
95
127
  // An element's open state is closed through it, as the attribute alone would leave a modal dialog blocking the page.
96
128
  if (live instanceof HTMLDialogElement && live.open && !other.hasAttribute('open'))
97
129
  live.close()
98
130
 
131
+ const opened = keepsOpen(live, other)
132
+
99
133
  for (const { name, value } of other.attributes) {
100
- if (live.getAttribute(name) !== value)
134
+ if (live.getAttribute(name) !== value && !(opened && name === 'open')) {
135
+ wrote(live, name)
101
136
  live.setAttribute(name, value)
137
+ }
102
138
  }
103
139
 
104
140
  if (other.hasAttribute('tabindex'))
105
141
  heldTabStops.get(live)?.abort()
106
142
 
107
143
  for (const name of live.getAttributeNames()) {
108
- if (other.hasAttribute(name))
144
+ if (other.hasAttribute(name) || (opened && name === 'open'))
109
145
  continue
110
146
 
111
- if (name === 'tabindex' && live === document.activeElement)
147
+ if (name === 'tabindex' && live === document.activeElement) {
112
148
  holdTabStop(live)
113
- else
114
- live.removeAttribute(name)
149
+
150
+ continue
151
+ }
152
+
153
+ wrote(live, name)
154
+ live.removeAttribute(name)
115
155
  }
116
156
 
117
157
  morphChildren(live, other)
@@ -0,0 +1,17 @@
1
+ // cyrb53, 53 bits of a string's hash in base 36, in plain script so the browser and the docs playground run it as the server does.
2
+ export function textHash(text: string): string {
3
+ let h1 = 0xDEADBEEF
4
+ let h2 = 0x41C6CE57
5
+
6
+ for (let index = 0; index < text.length; index++) {
7
+ const code = text.charCodeAt(index)
8
+
9
+ h1 = Math.imul(h1 ^ code, 2654435761)
10
+ h2 = Math.imul(h2 ^ code, 1597334677)
11
+ }
12
+
13
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
14
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
15
+
16
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36)
17
+ }
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { textHash } from './text-hash'
2
3
  import { freshPrefix, withIds } from './uid'
3
4
 
4
5
  // The page the server is rendering: its token keeps ids apart from those of a page swapped out around a persistent island.
@@ -50,7 +51,7 @@ export function withSlotIslands<T>(prefix: string, run: () => T): T {
50
51
  }
51
52
 
52
53
  // The prefix of the next island the server renders, written on its slot.
53
- // A `persist` island takes it from its key instead of its place, so the page that replaces one at the same URL, with the same token, cannot give another island the ids the kept one still holds.
54
+ // An island takes it from its key (a `persist` one's own, else its component's with its layout's) and its index among those of that key, not from its place in the page, so the page that replaces one at the same URL, with the same token, cannot give another island the ids the kept one still holds.
54
55
  export function islandPrefix(persist?: string): string {
55
56
  if (!page)
56
57
  return freshPrefix()
@@ -61,9 +62,10 @@ export function islandPrefix(persist?: string): string {
61
62
  if (persist === undefined)
62
63
  return `${page.token}-${page.islands++}-`
63
64
 
64
- const seen = page.kept.get(persist) ?? 0
65
+ const hash = textHash(persist).slice(-6)
66
+ const seen = page.kept.get(hash) ?? 0
65
67
 
66
- page.kept.set(persist, seen + 1)
68
+ page.kept.set(hash, seen + 1)
67
69
 
68
- return `${page.token}-p${Bun.hash(persist).toString(36)}${seen === 0 ? '' : `_${seen}`}-`
70
+ return `${page.token}-p${hash}${seen === 0 ? '' : `_${seen}`}-`
69
71
  }
@@ -211,6 +211,18 @@ export function handParts(list: readonly unknown[], written?: unknown): unknown
211
211
  return all.length < 2 ? all[0] : mergeParts(all)
212
212
  }
213
213
 
214
+ // The `class` and `parts` of a call handing a part of this component on, both read from one list (and the `parts` the call writes): the one prop pair a call site writes, as `partsClass` and `handParts` give them.
215
+ export function partProps(read: () => readonly [list: readonly unknown[], written?: unknown]): { readonly class: string | undefined, readonly parts: unknown } {
216
+ return {
217
+ get class() {
218
+ return partsClass(read()[0])
219
+ },
220
+ get parts() {
221
+ return handParts(...read())
222
+ },
223
+ }
224
+ }
225
+
214
226
  // The entry of a part that is a component is its own parts, as `partClass` reads it from a prop.
215
227
  function entryParts(entry: unknown): unknown {
216
228
  return typeof entry === 'object' && entry !== null && !Array.isArray(entry) ? taggedParts(entry as Record<string, unknown>) : entry
@@ -1,4 +1,5 @@
1
1
  import type { ClientOptions } from '../build/client'
2
+ import type { IslandImages } from '../build/island-images'
2
3
  import type { SizeReport } from '../build/report'
3
4
  import type { StyleUses, UnresolvedClass } from '../build/style-uses'
4
5
  import type { Node } from '../build/supports'
@@ -130,6 +131,8 @@ export interface ClientBuild extends Omit<ClientManifest, 'styles' | 'pages' | '
130
131
  report?: SizeReport | undefined
131
132
  // The directories of the packages its modules and stylesheets come from, for the notices file.
132
133
  packages?: string[] | undefined
134
+ // A static export's: the images its islands draw that no page renders.
135
+ islandImages?: IslandImages | undefined
133
136
  }
134
137
 
135
138
  // Quoted, spaces included, or bare.
package/src/server/dev.ts CHANGED
@@ -670,6 +670,8 @@ export interface DevRequest {
670
670
  prerender?: 'page' | 'listed' | 'server islands' | undefined
671
671
  // The page in each locale of a site with `i18n` that serves more than one, where a language switcher links to: the locale and the address, under the base.
672
672
  locales?: { locale: string, href: string }[] | undefined
673
+ // Whether the app serves `/_kay/env.js`, which the Env tab asks for only then.
674
+ publicEnv?: boolean | undefined
673
675
  }
674
676
 
675
677
  // What the server recorded of one response, for the Request tab to ask for once the page is in view.
@@ -769,7 +769,7 @@ export async function writeRemoteVariants(clientDir: string, remote: RemoteImage
769
769
  const original = await remote(src)
770
770
 
771
771
  if ('status' in original)
772
- throw new KayError('image-invalid', `kay: a page links ${src}, which the build could not download: ${original.message}`)
772
+ throw new KayError('image-invalid', `kay: a page or an island links ${src}, which the build could not download: ${original.message}`)
773
773
 
774
774
  await imageSize(Bun.file(original.path))
775
775
  await writeVariant(original.path, variant, target, variantLevel(variant, 'webp', quality, DEFAULT_AVIF_QUALITY))
@@ -31,6 +31,7 @@ export const KAY_EXPORTS: Record<string, 'free' | 'request' | 'local'> = {
31
31
  flush: 'free',
32
32
  focusInvalid: 'free',
33
33
  followLog: 'free',
34
+ followed: 'free',
34
35
  formErrors: 'free',
35
36
  guard: 'request',
36
37
  guardLeave: 'free',
@@ -21,7 +21,7 @@ import { collectHead, head as setHead } from '../runtime/head'
21
21
  import { child, component, html, newServerIslands, withinComponent, withServerIslands } from '../runtime/html'
22
22
  import { localePath, textDirection } from '../runtime/i18n'
23
23
  import { DEFAULT_MAX_DENSITY, RESOLVED_META } from '../runtime/image'
24
- import { unrevivableAction } from '../runtime/island.server'
24
+ import { inLayout, unrevivableAction } from '../runtime/island.server'
25
25
  import { resourcesUsed, resourcesWanted, withSeeds } from '../runtime/live-resource.server'
26
26
  import { localeState } from '../runtime/locale-state'
27
27
  import { kayLog } from '../runtime/log'
@@ -119,7 +119,7 @@ function pageClassesBlock(client: ClientBuild, files: string[]): string {
119
119
  }
120
120
 
121
121
  // What the dev tool's Request tab shows: the route matched, the files that rendered, the params, the status, and how long each load took, the matched route's when another page shows its error.
122
- function requestBlock(files: string[], rendering: Rendering, base: string): string {
122
+ function requestBlock(files: string[], rendering: Rendering, base: string, publicEnv: boolean): string {
123
123
  const { loads } = rendering
124
124
  const state = localeState()
125
125
  // A host of its own is a protocol-relative address, which the base does not prefix.
@@ -141,6 +141,7 @@ function requestBlock(files: string[], rendering: Rendering, base: string): stri
141
141
  ...rendering.slow,
142
142
  locale: rendering.ctx.locale,
143
143
  locales,
144
+ publicEnv,
144
145
  status: rendering.status,
145
146
  error: (rendering.ctx as Partial<ErrorPageContext>).error?.message,
146
147
  loads: loads ? loads.files.flatMap((file, index) => loads.modules[index]!.load ? [{ file: projectPath(file), ms: loads.timings?.[index] }] : []) : [],
@@ -359,10 +360,12 @@ function registerSeo(module: PageModule): void {
359
360
 
360
361
  // The page inside its layouts, each through `component`, so what a layout provides reaches its page.
361
362
  // A layout's named slot is read off its page: reading one renders the page first, once, which hands the layout the blocks it wrote.
362
- export function viewOf(modules: PageModule[], data: Record<string, unknown>[], entry?: HeadTag[]): () => unknown {
363
+ export function viewOf(modules: PageModule[], data: Record<string, unknown>[], entry?: HeadTag[], files?: readonly string[]): () => unknown {
363
364
  const page = modules.length - 1
364
365
  const chain = newFillChain(modules.length)
365
366
  const declared = modules.map(module => module.slots)
367
+ // The layout a module renders as, for the islands it draws to carry it: none for the page.
368
+ const layoutOf = (index: number) => index < page && files?.[index] !== undefined ? projectPath(files[index]) : undefined
366
369
 
367
370
  // Set after its layouts' heads and before its own, which each replace what the entry gave.
368
371
  let view = () => {
@@ -373,7 +376,7 @@ export function viewOf(modules: PageModule[], data: Record<string, unknown>[], e
373
376
 
374
377
  registerSeo(modules[page]!)
375
378
 
376
- return component(modules[page]!.default, data[page]!)
379
+ return inLayout(undefined, () => component(modules[page]!.default, data[page]!))
377
380
  }
378
381
 
379
382
  for (let index = page - 1; index >= 0; index--) {
@@ -400,14 +403,14 @@ export function viewOf(modules: PageModule[], data: Record<string, unknown>[], e
400
403
 
401
404
  const found = filledBy(chain, declared, index, name)
402
405
 
403
- return found && withinComponent(modules[found.at]!.default, found.block)
406
+ return found && inLayout(layoutOf(found.at), () => withinComponent(modules[found.at]!.default, found.block))
404
407
  } })
405
408
  }
406
409
 
407
410
  chain.at = index
408
411
  registerSeo(modules[index]!)
409
412
 
410
- return component(modules[index]!.default, props)
413
+ return inLayout(layoutOf(index), () => component(modules[index]!.default, props))
411
414
  }
412
415
  }
413
416
 
@@ -451,7 +454,7 @@ function seedBlocks(deferred: PendingBlock[], seeds: ReadonlyMap<string, Seed>):
451
454
  }
452
455
 
453
456
  function documentOf(files: string[], modules: PageModule[], data: Record<string, unknown>[], client: ClientBuild, rendering: Rendering, options: RenderOptions, rules: QueryRules | undefined, entry?: HeadTag[]): string | Pieced | ReadableStream<Uint8Array> {
454
- const view = viewOf(modules, data, entry)
457
+ const view = viewOf(modules, data, entry, files)
455
458
  const chunks = islandChunks(client)
456
459
  // A prerendered page holds each server island between marks the server splits it at.
457
460
  const scan = options.prerendering ? Object.assign(newServerIslands(true), { awaits: options.awaits }) : undefined
@@ -521,7 +524,7 @@ function documentOf(files: string[], modules: PageModule[], data: Record<string,
521
524
  const sheets = stylesheets(client, styled)
522
525
  // The nearest-`data-prefetch` selector is needed once the page holds the attribute or may gain it later: a streamed part, an island, or a server island spliced into a prerendered page.
523
526
  const mayPrefetchPerLink = shipsEntry || streamed || (scan?.modes.length ?? 0) > 0 || [markup, head.html, head.root].some(html => DATA_PREFETCH.test(html))
524
- const closing = `${headHtml}${scripts}${islandData}${kayMetas(options, hasIslands)}${newTabRule(markup, hasIslands || streamed, options.sameTabLinks === true)}${buttonFormRule(markup, streamed, islands.messages)}${shipsEntry && client.build !== undefined ? `<meta name="${BUILD_META}" content="${client.build}">` : ''}${shipsEntry && client.navigation === true ? prefetchMeta(options.client?.prefetch) : pageSpeculation(options, mayPrefetchPerLink)}${rendering.guarded === true ? GUARDED_META : ''}${client.navigation === true && !shipsEntry ? historyScript : ''}${options.offline ? registerScript(options.base ?? '', options.installOffer === true) : ''}${keepsInstallOffer ? `<script>${INSTALL_OFFER}</script>` : ''}${options.dev && options.devTools ? devScripts(client, styled, options.client?.lateStyles === true) + (options.prerendering ? '' : requestBlock(files, rendering, options.base ?? '')) : ''}</head><body>${body}`
527
+ const closing = `${headHtml}${scripts}${islandData}${kayMetas(options, hasIslands)}${newTabRule(markup, hasIslands || streamed, options.sameTabLinks === true)}${buttonFormRule(markup, streamed, islands.messages)}${shipsEntry && client.build !== undefined ? `<meta name="${BUILD_META}" content="${client.build}">` : ''}${shipsEntry && client.navigation === true ? prefetchMeta(options.client?.prefetch) : pageSpeculation(options, mayPrefetchPerLink)}${rendering.guarded === true ? GUARDED_META : ''}${client.navigation === true && !shipsEntry ? historyScript : ''}${options.offline ? registerScript(options.base ?? '', options.installOffer === true) : ''}${keepsInstallOffer ? `<script>${INSTALL_OFFER}</script>` : ''}${options.dev && options.devTools ? devScripts(client, styled, options.client?.lateStyles === true) + (options.prerendering ? '' : requestBlock(files, rendering, options.base ?? '', options.publicEnv === true)) : ''}</head><body>${body}`
525
528
  const written = opening + sheets + closing
526
529
  const start = marks === undefined ? written : placeFieldMarks(written, marks)
527
530
 
@@ -1,5 +1,5 @@
1
1
  import type { Context } from 'elysia'
2
- import type { KayConfig } from '../config'
2
+ import type { LoadedConfig } from '../config'
3
3
  import type { RenderConfigKey } from '../project'
4
4
  import type { CardPageContext, ErrorPageContext, Locals, PageContext, PageError } from '../runtime'
5
5
  import type { Action, Outcome } from '../runtime/action'
@@ -136,7 +136,7 @@ export interface ServedPage extends Omit<PrerenderedPage, 'pattern' | 'file' | '
136
136
  cut?: CutIslands | undefined
137
137
  }
138
138
 
139
- export interface RenderOptions extends Pick<KayConfig, RenderConfigKey> {
139
+ export interface RenderOptions extends Pick<LoadedConfig, RenderConfigKey | 'publicEnv'> {
140
140
  // Shows thrown errors with their stack instead of a generic message.
141
141
  dev?: boolean | undefined
142
142
  // Loads the dev tool's scripts, which the dev routes serve.
@@ -664,7 +664,7 @@ export async function renderServerIslands(route: ServedRoute, context: RequestCo
664
664
  }
665
665
  }, () => rendering.headers.append('vary', 'cookie'), rules)
666
666
  const chunks = islandChunks(client)
667
- const { deferred, islands: shell } = inScope(() => withServerIslands(islands, () => renderStatic(viewOf(page.modules, page.data), undefined, chunks)))
667
+ const { deferred, islands: shell } = inScope(() => withServerIslands(islands, () => renderStatic(viewOf(page.modules, page.data, undefined, page.files), undefined, chunks)))
668
668
  const unrevivable = unrevivableAction(shell, client)
669
669
 
670
670
  if (unrevivable)