@kayjs/kay 1.109.0 → 1.110.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 (115) hide show
  1. package/dist/eslint.js +332 -52
  2. package/editors/zed/extension.toml +2 -2
  3. package/llms/actions-from-islands.md +1 -1
  4. package/llms/components.md +1 -1
  5. package/llms/deprecated-lints.md +1 -1
  6. package/llms/island-and-form-lints.md +2 -1
  7. package/llms/islands.md +4 -2
  8. package/llms/live-values.md +1 -1
  9. package/llms/navigation-from-code.md +1 -1
  10. package/llms/navigation.md +4 -2
  11. package/llms/templates-elements-slots-snippets.md +2 -2
  12. package/llms/upgrading-archive.md +31 -1
  13. package/llms/upgrading.md +26 -32
  14. package/llms/whats-new.md +15 -0
  15. package/llms.txt +1 -1
  16. package/package.json +6 -6
  17. package/src/build/variants.ts +132 -18
  18. package/src/check/env-types.ts +1 -1
  19. package/src/check/project.ts +4 -0
  20. package/src/check/schema-builders.ts +125 -26
  21. package/src/commands/upgrade.ts +2 -1
  22. package/src/compiler/allow-comments.ts +38 -2
  23. package/src/compiler/ast.ts +4 -4
  24. package/src/compiler/codegen.ts +3 -3
  25. package/src/compiler/deprecated-lints-1-106.ts +2 -2
  26. package/src/compiler/hand-parts.ts +36 -8
  27. package/src/compiler/helper-imports.ts +2 -2
  28. package/src/compiler/index.ts +4 -3
  29. package/src/compiler/island-arguments.ts +9 -0
  30. package/src/compiler/island-lints.ts +7 -0
  31. package/src/compiler/items.ts +12 -0
  32. package/src/compiler/jsx.ts +5 -4
  33. package/src/compiler/lints.ts +5 -6
  34. package/src/compiler/markup.ts +16 -21
  35. package/src/compiler/names.ts +1 -1
  36. package/src/compiler/removed-lints.ts +90 -0
  37. package/src/compiler/signal-from-prop.ts +141 -0
  38. package/src/compiler/template-reads.ts +16 -0
  39. package/src/runtime/checks.ts +14 -2
  40. package/src/runtime/client.ts +5 -9
  41. package/src/runtime/dom.ts +1 -1
  42. package/src/runtime/html.ts +1 -1
  43. package/src/runtime/image.ts +2 -19
  44. package/src/runtime/index.ts +1 -1
  45. package/src/runtime/island.server.ts +40 -10
  46. package/src/runtime/navigate.ts +9 -0
  47. package/src/runtime/navigation.ts +5 -1
  48. package/src/runtime/page-swap.ts +2 -2
  49. package/src/runtime/swap-flight.ts +10 -10
  50. package/src/runtime/swap-kept.ts +69 -29
  51. package/src/runtime/swap-morph.ts +49 -9
  52. package/src/runtime/text-hash.ts +17 -0
  53. package/src/runtime/uid.server.ts +6 -4
  54. package/src/runtime/values.ts +12 -0
  55. package/src/server/render-document.ts +8 -6
  56. package/src/server/render.ts +1 -1
  57. package/types/build/variants.d.ts +9 -1
  58. package/types/build/variants.d.ts.map +1 -1
  59. package/types/check/project.d.ts.map +1 -1
  60. package/types/check/schema-builders.d.ts.map +1 -1
  61. package/types/commands/upgrade.d.ts.map +1 -1
  62. package/types/compiler/allow-comments.d.ts +2 -0
  63. package/types/compiler/allow-comments.d.ts.map +1 -1
  64. package/types/compiler/ast.d.ts +1 -1
  65. package/types/compiler/ast.d.ts.map +1 -1
  66. package/types/compiler/deprecated-lints-1-106.d.ts +2 -2
  67. package/types/compiler/deprecated-lints-1-106.d.ts.map +1 -1
  68. package/types/compiler/deprecated-lints.d.ts +2 -2
  69. package/types/compiler/hand-parts.d.ts +6 -3
  70. package/types/compiler/hand-parts.d.ts.map +1 -1
  71. package/types/compiler/index.d.ts.map +1 -1
  72. package/types/compiler/island-arguments.d.ts +5 -0
  73. package/types/compiler/island-arguments.d.ts.map +1 -1
  74. package/types/compiler/island-lints.d.ts +7 -0
  75. package/types/compiler/island-lints.d.ts.map +1 -1
  76. package/types/compiler/items.d.ts +1 -0
  77. package/types/compiler/items.d.ts.map +1 -1
  78. package/types/compiler/jsx.d.ts.map +1 -1
  79. package/types/compiler/lints.d.ts +11 -4
  80. package/types/compiler/lints.d.ts.map +1 -1
  81. package/types/compiler/markup.d.ts +1 -1
  82. package/types/compiler/markup.d.ts.map +1 -1
  83. package/types/compiler/names.d.ts.map +1 -1
  84. package/types/compiler/removed-lints.d.ts +3 -0
  85. package/types/compiler/removed-lints.d.ts.map +1 -0
  86. package/types/compiler/signal-from-prop.d.ts +4 -0
  87. package/types/compiler/signal-from-prop.d.ts.map +1 -0
  88. package/types/compiler/template-reads.d.ts +1 -0
  89. package/types/compiler/template-reads.d.ts.map +1 -1
  90. package/types/runtime/checks.d.ts +8 -2
  91. package/types/runtime/checks.d.ts.map +1 -1
  92. package/types/runtime/client.d.ts.map +1 -1
  93. package/types/runtime/dom.d.ts +1 -1
  94. package/types/runtime/dom.d.ts.map +1 -1
  95. package/types/runtime/html.d.ts +1 -1
  96. package/types/runtime/html.d.ts.map +1 -1
  97. package/types/runtime/image.d.ts.map +1 -1
  98. package/types/runtime/index.d.ts +1 -1
  99. package/types/runtime/index.d.ts.map +1 -1
  100. package/types/runtime/island.server.d.ts +1 -0
  101. package/types/runtime/island.server.d.ts.map +1 -1
  102. package/types/runtime/navigate.d.ts.map +1 -1
  103. package/types/runtime/navigation.d.ts +2 -0
  104. package/types/runtime/navigation.d.ts.map +1 -1
  105. package/types/runtime/swap-flight.d.ts +1 -1
  106. package/types/runtime/swap-flight.d.ts.map +1 -1
  107. package/types/runtime/swap-kept.d.ts.map +1 -1
  108. package/types/runtime/swap-morph.d.ts.map +1 -1
  109. package/types/runtime/text-hash.d.ts +2 -0
  110. package/types/runtime/text-hash.d.ts.map +1 -0
  111. package/types/runtime/uid.server.d.ts.map +1 -1
  112. package/types/runtime/values.d.ts +4 -0
  113. package/types/runtime/values.d.ts.map +1 -1
  114. package/types/server/render-document.d.ts +1 -1
  115. package/types/server/render-document.d.ts.map +1 -1
