@sixb/core 0.2.3 → 0.2.4

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 (122) hide show
  1. package/dist/actions/index.js +12 -12
  2. package/dist/agents/cancel.d.ts +1 -1
  3. package/dist/agents/cancel.d.ts.map +1 -1
  4. package/dist/agents/child-question.d.ts +35 -2
  5. package/dist/agents/child-question.d.ts.map +1 -1
  6. package/dist/agents/execution.d.ts +1 -1
  7. package/dist/agents/ids.d.ts +2 -0
  8. package/dist/agents/ids.d.ts.map +1 -1
  9. package/dist/agents/index.d.ts +3 -3
  10. package/dist/agents/index.d.ts.map +1 -1
  11. package/dist/agents/index.js +23 -15
  12. package/dist/agents/index.js.map +1 -1
  13. package/dist/agents/model-loop.d.ts.map +1 -1
  14. package/dist/agents/run-session-children.d.ts +9 -0
  15. package/dist/agents/run-session-children.d.ts.map +1 -1
  16. package/dist/agents/run-session-http.d.ts.map +1 -1
  17. package/dist/agents/run-session-serve.d.ts.map +1 -1
  18. package/dist/agents/tool-files.d.ts +1 -1
  19. package/dist/agents/tool-files.d.ts.map +1 -1
  20. package/dist/agents/tool-input-coercion.d.ts +20 -0
  21. package/dist/agents/tool-input-coercion.d.ts.map +1 -0
  22. package/dist/agents/validation.d.ts +1 -1
  23. package/dist/agents/validation.d.ts.map +1 -1
  24. package/dist/artifacts/frames/index.js +1 -1
  25. package/dist/artifacts/frames/protocol.d.ts +53 -2
  26. package/dist/artifacts/frames/protocol.d.ts.map +1 -1
  27. package/dist/artifacts/frames/runtime.d.ts +8 -1
  28. package/dist/artifacts/frames/runtime.d.ts.map +1 -1
  29. package/dist/artifacts/index.d.ts +1 -1
  30. package/dist/artifacts/index.d.ts.map +1 -1
  31. package/dist/artifacts/index.js +27 -1
  32. package/dist/artifacts/index.js.map +3 -3
  33. package/dist/artifacts/live/server.js +7 -7
  34. package/dist/artifacts/publish/index.js +6 -6
  35. package/dist/bootstrap/index.js +17 -17
  36. package/dist/{chunk-k66rp2hr.js → chunk-2bn6813a.js} +1 -1
  37. package/dist/{chunk-m7b9q5dk.js → chunk-3z1vxzcm.js} +1 -1
  38. package/dist/{chunk-qafng88v.js → chunk-6ef4esq4.js} +1 -1
  39. package/dist/{chunk-38yvdqzd.js → chunk-7kpqntgw.js} +1 -1
  40. package/dist/{chunk-tqa68kj7.js → chunk-8bns0y68.js} +2 -2
  41. package/dist/chunk-8t2ynwg0.js.map +1 -1
  42. package/dist/chunk-az95tsh3.js.map +2 -2
  43. package/dist/{chunk-4j0sagwv.js → chunk-evj5jxz3.js} +1 -1
  44. package/dist/{chunk-z0t4p2sk.js → chunk-gxwy4c3s.js} +41 -11
  45. package/dist/{chunk-z0t4p2sk.js.map → chunk-gxwy4c3s.js.map} +8 -8
  46. package/dist/{chunk-qds484t8.js → chunk-hvbvq7p4.js} +202 -12
  47. package/dist/chunk-hvbvq7p4.js.map +18 -0
  48. package/dist/{chunk-26qet7wh.js → chunk-msyevpp3.js} +1 -1
  49. package/dist/chunk-n4zzaf6q.js.map +1 -1
  50. package/dist/{chunk-s5n9617r.js → chunk-p8pgnq8d.js} +3 -3
  51. package/dist/{chunk-kv0kvknv.js → chunk-r9rtavg9.js} +2 -2
  52. package/dist/{chunk-bkmnd7zq.js → chunk-rsrc7vtw.js} +9 -9
  53. package/dist/{chunk-8p7bze4c.js → chunk-rsxb14an.js} +1 -1
  54. package/dist/{chunk-e9w4mgdh.js → chunk-rtm1jq00.js} +162 -17
  55. package/dist/{chunk-e9w4mgdh.js.map → chunk-rtm1jq00.js.map} +8 -7
  56. package/dist/{chunk-7z5rkf0m.js → chunk-t0s7b3d1.js} +4 -3
  57. package/dist/{chunk-7z5rkf0m.js.map → chunk-t0s7b3d1.js.map} +3 -3
  58. package/dist/{chunk-hkaa807g.js → chunk-td26wjr5.js} +1 -1
  59. package/dist/{chunk-6gtxshcc.js → chunk-vepea5c3.js} +3 -3
  60. package/dist/{chunk-2by73sm2.js → chunk-w1wq7gfr.js} +1 -1
  61. package/dist/{chunk-w9s23r24.js → chunk-yy914zfr.js} +3 -3
  62. package/dist/execution/agent.js +12 -12
  63. package/dist/execution/primitive.js +12 -12
  64. package/dist/execution/request.js +12 -12
  65. package/dist/index.js +19 -19
  66. package/dist/materializer/index.js +3 -3
  67. package/dist/models/execution/index.js +3 -3
  68. package/dist/models/language-model.d.ts +6 -0
  69. package/dist/models/language-model.d.ts.map +1 -1
  70. package/dist/models/tools.d.ts +2 -0
  71. package/dist/models/tools.d.ts.map +1 -1
  72. package/dist/objects/index.js +12 -12
  73. package/dist/objects/query/index.js +3 -3
  74. package/dist/pipelines/index.js +3 -3
  75. package/dist/projections/internal.js +2 -2
  76. package/dist/runtime/internal.js +7 -7
  77. package/dist/shares/internal.js +2 -2
  78. package/dist/storage/agents/provider.js +1 -1
  79. package/dist/storage/agents/types.d.ts +1 -1
  80. package/dist/storage/agents/types.d.ts.map +1 -1
  81. package/dist/storage/index.js +2 -2
  82. package/dist/syncs/index.js +4 -4
  83. package/dist/testing/index.js +19 -19
  84. package/dist/webhooks/internal.js +2 -2
  85. package/dist/workflows/index.js +15 -15
  86. package/package.json +1 -1
  87. package/src/agents/approval-outcome.ts +2 -2
  88. package/src/agents/cancel.ts +2 -2
  89. package/src/agents/child-question.ts +76 -8
  90. package/src/agents/execution.ts +1 -1
  91. package/src/agents/ids.ts +4 -1
  92. package/src/agents/index.ts +9 -2
  93. package/src/agents/model-loop.ts +3 -1
  94. package/src/agents/run-session-children.ts +33 -0
  95. package/src/agents/run-session-http.ts +1 -0
  96. package/src/agents/run-session-serve.ts +1 -0
  97. package/src/agents/tool-files.ts +1 -1
  98. package/src/agents/tool-input-coercion.ts +140 -0
  99. package/src/agents/validation.ts +11 -3
  100. package/src/artifacts/frames/protocol.ts +84 -2
  101. package/src/artifacts/frames/runtime.ts +296 -13
  102. package/src/artifacts/index.ts +3 -0
  103. package/src/http/api-routes.ts +1 -1
  104. package/src/models/language-model.ts +6 -0
  105. package/src/models/tools.ts +2 -0
  106. package/src/storage/agents/types.ts +1 -1
  107. package/dist/chunk-qds484t8.js.map +0 -18
  108. /package/dist/{chunk-k66rp2hr.js.map → chunk-2bn6813a.js.map} +0 -0
  109. /package/dist/{chunk-m7b9q5dk.js.map → chunk-3z1vxzcm.js.map} +0 -0
  110. /package/dist/{chunk-qafng88v.js.map → chunk-6ef4esq4.js.map} +0 -0
  111. /package/dist/{chunk-38yvdqzd.js.map → chunk-7kpqntgw.js.map} +0 -0
  112. /package/dist/{chunk-tqa68kj7.js.map → chunk-8bns0y68.js.map} +0 -0
  113. /package/dist/{chunk-4j0sagwv.js.map → chunk-evj5jxz3.js.map} +0 -0
  114. /package/dist/{chunk-26qet7wh.js.map → chunk-msyevpp3.js.map} +0 -0
  115. /package/dist/{chunk-s5n9617r.js.map → chunk-p8pgnq8d.js.map} +0 -0
  116. /package/dist/{chunk-kv0kvknv.js.map → chunk-r9rtavg9.js.map} +0 -0
  117. /package/dist/{chunk-bkmnd7zq.js.map → chunk-rsrc7vtw.js.map} +0 -0
  118. /package/dist/{chunk-8p7bze4c.js.map → chunk-rsxb14an.js.map} +0 -0
  119. /package/dist/{chunk-hkaa807g.js.map → chunk-td26wjr5.js.map} +0 -0
  120. /package/dist/{chunk-6gtxshcc.js.map → chunk-vepea5c3.js.map} +0 -0
  121. /package/dist/{chunk-2by73sm2.js.map → chunk-w1wq7gfr.js.map} +0 -0
  122. /package/dist/{chunk-w9s23r24.js.map → chunk-yy914zfr.js.map} +0 -0