@@ -0,0 +1,141 @@
1
+ import type { Diagnostic, Fix } from './ast'
2
+ import type { Node, NodeOfType } from './estree'
3
+ import type { ParsedFence, PropsDeclaration } from './script'
4
+ import { eachNode } from './each-node'
5
+ import { INITIAL_PROP } from './live-reads'
6
+ import { patternNames } from './pattern-names'
7
+
8
+ type ImportSpecifier = NodeOfType<'ImportSpecifier'>
9
+
10
+ const KAY = 'kay'
11
+
12
+ // The name a prop is read by, through a chain of plain properties (`todo.title`), or undefined for any other expression.
13
+ function propRoot(node: Node): string | undefined {
14
+ if (node.type === 'Identifier')
15
+ return node.name
16
+
17
+ return node.type === 'MemberExpression' && !node.computed && node.property.type === 'Identifier' ? propRoot(node.object) : undefined
18
+ }
19
+
20
+ function importedAs(node: Node, name: string): node is ImportSpecifier {
21
+ return node.type === 'ImportSpecifier' && node.importKind !== 'type' && node.local.name === name && (node.imported.type === 'Identifier' ? node.imported.name : node.imported.value) === name
22
+ }
23
+
24
+ // The names an `effect` writes, `effect(() => shown = open)` or `shown.set(open)`: a signal it follows needs no `linked`.
25
+ function followedByEffects(ast: Node): Set<string> {
26
+ const names = new Set<string>()
27
+
28
+ eachNode(ast, (node) => {
29
+ if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier' || node.callee.name !== 'effect')
30
+ return
31
+
32
+ eachNode(node, (inner) => {
33
+ if (inner.type === 'AssignmentExpression' && inner.left.type === 'Identifier')
34
+ names.add(inner.left.name)
35
+
36
+ if (inner.type === 'CallExpression' && inner.callee.type === 'MemberExpression' && inner.callee.property.type === 'Identifier' && inner.callee.property.name === 'set' && inner.callee.object.type === 'Identifier')
37
+ names.add(inner.callee.object.name)
38
+ })
39
+
40
+ return false
41
+ })
42
+
43
+ return names
44
+ }
45
+
46
+ // The names the script writes outside an `effect`: `name = value`, `name += 1` or `name.set(...)`, `.update(...)`.
47
+ function writtenNames(ast: Node): Set<string> {
48
+ const names = new Set<string>()
49
+
50
+ eachNode(ast, (node) => {
51
+ if (node.type === 'AssignmentExpression' && node.left.type === 'Identifier')
52
+ names.add(node.left.name)
53
+
54
+ if (node.type === 'UpdateExpression' && node.argument.type === 'Identifier')
55
+ names.add(node.argument.name)
56
+
57
+ if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression' && node.callee.object.type === 'Identifier' && node.callee.property.type === 'Identifier' && (node.callee.property.name === 'set' || node.callee.property.name === 'update'))
58
+ names.add(node.callee.object.name)
59
+ })
60
+
61
+ return names
62
+ }
63
+
64
+ // A `signal(prop)` at the top of an island's script that the island never writes: the signal takes the prop's value when the component is created, so it keeps the first one when the page gives the island another, as a refresh does while the island stays. `linked(() => prop)` is the signal that follows its source. A signal the island writes (a counter starting from a prop) is its own state and is left alone.
65
+ // A prop named as a seed (`initial...`, `default...`) is meant to be read once, and a name declared again in the script is left alone.
66
+ export function signalFromProps(fence: ParsedFence, props: PropsDeclaration | undefined, writtenInTemplate: ReadonlySet<string>): Diagnostic[] {
67
+ if (!props || !fence.code.includes('signal'))
68
+ return []
69
+
70
+ const watched = new Set(props.bindings.filter(binding => !INITIAL_PROP.test(binding.key)).map(binding => fence.code.slice(binding.local.start - fence.offset, binding.local.end - fence.offset)))
71
+ const declaration = fence.ast.body.find(node => node.type === 'ImportDeclaration' && node.source.value === KAY && node.importKind !== 'type')
72
+ const specifier = declaration?.type === 'ImportDeclaration' ? declaration.specifiers.find(node => importedAs(node, 'signal')) : undefined
73
+
74
+ if (watched.size === 0 || specifier?.type !== 'ImportSpecifier')
75
+ return []
76
+
77
+ const linked = declaration?.type === 'ImportDeclaration' && declaration.specifiers.some(node => importedAs(node, 'linked'))
78
+ let others = 0
79
+ let taken = false
80
+ const seeds: { call: NodeOfType<'CallExpression'>, name: string | undefined }[] = []
81
+
82
+ eachNode(fence.ast, (node) => {
83
+ if (node.type === 'ImportDeclaration' || (node.type === 'VariableDeclaration' && fence.shift(node).start === props.statement.start))
84
+ return false
85
+
86
+ // A parameter of a function in the script is its own value, not the prop.
87
+ if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
88
+ for (const param of node.params) {
89
+ for (const name of patternNames(param))
90
+ watched.delete(name)
91
+ }
92
+ }
93
+
94
+ if (node.type === 'VariableDeclarator') {
95
+ for (const name of patternNames(node.id)) {
96
+ watched.delete(name)
97
+ taken ||= name === 'linked'
98
+ }
99
+
100
+ const { init } = node
101
+
102
+ if (init?.type === 'CallExpression' && init.callee.type === 'Identifier' && init.callee.name === 'signal' && init.arguments.length === 1 && init.arguments[0]!.type !== 'SpreadElement')
103
+ seeds.push({ call: init, name: node.id.type === 'Identifier' ? node.id.name : undefined })
104
+ }
105
+
106
+ if (node.type === 'Identifier' && node.name === 'signal')
107
+ others++
108
+
109
+ return true
110
+ })
111
+
112
+ const diagnostics: Diagnostic[] = []
113
+ const followed = followedByEffects(fence.ast)
114
+ const written = writtenNames(fence.ast)
115
+ const found = seeds.filter(({ call, name }) => {
116
+ // A seed the island writes is its own state, which starts from the prop by intent, as a counter does.
117
+ const root = call.typeArguments || (name !== undefined && (followed.has(name) || written.has(name) || writtenInTemplate.has(name))) ? undefined : propRoot(call.arguments[0]!)
118
+
119
+ return root !== undefined && watched.has(root)
120
+ })
121
+
122
+ for (const { call } of found) {
123
+ const seed = call.arguments[0]!
124
+ const root = propRoot(seed)!
125
+ const text = fence.code.slice(seed.start, seed.end)
126
+ const imports: Fix['edits'] = linked || taken ? [] : [{ ...fence.shift(specifier), text: others > found.length ? 'linked, signal' : 'linked' }]
127
+ const fix: Fix = { title: `Write \`linked(() => ${text})\``, safe: !taken, edits: [{ ...fence.shift(call), text: `linked(() => ${text})` }, ...imports] }
128
+
129
+ diagnostics.push({
130
+ ...fence.shift(call),
131
+ code: 'signal-from-prop',
132
+ message: `\`signal(${text})\` keeps the first value of \`${root}\`, as a signal made from a prop does not follow it`,
133
+ note: 'the island stays when the page gives it new props, as after an action or a refresh, so a seed read once shows the old value',
134
+ help: `write \`linked(() => ${text})\`, which follows the prop and can still be written, or \`// kay-allow signal-from-prop\` when the first value is meant`,
135
+ checkOnly: true,
136
+ fixes: taken ? [] : [fix],
137
+ })
138
+ }
139
+
140
+ return diagnostics
141
+ }
@@ -173,6 +173,22 @@ export function templateWords(file: KayFile): string[] {
173
173
  return [...words]
174
174
  }