@@ -0,0 +1,140 @@
1
+ import type { JsonObject, JsonValue } from "../json"
2
+
3
+ /**
4
+ * A tool call's arguments as its schema reads them, before the tool's own `parseInput`: the slips
5
+ * models make most, fixed where the schema leaves one reading.
6
+ *
7
+ * ```text
8
+ * null for an optional property that does not allow null left out
9
+ * "42" for a number or an integer, when it fits exactly 42
10
+ * "true" / "false" for a boolean true / false
11
+ * an array as JSON text the array
12
+ * one value for an array [value]
13
+ * ```
14
+ *
15
+ * The `null` is also what a provider's strict mode sends for "nothing" once an adapter rewrites an
16
+ * optional property as required and nullable, so a tool never sees it. Everything else reaches
17
+ * `parseInput` as the model sent it, and a refusal goes back to the model. The call's stored input
18
+ * stays what the model sent, so history replays byte for byte.
19
+ */
20
+ export function coerceToolInput(schema: JsonObject, input: unknown): unknown {
21
+ return coerce(schema, input)
22
+ }
23
+
24
+ function coerce(schema: JsonValue | undefined, value: unknown): unknown {
25
+ if (!isObject(schema)) return value
26
+ const types = schemaTypes(schema)
27
+ if (types.length === 0 || types.some((type) => hasType(value, type))) {
28
+ return coerceInside(schema, value)
29
+ }
30
+
31
+ if (typeof value === "string") {
32
+ const text = value.trim()
33
+ // An integer past what a number holds exactly would change: an id would name its neighbour.
34
+ if (types.includes("integer") && /^-?\d+$/.test(text) && Number.isSafeInteger(Number(text))) {
35
+ return Number(text)
36
+ }
37
+ if (
38
+ types.includes("number") &&
39
+ /^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(text) &&
40
+ Number.isFinite(Number(text))
41
+ ) {
42
+ return Number(text)
43
+ }
44
+ if (types.includes("boolean") && (text === "true" || text === "false")) return text === "true"
45
+ if (types.includes("array") && text.startsWith("[")) {
46
+ const parsed = parseJson(text)
47
+ if (Array.isArray(parsed)) return coerceInside(schema, parsed)
48
+ }
49
+ }
50
+ if (types.includes("array") && value !== null && value !== undefined && !Array.isArray(value)) {
51
+ return [coerce(schema.items, value)]
52
+ }
53
+ return value
54
+ }
55
+
56
+ function parseJson(text: string): unknown {
57
+ try {
58
+ return JSON.parse(text)
59
+ } catch {
60
+ return undefined
61
+ }
62
+ }
63
+
64
+ function coerceInside(schema: JsonObject, value: unknown): unknown {
65
+ if (Array.isArray(value)) {
66
+ return isObject(schema.items) ? value.map((item) => coerce(schema.items, item)) : value
67
+ }
68
+ if (!isPlainObject(value) || !isObject(schema.properties)) return value
69
+
70
+ const properties = schema.properties
71
+ const required = new Set(Array.isArray(schema.required) ? schema.required : [])
72
+ const result: Record<string, unknown> = {}
73
+ for (const [key, item] of Object.entries(value)) {
74
+ const property = Object.hasOwn(properties, key) ? properties[key] : undefined
75
+ if (item === null && property !== undefined && !required.has(key) && !allowsNull(property)) {
76
+ continue
77
+ }
78
+ result[key] = property === undefined ? item : coerce(property, item)
79
+ }
80
+ return result
81
+ }
82
+
83
+ /** The schema's own `type`s; a union (`anyOf`, `oneOf`) is read as it is, never coerced into. */
84
+ function schemaTypes(schema: JsonObject): readonly string[] {
85
+ if (typeof schema.type === "string") return [schema.type]
86
+ if (Array.isArray(schema.type)) {
87
+ return schema.type.filter((type): type is string => typeof type === "string")
88
+ }
89
+ return []
90
+ }
91
+
92
+ function allowsNull(schema: JsonValue): boolean {
93
+ if (schema === true) return true
94
+ if (!isObject(schema)) return false
95
+ if (schemaTypes(schema).includes("null")) return true
96
+ if (schema.const === null || (Array.isArray(schema.enum) && schema.enum.includes(null))) {
97
+ return true
98
+ }
99
+ for (const key of ["anyOf", "oneOf"] as const) {
100
+ const variants = schema[key]
101
+ if (Array.isArray(variants) && variants.some(allowsNull)) return true
102
+ }
103
+ // Nothing that narrows it: any value, null included.
104
+ return (
105
+ schemaTypes(schema).length === 0 &&
106
+ schema.anyOf === undefined &&
107
+ schema.oneOf === undefined &&
108
+ schema.enum === undefined &&
109
+ schema.const === undefined
110
+ )
111
+ }
112
+
113
+ function hasType(value: unknown, type: string): boolean {
114
+ switch (type) {
115
+ case "null":
116
+ return value === null
117
+ case "string":
118
+ return typeof value === "string"
119
+ case "boolean":
120
+ return typeof value === "boolean"
121
+ case "number":
122
+ return typeof value === "number"
123
+ case "integer":
124
+ return Number.isInteger(value)
125
+ case "array":
126
+ return Array.isArray(value)
127
+ case "object":
128
+ return isPlainObject(value)
129
+ default:
130
+ return true
131
+ }
132
+ }
133
+
134
+ function isObject(value: JsonValue | undefined): value is JsonObject {
135
+ return typeof value === "object" && value !== null && !Array.isArray(value)
136
+ }
137
+
138
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
139
+ return typeof value === "object" && value !== null && !Array.isArray(value)
140
+ }
@@ -10,18 +10,26 @@ import { AGENT_WEB_TOOL_NAMES } from "./web"
10
10
  const AGENT_TOOL_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/
11
11
  export const AGENT_RESERVED_TOOL_NAMES = [
12
12
  "bash",
13
+ "wait",
14
+ "stop",
15
+ // What `wait` and `stop` were called for a background command: earlier threads hold calls to them.
13
16
  "bash_output",
14
17
  "bash_stop",
15
18
  "read",
19
+ "edit",
20
+ "write",
16
21
  "view_file",
17
22
  "spawn_agent",
18
- "wait_agent",
19
23
  "message_agent",
24
+ // What `wait` was called for sub-agents: earlier threads hold calls to it.
25
+ "wait_agent",
26
+ "ask",
27
+ // What `ask` was called for a sub-agent: earlier threads hold calls to it.
20
28
  "ask_parent",
21
29
  "publish_artifact",
22
- "update_artifact",
23
30
  "open_artifact",
24
- // What `update_artifact` was called: earlier threads hold calls to it.
31
+ // What `publish_artifact` with an id was called: earlier threads hold calls to them.
32
+ "update_artifact",
25
33
  "publish_artifact_version",
26
34
  ...AGENT_WEB_TOOL_NAMES,
27
35
  ] as const
@@ -64,6 +64,14 @@ export type FrameRequest =
64
64
  * element the reader is typing in takes its patch once they leave it.
65
65
  */