175
175
 
176
+ // The names the template's expressions write, `count = 1`, `count += 1`, `count++` or `count.set(...)`; it over-approximates, a word before `=` in any expression counts.
177
+ const WRITE = /([\w$]+)\s*(?:\.(?:set|update)\s*\(|(?:\*\*|<<|>>>?|&&|\|\||\?\?|[-+*/%&|^])?=(?![=>])|\+\+|--)|(?:\+\+|--)\s*([\w$]+)/g
178
+
179
+ export function templateWrites(file: KayFile): Set<string> {
180
+ const names = new Set<string>()
181
+
182
+ visitNodes(file.template, (node) => {
183
+ for (const span of nodeExpressions(node)) {
184
+ for (const [, after, before] of file.source.slice(span.start, span.end).matchAll(WRITE))
185
+ names.add((after ?? before)!)
186
+ }
187
+ })
188
+
189
+ return names
190
+ }
191
+
176
192
  // The child blocks of a node with the spans naming what each sees besides its parent's names: a loop's item and index, a snippet's or slot's parameters, a branch's alias.
177
193
  export function scopedBlocks(node: Node): [Node[], Span[]][] {
178
194
  switch (node.kind) {
@@ -43,6 +43,17 @@ export type BoundValue<Tag, Key> = Key extends keyof PropsOfComponent<Tag> ? Mar
43
43
  // Lets the checker tell islands from plain components.
44
44
  export interface IslandBrand { readonly [ISLAND]: true }
45
45
 
46
+ declare const ASKED: unique symbol
47
+
48
+ // What an island lists in `island({ interactive })`, kept in its type so a use that turns none of those props on is known to render as plain markup, which takes a function.
49
+ export interface IslandAsked<Interactive extends Readonly<Record<string, boolean>>> { readonly [ASKED]: Interactive }
50
+
51
+ // The props that make a use an island whatever the component lists.
52
+ type IslandOptionKeys = 'hydrate' | 'persist' | 'render' | 'fallback'
53
+
54
+ // Whether a use naming these props turns none of the component's interactive ones on: a prop it may leave out is on by default, and a spread, which names nothing, may carry any.
55
+ type StaysPlain<Component, Used> = Component extends IslandAsked<infer Interactive> ? true extends Interactive[keyof Interactive] ? false : [Used & (keyof Interactive | IslandOptionKeys)] extends [never] ? true : false : false
56
+
46
57
  // What an interactive component's default export is; only islands take `hydrate`.
47
58
  // What a static parent passes an island besides its props: when it hydrates, and whether it lives on across navigations, `persist` keeping it by its component, `persist="key"` by a key of its own.
48
59
  // `fallback` is the markup a client-only use shows on the server until the browser renders the island, written as an `@fallback` block: it reaches the island under a key of kay's own, so a component's `fallback` prop of another kind is its own.
@@ -328,7 +339,8 @@ export type PlainIslandProp<Component, Value> = Component extends IslandBrand ?
328
339
  export type SlotCall = (...args: any[]) => JSX.Element
329
340
 
330
341
  // A function written in the attribute is checked apart from its value, which a wrapping call would stop a generic component from typing: `0` stands for the attribute.
331
- export type FunctionProp<Component> = Component extends IslandBrand ? { kayLint: 'island-prop', kayAlways: true, kayError: Unsendable } : 0
342
+ // `Names` is the props the use writes, as an object type: a use turning no interactive prop of an island on is plain markup, which takes a function.
343
+ export type FunctionProp<Component, Names extends object = Record<string, unknown>> = Component extends IslandBrand ? true extends StaysPlain<Component, keyof Names> ? 0 : { kayLint: 'island-prop', kayAlways: true, kayError: Unsendable } : 0
332
344
 
333
345
  // What `defer()` returns, a plain promise: an `await` block takes any promise, so nothing marks one.
334
346
  export type Deferred<T> = Promise<T>
@@ -375,7 +387,7 @@ export interface TemplateHelpers {
375
387
  componentClass: <const List extends readonly unknown[]>(list: List) => ComponentClass<List>
376
388
  partClass: (props: unknown, part: string) => unknown
377
389
  partHanded: (part: string, list: readonly unknown[]) => unknown
378
- partsClass: (list: readonly unknown[]) => unknown
390
+ partProps: (read: () => readonly [list: readonly unknown[], written?: unknown]) => unknown
379
391
  handParts: (list: readonly unknown[], written?: unknown) => unknown
380
392
  omit: <Props extends object, Key extends keyof Props>(props: Props, ...keys: Key[]) => Omit<Props, Key>
381
393
  head: (tags: { tag: string, props: Record<string, unknown> }[]) => void
@@ -3,6 +3,7 @@ import { reviveActionsIn } from './action-revive'
3
3
  import { withBase } from './base'
4
4
  import { skew } from './build'
5
5
  import { dispatch, hydrate, render } from './dom'
6
+ import { liveProps } from './live-props'
6
7
  import { HYDRATED, ISLAND } from './markers'
7
8
  import { flush, recordSignals, reportError, root, setErrorReporter } from './reactive'
8
9
  import { savesDataInBrowser } from './save-data'
@@ -225,10 +226,10 @@ async function hydrateIsland(registry: IslandRegistry, element: HTMLElement): Pr
225
226
  return
226
227
  }
227
228
 
228
- let loaded: [Awaited<ReturnType<IslandRegistry[string]>>, Awaited<ReturnType<typeof staticSlots>>, Awaited<ReturnType<typeof livePropsOf>>, void | undefined]
229
+ let loaded: [Awaited<ReturnType<IslandRegistry[string]>>, Awaited<ReturnType<typeof staticSlots>>, void | undefined]
229
230
 
230
231
  try {
231
- loaded = await Promise.all([load(), staticSlots(registry, element), livePropsOf(element), reviveActionsIn(element.dataset.props)])
232
+ loaded = await Promise.all([load(), staticSlots(registry, element), reviveActionsIn(element.dataset.props)])
232
233
 
233
234
  // What the server drew of its lazy components loads first, so the markup is claimed as it stands.
234
235
  const drawn = (globalThis as { $kayLoadDrawn?: (island: HTMLElement) => Promise<void> }).$kayLoadDrawn
@@ -246,7 +247,7 @@ async function hydrateIsland(registry: IslandRegistry, element: HTMLElement): Pr
246
247
  throw error
247
248
  }
248
249
 
249
- const [{ default: component }, slots, live] = loaded
250
+ const [{ default: component }, slots] = loaded
250
251
 
251
252
  // A page swap took it away while its chunk loaded: hydrated now, its effects would outlive it. One in a static slot its island hid hydrates as it shows it again.
252
253
  if (!element.isConnected) {
@@ -256,7 +257,7 @@ async function hydrateIsland(registry: IslandRegistry, element: HTMLElement): Pr
256
257
  }
257
258
 
258
259
  const given = element.dataset.props === undefined ? {} : decodeServerValue(element.dataset.props) as Record<string, unknown>
259
- const [props, update] = live ? live(given) : [given, undefined]
260
+ const [props, update] = liveProps(given)
260
261
 
261
262
  for (const [key, slot] of Object.entries(slots))
262
263
  Object.defineProperty(props, key, { value: slot, enumerable: true, configurable: true })
@@ -316,11 +317,6 @@ async function hydrateIsland(registry: IslandRegistry, element: HTMLElement): Pr
316
317
  element.dispatchEvent(new Event(HYDRATED))
317
318
  }
318
319
 
319
- // Its own chunk, which only a page holding a persistent island loads: the one kind of island the next page gives other props to.
320
- async function livePropsOf(element: HTMLElement): Promise<typeof import('./live-props').liveProps | undefined> {
321
- return element.dataset.persist === undefined ? undefined : (await import('./live-props')).liveProps
322
- }
323
-
324
320
  // The static slots a static parent gave the island, whose code only a page holding such an island loads.
325
321
  async function staticSlots(registry: IslandRegistry, element: HTMLElement): Promise<Record<string, () => Node[]>> {
326
322
  return element.dataset.slots === undefined ? {} : (await import('./static-slots')).islandSlots(element, root => void hydrateIslands(registry, root))
@@ -21,7 +21,7 @@ declare const KAY_FRENCH: true | undefined
21
21
  export { holdSubmits, listenSubmit, listenSubmitWith, listenWith } from './form-hold'
22
22
  export { renderEffect as effect, memo, untrack } from './reactive'
23
23
  export { transition } from './transition'
24
- export { checkedMarkup, componentClass, handParts, merge, omit, partClass, partHanded, partsClass, spreadAttributes, spreadWith } from './values'
24
+ export { checkedMarkup, componentClass, handParts, merge, omit, partClass, partHanded, partProps, spreadAttributes, spreadWith } from './values'
25
25
 
26
26
  // Several sibling nodes rendered as one: a block or a component returning more than one node. Its first and last nodes stay in place while what sits between changes.
27
27
  export class Range {
@@ -35,7 +35,7 @@ export { memo, untrack } from './reactive'
35
35
  export { html, isRendered } from './rendered'
36
36
 
37
37
  export type { Html } from './rendered'
38
- export { checkedMarkup, componentClass, handParts, merge, omit, partClass, partHanded, partsClass, spreadWith } from './values'
38
+ export { checkedMarkup, componentClass, handParts, merge, omit, partClass, partHanded, partProps, spreadWith } from './values'
39
39
 
40
40
  // Leads the markup of a `try` block the server rendered its `catch` block for.
41
41
  export const FAILED_MARKER = `<!--${FAILED}-->`
@@ -1,5 +1,6 @@
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
5
6
 
@@ -265,25 +266,7 @@ export function requestedRemoteVariants(): { src: string, name: string, variant:
265
266
 
266
267
  // Named after a hash of the URL.
267
268
  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)
269
+ return `remote-${textHash(src)}${variantSuffix(variant)}`
287
270
  }
288
271
 
289
272
  function currentMaxDensity(): number {
@@ -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'
@@ -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, 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 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,7 @@ 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)
75
76
  window.addEventListener('popstate', onPopState)
76
77
  // `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
78
  window.addEventListener('scroll', onScroll, { passive: true })
@@ -90,6 +91,14 @@ async function loadFormSubmits(): Promise<typeof import('./form-submits')> {
90
91
  return typeof KAY_NAV_ENTRY === 'undefined' ? formsModule ??= import('./form-submits') : Promise.reject(new Error('unreachable'))
91
92
  }
92
93
 
94
+ // Notes what a `details` showed before its visitor first toggled it, which a refresh compares with the server's.
95
+ function onToggle(event: Event): void {
96
+ const details = event.target
97
+
98
+ if (details instanceof HTMLDetailsElement && !navigation.written.delete(details) && !navigation.opened.has(details))
99
+ navigation.opened.set(details, !details.open)
100
+ }
101
+
93
102
  // Until the forms' listener runs, which then takes the forms a swap brings or a focus lands in itself.
94
103
  function wakeShownForms(): void {
95
104
  if (!formsListen && document.forms.length > 0)
@@ -117,7 +117,11 @@ export const navigation: {
117
117
  traversed?: (state: unknown) => boolean
118
118
  // 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
119
  typed?: boolean
120
- } = { shown: '', at: 0, page: 0, current: 0, released: false, loads: 0 }
120
+ // 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.
121
+ opened: WeakMap<Element, boolean>
122
+ // The `details` whose `open` a swap just wrote, so the `toggle` it fires is not taken for the visitor's.
123
+ written: WeakSet<Element>
124
+ } = { shown: '', at: 0, page: 0, current: 0, released: false, loads: 0, opened: new WeakMap(), written: new WeakSet() }
121
125
 
122
126
  // Run once a swap to another path is shown: what an action streams to a caller no island owns closes there.
123
127
  export const leaving = new Set<() => void>()
@@ -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,7 @@ 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
443
 
444
444
  try {
445
445
  swapBody(next, policy, held, left)
@@ -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>