66
66
  | FrameRequestOf<"edit.patch", { readonly patches: readonly BoardFramePatch[] }>
67
+ /**
68
+ * A canvas's board running on the canvas, where the reader uses its page in place. The first
69
+ * request after the frame loads transfers a `MessagePort`: the frame then sends through it alone
70
+ * the reader's gestures the canvas takes (`zoom`, `pan`, `space`) and the words of what they
71
+ * press. `moving` says the canvas is panning by the wheel: a page coming under a still pointer
72
+ * then keeps panning the canvas rather than scrolling itself.
73
+ */
74
+ | FrameRequestOf<"canvas", { readonly moving: boolean }>
67
75
 
68
76
  interface FrameRequestOf<Method extends string, Params> {
69
77
  readonly protocol: typeof FRAME_PROTOCOL
@@ -104,8 +112,9 @@ export type FrameEvent =
104
112
  /** A page's height as laid out at the frame's width, so a document can size the frame to it. */
105
113
  | FrameEventOf<"size", { readonly height: number }>
106
114
  /**
107
- * The reader pressed a button, or a link within the page, that reads `text`: a canvas's opened
108
- * board follows the arrow that leaves it with that label. At most a label's length.
115
+ * The reader pressed a button, or a link within the page, that reads `text`: a canvas's board
116
+ * follows the arrow that leaves it with that label. At most a label's length. A board running on
117
+ * the canvas also sends it through its port, for the reader's own presses alone.
109
118
  */
110
119
  | FrameEventOf<"press", { readonly text: string }>
111
120
  /** Editing, the reader points at an element, or at none. */
@@ -130,6 +139,44 @@ export type FrameEvent =
130
139
  "edit.text",
131
140
  { readonly address: string; readonly base: string; readonly text: string }
132
141
  >
142
+ /**
143
+ * The reader zoomed over a canvas's board, opened or running on the canvas, which the app zooms
144
+ * instead of the browser: a pinch or the wheel with ⌘ or Ctrl, `factor` times around `at`, in
145
+ * the frame's pixels; or ⌘ or Ctrl with +, − or 0, a `step`. Only a frame handed a port with
146
+ * `edit` or `canvas` reports it, through that port, and only for the reader's own gestures and
147
+ * keys; any other leaves them to the browser.
148
+ */
149
+ | FrameEventOf<"zoom", FrameZoom>
150
+ /**
151
+ * The reader turned the wheel or dragged a finger over a board running on the canvas, which pans
152
+ * the canvas instead of scrolling the page. Only a frame handed a port with `canvas` reports it,
153
+ * through that port, for the reader's own gestures.
154
+ */
155
+ | FrameEventOf<"pan", FramePan>
156
+ /**
157
+ * The reader pressed or let go of Space over a board running on the canvas, outside a field:
158
+ * while it is held, dragging pans the canvas. Through the port, as `pan` is.
159
+ */
160
+ | FrameEventOf<"space", { readonly down: boolean }>
161
+
162
+ /**
163
+ * How far the reader scrolled, as a wheel's deltas say it: `x` right and `y` down, in pixels. A
164
+ * finger dragging scrolls the opposite way it moves, as it would scroll a page; the wheel's turns
165
+ * pan the canvas at its own speed for them, as React Flow's do.
166
+ */
167
+ export interface FramePan {
168
+ readonly x: number
169
+ readonly y: number
170
+ readonly by: "wheel" | "touch"
171
+ }
172
+
173
+ /** How the reader zoomed: by a gesture, or by a key. */
174
+ export type FrameZoom =
175
+ | { readonly factor: number; readonly at: FramePoint }
176
+ | { readonly step: FrameZoomStep }
177
+
178
+ /** ⌘ or Ctrl with +, − or 0: in, out, or the page at its own size. */
179
+ export type FrameZoomStep = "in" | "out" | "actual"
133
180
 
134
181
  /**
135
182
  * An element of a board being edited. One a script built, or whose words a script rewrote, is
@@ -374,6 +421,33 @@ export function parseFrameEvent(data: unknown): FrameEvent | null {
374
421
  params.base.length <= MAX_EDIT_TEXT_LENGTH
375
422
  ? event("edit.text", { address: params.address, base: params.base, text: params.text })
376
423
  : null
424
+ case "zoom": {
425
+ if (params.step !== undefined) {
426
+ return ZOOM_STEPS.includes(String(params.step))
427
+ ? event("zoom", { step: params.step as FrameZoomStep })
428
+ : null
429
+ }
430
+
431
+ const at = parsePoint(params.at)
432
+ const factor = Number(params.factor)
433
+ if (!at || !Number.isFinite(params.factor) || factor <= 0) return null
434
+
435
+ return event("zoom", {
436
+ factor: Math.min(MAX_ZOOM_FACTOR, Math.max(1 / MAX_ZOOM_FACTOR, factor)),
437
+ at,
438
+ })
439
+ }
440
+ case "pan": {
441
+ const { x, y, by } = params
442
+ if (!Number.isFinite(x) || !Number.isFinite(y) || (by !== "wheel" && by !== "touch")) {
443
+ return null
444
+ }
445
+
446
+ const bounded = (delta: number) => Math.min(MAX_PAN, Math.max(-MAX_PAN, delta))
447
+ return event("pan", { x: bounded(Number(x)), y: bounded(Number(y)), by })
448
+ }
449
+ case "space":
450
+ return typeof params.down === "boolean" ? event("space", { down: params.down }) : null
377
451
  case "press":
378
452
  return typeof params.text === "string" &&
379
453
  params.text.length > 0 &&
@@ -390,6 +464,14 @@ const MAX_EDIT_TEXT_LENGTH = ARTIFACT_LIMITS.maxBoardBytes
390
464
 
391
465
  const EDIT_KINDS: readonly string[] = ["text", "image", "whole", "box"]
392
466
 
467
+ const ZOOM_STEPS: readonly string[] = ["in", "out", "actual"] satisfies FrameZoomStep[]
468
+
469
+ /** The most one gesture zooms by, either way: a wheel's notch is far less. */
470
+ const MAX_ZOOM_FACTOR = 4
471
+
472
+ /** The most one wheel's turn or one finger's move pans by, either way: a screen's width. */
473
+ const MAX_PAN = 4000
474
+
393
475
  /** The longest label a frame reports for an element: the runtime cuts its own at 80. */
394
476
  const MAX_EDIT_LABEL_LENGTH = 200
395
477
 
@@ -35,7 +35,14 @@
35
35
  * a script rewrote, is reported as scripted and takes nothing. What others change arrives as
36
36
  * patches, element by element; the one the reader is typing in takes its own once they leave it,
37
37
  * so their caret stays. What editing reports goes through the port the app hands over with its
38
- * first `edit` request, taken before the page's scripts run: they cannot post on it.
38
+ * first `edit` request, taken before the page's scripts run: they cannot post on it. Once it holds
39
+ * that port, the frame also sends the reader's pinches, ⌘-wheel turns and ⌘ +, − and 0 through
40
+ * it, for the app to zoom the opened board instead of the browser zooming everything.
41
+ *
42
+ * A board running on the canvas is handed its port with `canvas` instead: the reader uses its page
43
+ * in place, and the frame sends through the port what moves the canvas, their wheel turns unless
44
+ * the page scrolls them, a finger's drag, Space held to drag, and the zooming above, and the words
45
+ * of what they press, for the canvas to follow the arrow they label.
39
46
  */
40
47
  export function frameRuntime(): void {
41
48
  const PROTOCOL = "sixb-frame/1"
@@ -81,6 +88,12 @@ export function frameRuntime(): void {
81
88
  "[data-sixb-commenting] [data-sixb-hover] { outline: 2px dashed #0a84ff; outline-offset: 3px; }",
82
89
  "[data-sixb-commenting] [data-sixb-picked] { outline: 2px solid #0a84ff; outline-offset: 3px; }",
83
90
  ].join(" ")
91
+ /**
92
+ * A board running on the canvas: the page takes no touch gesture of its own, which the canvas
93
+ * takes instead, and its scrolling never carries on to the app around it.
94
+ */
95
+ const CANVAS_CSS =
96
+ "html { overscroll-behavior: none; } html, html * { touch-action: none !important; }"
84
97
  const root = document.documentElement
85
98
  // Only set while the runtime itself runs, so kept for what reads it later.
86
99
  const script = document.currentScript as HTMLScriptElement | null
@@ -221,14 +234,15 @@ export function frameRuntime(): void {
221
234
 
222
235
  // ── Editing a board ─────────────────────────────────────────────────
223
236
 
224
- // What editing reports goes to the app through the port its first `edit` request hands over,
225
- // never through the window, where the page's own scripts post too. The port, and the way to
226
- // post on it, are taken before any of the page's scripts run, which cannot reach either.
237
+ // What editing reports goes to the app through the port its first `edit` request hands over, as
238
+ // a board running on the canvas is handed one with `canvas`, never through the window, where the
239
+ // page's own scripts post too. The port, and the way to post on it, are taken before any of the
240
+ // page's scripts run, which cannot reach either.
227
241
  const portPost = typeof MessagePort === "function" ? MessagePort.prototype.postMessage : undefined
228
242
  const apply = Reflect.apply
229
- let editPort: MessagePort | null = null
230
- const postEdit = (message: Record<string, unknown>) => {
231
- if (editPort && portPost) apply(portPost, editPort, [{ protocol: PROTOCOL, ...message }])
243
+ let appPort: MessagePort | null = null
244
+ const postPort = (message: Record<string, unknown>) => {
245
+ if (appPort && portPost) apply(portPost, appPort, [{ protocol: PROTOCOL, ...message }])
232
246
  }
233
247
 
234
248
  let editing = false
@@ -390,7 +404,7 @@ export function frameRuntime(): void {
390
404
  picked = mark("data-sixb-picked", picked, commentable(element, event.target))
391
405
  // Where the reader clicked, for a comment's pin.
392
406
  const at = { x: event.clientX, y: event.clientY }
393
- postEdit({ event: "edit.select", params: { target, at } })
407
+ postPort({ event: "edit.select", params: { target, at } })
394
408
  if (typable && element instanceof HTMLElement && target.kind === "text") {
395
409
  typing = element
396
410
  typedFrom = element.textContent ?? ""
@@ -406,13 +420,13 @@ export function frameRuntime(): void {
406
420
  const shown = commentable(element, event.target)
407
421
  if (shown === pointed && shown !== null) return
408
422
  pointed = mark("data-sixb-hover", pointed, shown)
409
- postEdit({ event: "edit.hover", params: { target } })
423
+ postPort({ event: "edit.hover", params: { target } })
410
424
  })
411
425
  // The pointer gone from the page, nothing is under it: it left for nothing of the page.
412
426
  document.addEventListener("mouseout", (event) => {
413
427
  if (!editing || !event.isTrusted || event.relatedTarget !== null || pointed === null) return
414
428
  pointed = mark("data-sixb-hover", pointed, null)
415
- postEdit({ event: "edit.hover", params: { target: null } })
429
+ postPort({ event: "edit.hover", params: { target: null } })
416
430
  })
417
431
  document.addEventListener("input", (event) => {
418
432
  if (!editing || !event.isTrusted || !typing || !typing.contains(event.target as Node | null)) {
@@ -421,7 +435,7 @@ export function frameRuntime(): void {
421
435
  const text = typing.textContent ?? ""
422
436
  // Its words are the reader's now: still theirs to type in.
423
437
  typing.setAttribute(WORDS, wordsHash(text))
424
- postEdit({
438
+ postPort({
425
439
  event: "edit.text",
426
440
  params: { address: typing.getAttribute(AT), base: typedFrom, text },
427
441
  })
@@ -442,6 +456,261 @@ export function frameRuntime(): void {
442
456
  if (typing && event.target === typing) stopTyping()
443
457
  })
444
458
 
459
+ // ── The reader's gestures over a canvas's board ─────────────────────
460
+
461
+ // A canvas's board is zoomed by the app around it, never by the browser: once the app has handed
462
+ // the port over, a pinch, the wheel with ⌘ or Ctrl, and ⌘ or Ctrl with +, − or 0 go to the app
463
+ // through it, the reader's own alone. Without a port, as a document's or a deck's frame is, they
464
+ // stay the browser's.
465
+ //
466
+ // A board running on the canvas, handed its port with `canvas`, is a page the reader uses in
467
+ // place among the others: its clicks, keys and text stay its own, and what moves the canvas goes
468
+ // to the app. The wheel pans the canvas unless the page scrolls under the pointer; a finger
469
+ // dragging pans it, while a tap stays the page's; Space held outside a field lets the reader
470
+ // drag the canvas.
471
+ const mac = /Mac|iPhone|iPad/.test(window.navigator?.platform ?? "")
472
+ const zoom = (params: Record<string, unknown>) => postPort({ event: "zoom", params })
473
+ const pan = (x: number, y: number, by: "wheel" | "touch") =>
474
+ postPort({ event: "pan", params: { x, y, by } })
475
+ const forwards = (event: Event) => appPort !== null && event.isTrusted
476
+ let onCanvas = false
477
+ /** The canvas is panning by the wheel, as the app last said. */
478
+ let canvasMoving = false
479
+
480
+ /** How long a wheel's turns are one gesture apart: React Flow's own pause before a pan ends. */
481
+ const WHEEL_GESTURE_MS = 150
482
+ /** Less overflow than this is a page's margins, not content to scroll. */
483
+ const MIN_OVERFLOW = 16
484
+ let wheeledAt = Number.NEGATIVE_INFINITY
485
+ let wheelScrolls = false
486
+
487
+ /** Whether what is under `target`, or the page, scrolls further by `x`, `y`. */
488
+ const scrollsUnder = (target: EventTarget | null, x: number, y: number): boolean => {
489
+ const vertical = Math.abs(y) >= Math.abs(x)
490
+ const delta = vertical ? y : x
491
+ if (delta === 0) return false
492
+
493
+ const overflowOf = (element: Element) =>
494
+ getComputedStyle(element)[vertical ? "overflowY" : "overflowX"]
495
+ const scrolls = (size: number, shown: number, at: number) =>
496
+ size - shown >= MIN_OVERFLOW && (delta > 0 ? at + shown < size - 1 : at > 0)
497
+
498
+ for (
499
+ let element = target instanceof Element ? target : null;
500
+ element && element !== root && element !== document.body;
501
+ element = element.parentElement
502
+ ) {
503
+ if (!/auto|scroll/.test(overflowOf(element))) continue
504
+ const scrolled = vertical
505
+ ? scrolls(element.scrollHeight, element.clientHeight, element.scrollTop)
506
+ : scrolls(element.scrollWidth, element.clientWidth, element.scrollLeft)
507
+ if (scrolled) return true
508
+ }
509
+
510
+ const page = document.scrollingElement
511
+ if (
512
+ !page ||
513
+ [root, document.body].some((each) => each && /hidden|clip/.test(overflowOf(each)))
514
+ ) {
515
+ return false
516
+ }
517
+ return vertical
518
+ ? scrolls(page.scrollHeight, window.innerHeight, window.scrollY)
519
+ : scrolls(page.scrollWidth, window.innerWidth, window.scrollX)
520
+ }
521
+
522
+ window.addEventListener(
523
+ "wheel",
524
+ (event) => {
525
+ if (!forwards(event)) return
526
+
527
+ if (event.ctrlKey || event.metaKey) {
528
+ event.preventDefault()
529
+ // As the canvas zooms by the wheel: a trackpad's pinch is the wheel with Ctrl, in small steps.
530
+ const unit = event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002
531
+ const factor = 2 ** (-event.deltaY * unit * (event.ctrlKey && mac ? 10 : 1))
532
+ zoom({ factor, at: { x: event.clientX, y: event.clientY } })
533
+ return
534
+ }
535
+ if (!onCanvas) return
536
+
537
+ // Lines, as Firefox turns, count as React Flow counts them; Shift turns the wheel sideways
538
+ // where the system doesn't already.
539
+ const unit = event.deltaMode === 1 ? 20 : event.deltaMode === 2 ? window.innerHeight : 1
540
+ const x = (!mac && event.shiftKey ? event.deltaY : event.deltaX) * unit
541
+ const y = !mac && event.shiftKey ? 0 : event.deltaY * unit
542
+
543
+ // A gesture goes one way from its first turn, as a browser keeps scrolling what it started
544
+ // on. The page scrolls it when something under the pointer scrolls that way and the canvas
545
+ // was not panning: a canvas panned under a still pointer keeps panning as a page comes under
546
+ // it, and a page scrolled to its end lets the next gesture pan.
547
+ if (event.timeStamp - wheeledAt > WHEEL_GESTURE_MS) {
548
+ wheelScrolls = !canvasMoving && scrollsUnder(event.target, x, y)
549
+ }
550
+ wheeledAt = event.timeStamp
551
+ if (wheelScrolls) return
552
+
553
+ event.preventDefault()
554
+ pan(x, y, "wheel")
555
+ },
556
+ { passive: false }
557
+ )
558
+
559
+ // Two fingers pinch on a touch screen, measured on the screen: the frame grows as the zoom
560
+ // follows them, so in its own pixels they would seem to close. Safari also tells of a pinch as a
561
+ // gesture of its own, which is only stopped here; on a Mac's trackpad, where no finger touches
562
+ // the page, the gesture is it.
563
+ //
564
+ // On the canvas, one finger dragging past a few pixels pans it, and two pan it by their middle as
565
+ // they pinch: the page takes no touch gesture of its own (`touch-action`), and a tap, which
566
+ // moves less, stays a click on the page.
567
+ const TOUCH_SLOP = 6
568
+ let spread = 0
569
+ /** Where the fingers are on screen, one or two's middle, and whether they drag the canvas yet. */
570
+ let touched: { x: number; y: number; dragging: boolean } | null = null
571
+ const spreadOf = (touches: TouchList) => {
572
+ const [one, two] = [touches[0], touches[1]]
573
+ return one && two ? Math.hypot(one.screenX - two.screenX, one.screenY - two.screenY) : 0
574
+ }
575
+ const middleOf = (touches: TouchList) => {
576
+ const fingers = [touches[0], touches[1]].filter((touch) => touch !== undefined)
577
+ const sum = (axis: "screenX" | "screenY") =>
578
+ fingers.reduce((total, touch) => total + touch[axis], 0) / Math.max(1, fingers.length)
579
+ return { x: sum("screenX"), y: sum("screenY") }
580
+ }
581
+ window.addEventListener(
582
+ "touchstart",
583
+ (event) => {
584
+ const ours = forwards(event)
585
+ spread = ours && event.touches.length === 2 ? spreadOf(event.touches) : 0
586
+ touched =
587
+ ours && onCanvas ? { ...middleOf(event.touches), dragging: event.touches.length > 1 } : null
588
+ },
589
+ { passive: true }
590
+ )
591
+ window.addEventListener(
592
+ "touchmove",
593
+ (event) => {
594
+ if (!forwards(event)) return
595
+
596
+ if (touched && event.touches.length <= 2) {
597
+ // As far as a page would scroll: the other way the fingers move.
598
+ const middle = middleOf(event.touches)
599
+ const x = touched.x - middle.x
600
+ const y = touched.y - middle.y
601
+ if (!touched.dragging && Math.hypot(x, y) < TOUCH_SLOP) return
602
+
603
+ event.preventDefault()
604
+ touched = { ...middle, dragging: true }
605
+ if (x !== 0 || y !== 0) pan(x, y, "touch")
606
+ }
607
+ if (event.touches.length !== 2 || spread === 0) return
608
+ event.preventDefault()
609
+
610
+ const [one, two] = [event.touches[0], event.touches[1]]
611
+ const next = spreadOf(event.touches)
612
+ if (!one || !two || next === 0) return
613
+ zoom({
614
+ factor: next / spread,
615
+ at: { x: (one.clientX + two.clientX) / 2, y: (one.clientY + two.clientY) / 2 },
616
+ })
617
+ spread = next
618
+ },
619
+ { passive: false }
620
+ )
621
+ const untouch = (event: TouchEvent) => {
622
+ if (event.touches.length < 2) spread = 0
623
+ // A finger lifted: the others drag on from where they are, with no jump.
624
+ if (touched)
625
+ touched = event.touches.length > 0 ? { ...middleOf(event.touches), dragging: true } : null
626
+ }
627
+ window.addEventListener("touchend", untouch)
628
+ window.addEventListener("touchcancel", untouch)
629
+
630
+ let gestured = 1
631
+ const onGesture = (event: Event) => {
632
+ if (!forwards(event)) return
633
+ event.preventDefault()
634
+
635
+ const gesture = event as Event & { scale?: number; clientX?: number; clientY?: number }
636
+ const scale = gesture.scale ?? 1
637
+ if (event.type === "gesturestart" || spread > 0 || scale <= 0) {
638
+ gestured = scale > 0 ? scale : 1
639
+ return
640
+ }
641
+ zoom({ factor: scale / gestured, at: { x: gesture.clientX ?? 0, y: gesture.clientY ?? 0 } })
642
+ gestured = scale
643
+ }
644
+ window.addEventListener("gesturestart", onGesture, { passive: false })
645
+ window.addEventListener("gesturechange", onGesture, { passive: false })
646
+
647
+ // Before the page's own keys, and while the reader types in a text.
648
+ window.addEventListener(
649
+ "keydown",
650
+ (event) => {
651
+ if (!forwards(event) || !(event.metaKey || event.ctrlKey) || event.altKey) return
652
+ const step =
653
+ event.key === "=" || event.key === "+"
654
+ ? "in"
655
+ : event.key === "-"
656
+ ? "out"
657
+ : event.key === "0"
658
+ ? "actual"
659
+ : null
660
+ if (!step) return
661
+
662
+ event.preventDefault()
663
+ zoom({ step })
664
+ },
665
+ true
666
+ )
667
+
668
+ // Space, held on the canvas, lets the reader drag it, as anywhere else on it, unless what has the
669
+ // focus takes Space itself: a field types it, a checkbox or a switch toggles. A button or a link
670
+ // the reader clicked keeps Enter: Space let go over it would press it again after the drag.
671
+ const SPACE_TAKERS = [
672
+ "input:not([type=button], [type=submit], [type=reset], [type=image])",
673
+ "textarea",
674
+ "select",
675
+ ...[
676
+ "checkbox",
677
+ "radio",
678
+ "switch",
679
+ "option",
680
+ "menuitemcheckbox",
681
+ "menuitemradio",
682
+ "textbox",
683
+ "searchbox",
684
+ "combobox",
685
+ "slider",
686
+ "spinbutton",
687
+ ].map((role) => `[role=${role}]`),
688
+ ].join(", ")
689
+ let spaceHeld = false
690
+ const holdSpace = (down: boolean) => {
691
+ if (spaceHeld === down) return
692
+ spaceHeld = down
693
+ postPort({ event: "space", params: { down } })
694
+ }
695
+ const onSpace = (event: KeyboardEvent) => {
696
+ if (!onCanvas || !forwards(event) || event.key !== " ") return
697
+ if (event.metaKey || event.ctrlKey || event.altKey) return
698
+
699
+ const down = event.type === "keydown"
700
+ const focused = document.activeElement
701
+ if (down && focused instanceof HTMLElement) {
702
+ if (focused.isContentEditable || focused.matches(SPACE_TAKERS)) return
703
+ }
704
+ if (!down && !spaceHeld) return
705
+
706
+ event.preventDefault()
707
+ event.stopPropagation()
708
+ holdSpace(down)
709
+ }
710
+ window.addEventListener("keydown", onSpace, true)
711
+ window.addEventListener("keyup", onSpace, true)
712
+ window.addEventListener("blur", () => holdSpace(false))
713
+
445
714
  const handle = (method: string, params: Record<string, unknown>) => {
446
715
  switch (method) {
447
716
  case "theme": {
@@ -496,6 +765,16 @@ export function frameRuntime(): void {
496
765
  case "edit":
497
766
  startEditing(params.on === true, params.typing !== false)
498
767
  return
768
+ case "canvas":
769
+ onCanvas = true
770
+ canvasMoving = params.moving === true
771
+ if (!document.getElementById("sixb-canvas")) {
772
+ const style = document.createElement("style")
773
+ style.id = "sixb-canvas"
774
+ style.textContent = CANVAS_CSS
775
+ document.head.append(style)
776
+ }
777
+ return
499
778
  case "edit.patch": {
500
779
  const patches = Array.isArray(params.patches) ? params.patches : []
501
780
  for (const patch of patches as Record<string, unknown>[]) {
@@ -649,7 +928,7 @@ export function frameRuntime(): void {
649
928
  if (typeof data.method !== "string") return
650
929
  event.stopImmediatePropagation()
651
930
  const port = event.ports?.[0]
652
- if (data.method === "edit" && port) editPort = port
931
+ if ((data.method === "edit" || data.method === "canvas") && port) appPort = port
653
932
  try {
654
933
  handle(String(data.method), (data.params ?? {}) as Record<string, unknown>)
655
934
  post({ id: data.id })
@@ -677,7 +956,11 @@ export function frameRuntime(): void {
677
956
  // arrow they label.
678
957
  const pressed = target?.closest<HTMLElement>('button, [role="button"], a[href^="#"]')
679
958
  const words = (pressed?.innerText ?? pressed?.textContent ?? "").replace(/\s+/g, " ").trim()
680
- if (words && words.length <= MAX_LABEL_LENGTH) post({ event: "press", params: { text: words } })
959
+ if (words && words.length <= MAX_LABEL_LENGTH) {
960
+ post({ event: "press", params: { text: words } })
961
+ // On the canvas, the reader's own press also goes through the port, where no script posts.
962
+ if (onCanvas && event.isTrusted) postPort({ event: "press", params: { text: words } })
963
+ }
681
964
 
682
965
  const link = target?.closest<HTMLAnchorElement>("a[href]")
683
966
  if (link) {