@johnoscott/isometric-engine 0.0.0-stage → 0.9.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 (310) hide show
  1. package/EDITOR-GUIDE.md +317 -0
  2. package/LICENSE +21 -0
  3. package/LICENSES/ajv.txt +22 -0
  4. package/LICENSES/lucide-static.txt +43 -0
  5. package/LICENSES/yaml.txt +13 -0
  6. package/README.md +62 -2
  7. package/assets/app.css +265 -0
  8. package/assets/default-theme.yaml +99 -0
  9. package/assets/icons.svg +1 -0
  10. package/assets/marks.css +35 -0
  11. package/assets/skin.css +181 -0
  12. package/iso-editor.d.ts +4 -0
  13. package/iso-editor.js +550 -0
  14. package/iso-render.d.ts +3 -0
  15. package/iso-render.js +388 -0
  16. package/iso-systems.d.ts +4 -0
  17. package/iso-systems.js +389 -0
  18. package/js/iso-core/compile-schema.js +22 -0
  19. package/js/iso-core/depth.js +55 -0
  20. package/js/iso-core/errors.js +65 -0
  21. package/js/iso-core/glyphs.js +100 -0
  22. package/js/iso-core/index.js +55 -0
  23. package/js/iso-core/kernel.js +158 -0
  24. package/js/iso-core/metrics.json +1 -0
  25. package/js/iso-core/package.json +6 -0
  26. package/js/iso-core/parse.js +79 -0
  27. package/js/iso-core/schema-errors.js +170 -0
  28. package/js/iso-core/shims/crypto.js +125 -0
  29. package/js/iso-core/shims/path.js +49 -0
  30. package/js/iso-core/svg-dom.js +144 -0
  31. package/js/iso-core/theme.js +48 -0
  32. package/js/iso-core/vdom.js +48 -0
  33. package/js/iso-editor/adapter.js +0 -0
  34. package/js/iso-editor/clipboard.js +152 -0
  35. package/js/iso-editor/commands.js +173 -0
  36. package/js/iso-editor/complete.js +55 -0
  37. package/js/iso-editor/doc.js +182 -0
  38. package/js/iso-editor/index.js +105 -0
  39. package/js/iso-editor/model.js +210 -0
  40. package/js/iso-editor/outline.js +111 -0
  41. package/js/iso-editor/package.json +6 -0
  42. package/js/iso-editor/path.js +19 -0
  43. package/js/iso-editor/providers.js +96 -0
  44. package/js/iso-editor/schema-nav.js +117 -0
  45. package/js/iso-editor/splice.js +441 -0
  46. package/js/iso-editor/storage-keys.js +6 -0
  47. package/js/iso-editor/ui/actions.js +116 -0
  48. package/js/iso-editor/ui/canvas-layer.js +0 -0
  49. package/js/iso-editor/ui/canvas.js +1205 -0
  50. package/js/iso-editor/ui/clip.js +133 -0
  51. package/js/iso-editor/ui/dialog.js +26 -0
  52. package/js/iso-editor/ui/flat-canvas.js +54 -0
  53. package/js/iso-editor/ui/icons.js +15 -0
  54. package/js/iso-editor/ui/keys.js +26 -0
  55. package/js/iso-editor/ui/later.js +28 -0
  56. package/js/iso-editor/ui/layer.js +11 -0
  57. package/js/iso-editor/ui/menu.js +105 -0
  58. package/js/iso-editor/ui/monaco-entry.js +2 -0
  59. package/js/iso-editor/ui/mount-kit.js +0 -0
  60. package/js/iso-editor/ui/mount.js +767 -0
  61. package/js/iso-editor/ui/pane.js +0 -0
  62. package/js/iso-editor/ui/part.js +0 -0
  63. package/js/iso-editor/ui/plain-icons.js +34 -0
  64. package/js/iso-editor/ui/props.js +314 -0
  65. package/js/iso-editor/ui/scope-css.js +81 -0
  66. package/js/iso-editor/ui/setup.js +145 -0
  67. package/js/iso-editor/ui/text.js +323 -0
  68. package/js/iso-editor/ui/tree.js +728 -0
  69. package/js/iso-editor/validate.js +33 -0
  70. package/js/iso-editor/window/protocol.js +8 -0
  71. package/js/iso-objects/assemble.js +43 -0
  72. package/js/iso-objects/assets.js +88 -0
  73. package/js/iso-objects/board.js +162 -0
  74. package/js/iso-objects/compile.js +60 -0
  75. package/js/iso-objects/css.js +154 -0
  76. package/js/iso-objects/flat.js +696 -0
  77. package/js/iso-objects/focus.js +16 -0
  78. package/js/iso-objects/geometry.js +76 -0
  79. package/js/iso-objects/index.js +93 -0
  80. package/js/iso-objects/kinds.js +12 -0
  81. package/js/iso-objects/labels.js +325 -0
  82. package/js/iso-objects/package.json +6 -0
  83. package/js/iso-objects/place.js +347 -0
  84. package/js/iso-objects/route.js +461 -0
  85. package/js/iso-objects/scene.js +350 -0
  86. package/js/iso-objects/steps.js +246 -0
  87. package/js/iso-objects/types.js +0 -0
  88. package/js/iso-systems/catalog.js +42 -0
  89. package/js/iso-systems/compile.js +34 -0
  90. package/js/iso-systems/css.js +8 -0
  91. package/js/iso-systems/index.js +16 -0
  92. package/js/iso-systems/nodes.js +124 -0
  93. package/js/iso-systems/package.json +6 -0
  94. package/js/iso-systems/schema.json +311 -0
  95. package/js/iso-systems/validate.js +35 -0
  96. package/js/iso-viewer/bundle.js +20 -0
  97. package/js/iso-viewer/card-motion.js +228 -0
  98. package/js/iso-viewer/dom.js +14 -0
  99. package/js/iso-viewer/dual-view.js +212 -0
  100. package/js/iso-viewer/flat-view.js +124 -0
  101. package/js/iso-viewer/history.js +990 -0
  102. package/js/iso-viewer/index.js +98 -0
  103. package/js/iso-viewer/morph.js +192 -0
  104. package/js/iso-viewer/overlay.js +199 -0
  105. package/js/iso-viewer/package.json +6 -0
  106. package/js/iso-viewer/page.js +138 -0
  107. package/js/iso-viewer/player.js +409 -0
  108. package/js/iso-viewer/still.js +81 -0
  109. package/js/iso-viewer/timeline-contract.js +14 -0
  110. package/js/iso-viewer/timeline-engine.js +475 -0
  111. package/js/iso-viewer/timeline-export.js +36 -0
  112. package/js/iso-viewer/timeline-scale.js +116 -0
  113. package/js/iso-viewer/timeline-scope.js +58 -0
  114. package/js/iso-viewer/timeline-search.js +216 -0
  115. package/js/iso-viewer/timeline-time.js +55 -0
  116. package/js/iso-viewer/view-css.js +68 -0
  117. package/js/iso-viewer/viewport.js +177 -0
  118. package/package.json +502 -4
  119. package/src/iso-core/compile-schema.ts +23 -0
  120. package/src/iso-core/depth.ts +56 -0
  121. package/src/iso-core/errors.ts +73 -0
  122. package/src/iso-core/glyphs.ts +108 -0
  123. package/src/iso-core/index.ts +27 -0
  124. package/src/iso-core/kernel.ts +163 -0
  125. package/src/iso-core/metrics.json +1 -0
  126. package/src/iso-core/package.json +6 -0
  127. package/src/iso-core/parse.ts +91 -0
  128. package/src/iso-core/schema-errors.ts +163 -0
  129. package/src/iso-core/shims/crypto.ts +37 -0
  130. package/src/iso-core/shims/path.ts +24 -0
  131. package/src/iso-core/svg-dom.ts +103 -0
  132. package/src/iso-core/theme.ts +64 -0
  133. package/src/iso-core/vdom.ts +41 -0
  134. package/src/iso-editor/adapter.ts +128 -0
  135. package/src/iso-editor/clipboard.ts +163 -0
  136. package/src/iso-editor/commands.ts +191 -0
  137. package/src/iso-editor/complete.ts +73 -0
  138. package/src/iso-editor/doc.ts +207 -0
  139. package/src/iso-editor/index.ts +67 -0
  140. package/src/iso-editor/model.ts +234 -0
  141. package/src/iso-editor/outline.ts +126 -0
  142. package/src/iso-editor/package.json +6 -0
  143. package/src/iso-editor/path.ts +18 -0
  144. package/src/iso-editor/providers.ts +113 -0
  145. package/src/iso-editor/schema-nav.ts +129 -0
  146. package/src/iso-editor/splice.ts +472 -0
  147. package/src/iso-editor/storage-keys.ts +6 -0
  148. package/src/iso-editor/ui/actions.ts +119 -0
  149. package/src/iso-editor/ui/app.css +230 -0
  150. package/src/iso-editor/ui/canvas-layer.ts +56 -0
  151. package/src/iso-editor/ui/canvas.ts +1071 -0
  152. package/src/iso-editor/ui/clip.ts +97 -0
  153. package/src/iso-editor/ui/dialog.ts +25 -0
  154. package/src/iso-editor/ui/flat-canvas.ts +51 -0
  155. package/src/iso-editor/ui/icons.ts +21 -0
  156. package/src/iso-editor/ui/keys.ts +30 -0
  157. package/src/iso-editor/ui/later.ts +22 -0
  158. package/src/iso-editor/ui/layer.ts +7 -0
  159. package/src/iso-editor/ui/marks.css +35 -0
  160. package/src/iso-editor/ui/menu.ts +67 -0
  161. package/src/iso-editor/ui/monaco-entry.ts +6 -0
  162. package/src/iso-editor/ui/mount-kit.ts +35 -0
  163. package/src/iso-editor/ui/mount.ts +684 -0
  164. package/src/iso-editor/ui/pane.ts +45 -0
  165. package/src/iso-editor/ui/part.ts +45 -0
  166. package/src/iso-editor/ui/plain-icons.ts +83 -0
  167. package/src/iso-editor/ui/props.ts +347 -0
  168. package/src/iso-editor/ui/scope-css.ts +65 -0
  169. package/src/iso-editor/ui/setup.ts +144 -0
  170. package/src/iso-editor/ui/skin.css +181 -0
  171. package/src/iso-editor/ui/text.ts +262 -0
  172. package/src/iso-editor/ui/tree.ts +657 -0
  173. package/src/iso-editor/validate.ts +62 -0
  174. package/src/iso-editor/window/protocol.ts +33 -0
  175. package/src/iso-objects/assemble.ts +57 -0
  176. package/src/iso-objects/assets.ts +122 -0
  177. package/src/iso-objects/board.ts +169 -0
  178. package/src/iso-objects/compile.ts +76 -0
  179. package/src/iso-objects/css.ts +163 -0
  180. package/src/iso-objects/flat.ts +653 -0
  181. package/src/iso-objects/focus.ts +14 -0
  182. package/src/iso-objects/geometry.ts +86 -0
  183. package/src/iso-objects/index.ts +33 -0
  184. package/src/iso-objects/kinds.ts +56 -0
  185. package/src/iso-objects/labels.ts +310 -0
  186. package/src/iso-objects/package.json +6 -0
  187. package/src/iso-objects/place.ts +318 -0
  188. package/src/iso-objects/route.ts +444 -0
  189. package/src/iso-objects/scene.ts +376 -0
  190. package/src/iso-objects/steps.ts +234 -0
  191. package/src/iso-objects/types.ts +68 -0
  192. package/src/iso-systems/catalog.ts +31 -0
  193. package/src/iso-systems/compile.ts +39 -0
  194. package/src/iso-systems/css.ts +9 -0
  195. package/src/iso-systems/index.ts +12 -0
  196. package/src/iso-systems/nodes.ts +126 -0
  197. package/src/iso-systems/package.json +6 -0
  198. package/src/iso-systems/schema.json +311 -0
  199. package/src/iso-systems/validate.ts +34 -0
  200. package/src/iso-viewer/bundle.ts +15 -0
  201. package/src/iso-viewer/card-motion.ts +237 -0
  202. package/src/iso-viewer/dom.ts +13 -0
  203. package/src/iso-viewer/dual-view.ts +212 -0
  204. package/src/iso-viewer/flat-view.ts +127 -0
  205. package/src/iso-viewer/history.ts +781 -0
  206. package/src/iso-viewer/index.ts +40 -0
  207. package/src/iso-viewer/morph.ts +191 -0
  208. package/src/iso-viewer/overlay.ts +212 -0
  209. package/src/iso-viewer/package.json +6 -0
  210. package/src/iso-viewer/page.ts +150 -0
  211. package/src/iso-viewer/player.ts +321 -0
  212. package/src/iso-viewer/still.ts +74 -0
  213. package/src/iso-viewer/timeline-contract.ts +342 -0
  214. package/src/iso-viewer/timeline-engine.ts +420 -0
  215. package/src/iso-viewer/timeline-export.ts +31 -0
  216. package/src/iso-viewer/timeline-scale.ts +129 -0
  217. package/src/iso-viewer/timeline-scope.ts +56 -0
  218. package/src/iso-viewer/timeline-search.ts +198 -0
  219. package/src/iso-viewer/timeline-time.ts +54 -0
  220. package/src/iso-viewer/view-css.ts +59 -0
  221. package/src/iso-viewer/viewport.ts +142 -0
  222. package/types/iso-core/compile-schema.d.ts +11 -0
  223. package/types/iso-core/depth.d.ts +6 -0
  224. package/types/iso-core/errors.d.ts +24 -0
  225. package/types/iso-core/glyphs.d.ts +19 -0
  226. package/types/iso-core/index.d.ts +17 -0
  227. package/types/iso-core/kernel.d.ts +130 -0
  228. package/types/iso-core/metrics.json +1 -0
  229. package/types/iso-core/parse.d.ts +18 -0
  230. package/types/iso-core/schema-errors.d.ts +14 -0
  231. package/types/iso-core/shims/crypto.d.ts +9 -0
  232. package/types/iso-core/svg-dom.d.ts +15 -0
  233. package/types/iso-core/theme.d.ts +38 -0
  234. package/types/iso-core/vdom.d.ts +26 -0
  235. package/types/iso-editor/adapter.d.ts +145 -0
  236. package/types/iso-editor/clipboard.d.ts +23 -0
  237. package/types/iso-editor/commands.d.ts +32 -0
  238. package/types/iso-editor/complete.d.ts +25 -0
  239. package/types/iso-editor/doc.d.ts +50 -0
  240. package/types/iso-editor/index.d.ts +57 -0
  241. package/types/iso-editor/model.d.ts +96 -0
  242. package/types/iso-editor/outline.d.ts +28 -0
  243. package/types/iso-editor/path.d.ts +7 -0
  244. package/types/iso-editor/providers.d.ts +43 -0
  245. package/types/iso-editor/schema-nav.d.ts +34 -0
  246. package/types/iso-editor/splice.d.ts +53 -0
  247. package/types/iso-editor/storage-keys.d.ts +5 -0
  248. package/types/iso-editor/ui/actions.d.ts +23 -0
  249. package/types/iso-editor/ui/canvas-layer.d.ts +65 -0
  250. package/types/iso-editor/ui/canvas.d.ts +279 -0
  251. package/types/iso-editor/ui/clip.d.ts +14 -0
  252. package/types/iso-editor/ui/dialog.d.ts +7 -0
  253. package/types/iso-editor/ui/flat-canvas.d.ts +2 -0
  254. package/types/iso-editor/ui/icons.d.ts +5 -0
  255. package/types/iso-editor/ui/keys.d.ts +7 -0
  256. package/types/iso-editor/ui/later.d.ts +12 -0
  257. package/types/iso-editor/ui/layer.d.ts +2 -0
  258. package/types/iso-editor/ui/menu.d.ts +21 -0
  259. package/types/iso-editor/ui/mount-kit.d.ts +31 -0
  260. package/types/iso-editor/ui/mount.d.ts +146 -0
  261. package/types/iso-editor/ui/pane.d.ts +60 -0
  262. package/types/iso-editor/ui/part.d.ts +40 -0
  263. package/types/iso-editor/ui/plain-icons.d.ts +10 -0
  264. package/types/iso-editor/ui/props.d.ts +57 -0
  265. package/types/iso-editor/ui/scope-css.d.ts +5 -0
  266. package/types/iso-editor/ui/setup.d.ts +40 -0
  267. package/types/iso-editor/ui/text.d.ts +19 -0
  268. package/types/iso-editor/ui/tree.d.ts +100 -0
  269. package/types/iso-editor/validate.d.ts +36 -0
  270. package/types/iso-editor/window/protocol.d.ts +60 -0
  271. package/types/iso-objects/assemble.d.ts +35 -0
  272. package/types/iso-objects/assets.d.ts +49 -0
  273. package/types/iso-objects/board.d.ts +36 -0
  274. package/types/iso-objects/compile.d.ts +35 -0
  275. package/types/iso-objects/css.d.ts +16 -0
  276. package/types/iso-objects/flat.d.ts +130 -0
  277. package/types/iso-objects/focus.d.ts +1 -0
  278. package/types/iso-objects/geometry.d.ts +59 -0
  279. package/types/iso-objects/index.d.ts +26 -0
  280. package/types/iso-objects/kinds.d.ts +53 -0
  281. package/types/iso-objects/labels.d.ts +92 -0
  282. package/types/iso-objects/place.d.ts +25 -0
  283. package/types/iso-objects/route.d.ts +67 -0
  284. package/types/iso-objects/scene.d.ts +63 -0
  285. package/types/iso-objects/steps.d.ts +90 -0
  286. package/types/iso-objects/types.d.ts +140 -0
  287. package/types/iso-systems/catalog.d.ts +4 -0
  288. package/types/iso-systems/compile.d.ts +6 -0
  289. package/types/iso-systems/css.d.ts +3 -0
  290. package/types/iso-systems/index.d.ts +5 -0
  291. package/types/iso-systems/nodes.d.ts +3 -0
  292. package/types/iso-viewer/card-motion.d.ts +56 -0
  293. package/types/iso-viewer/dom.d.ts +1 -0
  294. package/types/iso-viewer/dual-view.d.ts +44 -0
  295. package/types/iso-viewer/flat-view.d.ts +25 -0
  296. package/types/iso-viewer/history.d.ts +91 -0
  297. package/types/iso-viewer/index.d.ts +31 -0
  298. package/types/iso-viewer/morph.d.ts +28 -0
  299. package/types/iso-viewer/overlay.d.ts +135 -0
  300. package/types/iso-viewer/page.d.ts +13 -0
  301. package/types/iso-viewer/still.d.ts +26 -0
  302. package/types/iso-viewer/timeline-contract.d.ts +345 -0
  303. package/types/iso-viewer/timeline-engine.d.ts +20 -0
  304. package/types/iso-viewer/timeline-export.d.ts +5 -0
  305. package/types/iso-viewer/timeline-scale.d.ts +44 -0
  306. package/types/iso-viewer/timeline-scope.d.ts +33 -0
  307. package/types/iso-viewer/timeline-search.d.ts +52 -0
  308. package/types/iso-viewer/timeline-time.d.ts +8 -0
  309. package/types/iso-viewer/view-css.d.ts +7 -0
  310. package/types/iso-viewer/viewport.d.ts +50 -0
@@ -0,0 +1,1071 @@
1
+ // The canvas: the file drawn by the drawing engine (the kit's draw()), editable.
2
+ // - Selection: click, ⇧-click or ⌘-click to add or remove, a marquee drag on empty canvas (⌥: touching is enough),
3
+ // ⌘↑ the parent, rings in the skin's accent. Shared with the tree and the text through the model.
4
+ // - Pan and zoom: the wheel pans, a pinch or ⌘/Ctrl-wheel zooms around the pointer, space-drag or middle-drag pans;
5
+ // + − zoom, 0 fits, 1 is 100%, ⇧2 zooms to the selection; 10%–800%.
6
+ // - Pins: drag a selected thing to pin it to the grid; the pin is x-editor.layout.NAME.at in the file.
7
+ // - Right-click: the menu of what is under the pointer (or of the canvas).
8
+ // The drawing is in the page itself (E9): an <svg> built with DOM calls from the renderer's output (svg-dom.ts, never
9
+ // innerHTML), styled by the host's canvas CSS, which scopes the diagram's CSS under the kit's root class and names its
10
+ // tokens --iso-*, so it never meets the page's. No frame: the pointer's coordinates are the page's.
11
+ // - The kit (CanvasKit) is the domain: how a file is drawn, its objects and kinds, its commands and pins, what
12
+ // the palette offers and what a drop into a container makes, and the words.
13
+
14
+ import { h, icon, type IconName } from './icons.ts';
15
+ import { openMenu, type MenuItem } from './menu.ts';
16
+ import { run, type Actions } from './actions.ts';
17
+ import { screenToGrid, localAt, boxSilhouette, floorOf, snapMove, overlaps, paddingOf, type Move } from '../../iso-objects/geometry.ts';
18
+ import { regionKind, type KindCatalog } from '../../iso-objects/kinds.ts';
19
+ import type { CompiledScene } from '../../iso-objects/compile.ts';
20
+ import { iso, C, S } from '../../iso-core/kernel.ts';
21
+ import type { EditorModel, Command } from '../model.ts';
22
+ import type { Problem } from '../validate.ts';
23
+ import { applyStep } from '../splice.ts';
24
+ import { seqCmd, type Commands } from '../commands.ts';
25
+ import type { ObjectKindInfo, ObjectRef } from '../adapter.ts';
26
+ import { fromPointer, toPointer, type Path } from '../path.ts';
27
+ import { buildSvg } from '../../iso-core/svg-dom.ts';
28
+ import { viewport, type View } from '../../iso-viewer/viewport.ts';
29
+ import type { CanvasCtx, CanvasLayer } from './canvas-layer.ts';
30
+ import type { FlatStyle } from '../../iso-viewer/flat-view.ts';
31
+ import type { FlatOptions } from '../../iso-objects/flat.ts';
32
+ import type { SvgMorph } from '../../iso-viewer/morph.ts';
33
+
34
+ /** what the canvas draws: the domain's drawn document */
35
+ export interface CanvasDrawing {
36
+ scene: CompiledScene;
37
+ /** the frame: the scene's SVG */
38
+ svg: string;
39
+ /** data-id → the JSON pointer in the file it shows */
40
+ pathOf: Map<string, string>;
41
+ /** object name → the id of the element a pin moves */
42
+ pinId: Map<string, string>;
43
+ /** pins that couldn't apply, with why */
44
+ pinNotes: string[];
45
+ diags: string[];
46
+ }
47
+ /** a scene drawn in 2D, as the canvas uses it (flat-canvas.ts makes it) */
48
+ export interface FlatDrawn {
49
+ svg: string;
50
+ /** its viewBox */
51
+ full: [number, number, number, number];
52
+ /** the layout (for tests) */
53
+ layout: unknown;
54
+ /** the outlines of these drawn ids: a card's or a panel's rect, a link's path */
55
+ outlines(ids: Set<string>, svg: SVGSVGElement): ({ kind: 'poly'; id: string; points: [number, number][] } | { kind: 'route'; d: string })[];
56
+ /** the ids of the cards and panels in a rectangle (or touching it) */
57
+ hits(r: { l: number; t: number; r: number; b: number }, touch: boolean): string[];
58
+ /** the panels under a point, innermost first */
59
+ panelsAt(x: number, y: number): string[];
60
+ }
61
+ /** the 2D view's implementation, handed to the canvas by its host */
62
+ export interface FlatCanvas {
63
+ draw(scene: CompiledScene, stage: Element, o: { styles?: Record<string, FlatStyle>; title?: string; options?: Partial<FlatOptions> }): FlatDrawn;
64
+ /** (0.7.5) the switch's morph, from the view on the stage to the other, both laid out in `root`: undefined when it
65
+ * shouldn't animate (the motion option, reduced motion); the canvas shows and hides the two drawings itself */
66
+ morph?(root: HTMLElement, scene: CompiledScene, from: { svg: SVGSVGElement; mode: '3d' | '2d' }, to: SVGSVGElement,
67
+ o: { duration?: number; motion?: 'auto' | 'always' | 'never' }): SvgMorph | undefined;
68
+ }
69
+ /** a drop into a container: what the new object is made as, and the words for it */
70
+ export interface DropInto { container: string; value(container: string): unknown; label(container: string): string }
71
+ /** the canvas's words and names */
72
+ export interface CanvasUi {
73
+ /** the stage's class (the host's canvas CSS is scoped under it), and the drawing's class while the space key is down */
74
+ rootClass: string; panKeyClass: string;
75
+ /** the kinds the canvas's menu offers, in order */
76
+ newOrder: string[];
77
+ palette: { kind: string; icon: IconName; label: string }[];
78
+ text: {
79
+ stage: string; dragGroup: string; dragSelectTip: string; unreadable: string; palette: string;
80
+ /** the end of a pin drag's hint */
81
+ pinHint: string; renameWhy: string; duplicateWhy: string;
82
+ };
83
+ }
84
+ /** what the canvas is given of the domain (M: the domain's reading of the file; D: its drawing) */
85
+ export interface CanvasKit<M, D extends CanvasDrawing> {
86
+ draw(model: M, data: unknown, theme: string): D;
87
+ /** the drawing a text would be (a trial: where a drop lands), or undefined */
88
+ trial(text: string, theme: string): D | undefined;
89
+ catalog: KindCatalog;
90
+ objectOf(ptr: string): ObjectRef | undefined;
91
+ kinds: ObjectKindInfo[];
92
+ commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>;
93
+ actions: Actions;
94
+ /** what an object's own menu offers, beyond rename, duplicate and delete */
95
+ objectItems(doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void): MenuItem[];
96
+ pins: { key: string; legacyKey?: string; of(data: unknown): Record<string, unknown> | undefined; keyOf(data: unknown): string; legacyOnly(data: unknown): boolean };
97
+ /** the 2D view (0.6.4): offered as a 3D | 2D switch when given. `load` hands over its implementation (flat-canvas.ts;
98
+ * the canvas never names it, so a host without a 2D view bundles none of it). In 2D, selecting, the menu, renaming,
99
+ * deleting, adding from the palette (into a panel, or placed by the layout) and undo work as in 3D; pins (moving)
100
+ * are 3D only. The host's canvas CSS has the 2D view's (flatCss), scoped as the drawing's is. */
101
+ flat?: { load(): Promise<FlatCanvas>; styles?: Record<string, FlatStyle>; title?: string; options?: Partial<FlatOptions>;
102
+ /** (0.7.5) the switch morphs, as dualView does: 'auto' (the default) honours prefers-reduced-motion, 'always' morphs
103
+ * regardless, 'never' swaps at once; `duration` in ms (600) */
104
+ motion?: 'auto' | 'always' | 'never'; duration?: number };
105
+ /** a drop of this kind onto a container's floor (none: it is pinned where it drops) */
106
+ dropInto?(kind: string): DropInto | undefined;
107
+ ui: CanvasUi;
108
+ }
109
+
110
+ export interface CanvasOpts<M, D extends CanvasDrawing, A extends object = object> {
111
+ kit: CanvasKit<M, D>;
112
+ theme: string;
113
+ problems(): Problem[];
114
+ note(t: string, tone?: 'info' | 'warn' | 'bad'): void;
115
+ showInText(p: Path): void;
116
+ showInTree(p: Path): void;
117
+ onZoom(pct: number): void;
118
+ /** the navigation modes, for the status bar */
119
+ onHint?(text: string): void;
120
+ /** Copy, Cut and Paste for the menu */
121
+ clipItems?(): MenuItem[];
122
+ /** where the navigation modes are kept between visits (the host's storage); none: for this mount only */
123
+ store?: { get(k: string): string | null; set(k: string, v: string | null): void };
124
+ /** a layer over the drawing (none: the drawing and its marks only) */
125
+ layer?: (ctx: CanvasCtx<D>) => CanvasLayer<A>;
126
+ }
127
+
128
+ const SVGNS = 'http://www.w3.org/2000/svg';
129
+
130
+
131
+ export function canvasView<M, D extends CanvasDrawing, A extends object = object>(host: HTMLElement, doc: EditorModel, opts: CanvasOpts<M, D, A>) {
132
+ const K = opts.kit, ui = K.ui, T = ui.text;
133
+ const { setCmd, deleteCmd, insertCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
134
+ const { deletePaths, renameDialog, duplicate, connected } = K.actions;
135
+ const resourceOf = (ptr: string) => K.objectOf(ptr);
136
+ const kindOf = (k: string) => K.kinds.find(x => x.kind === k)!;
137
+ const PINS_KEY = K.pins.key;
138
+ host.classList.add('canvas');
139
+ // the stage holds the drawing, and takes the focus, the keys and the pointer
140
+ const stage = h('div', { class: `${ui.rootClass} canvas-stage`, tabindex: '0', role: 'application', 'aria-label': T.stage });
141
+ const tools = h('div', { class: 'canvas-tools', role: 'toolbar', 'aria-label': 'Canvas' });
142
+ const zoomOut = h('button', { type: 'button', class: 'btn sm quiet icon-only', 'aria-label': 'Zoom out (−)', title: 'Zoom out (−)' }, '−');
143
+ const zoomLabel = h('button', { type: 'button', class: 'btn sm quiet zoom-label', title: 'Fit (0) · 100% (1)' }, '100%');
144
+ const zoomIn = h('button', { type: 'button', class: 'btn sm quiet icon-only', 'aria-label': 'Zoom in (+)', title: 'Zoom in (+)' }, '+');
145
+ const fitBtn = h('button', { type: 'button', class: 'btn sm quiet', title: 'Fit (0)' }, 'Fit');
146
+ // navigation: what the wheel does, and what a drag on nothing does (remembered by this browser)
147
+ const seg = (label: string, key: string, values: [string, string, string][]) => {
148
+ const g = h('div', { class: 'segmented', role: 'group', 'aria-label': label, title: label });
149
+ for (const [v, text, tip] of values) {
150
+ const b = h('button', { type: 'button', class: 'seg', 'data-v': v, title: tip }, text);
151
+ b.addEventListener('click', () => { nav[key as 'wheel' | 'drag'] = v as never; saveNav(); paintNav(); });
152
+ g.append(b);
153
+ }
154
+ return g;
155
+ };
156
+ const wheelSeg = seg('The wheel', 'wheel', [['zoom', 'Zoom', 'The wheel zooms around the pointer; ⇧-wheel pans sideways'], ['scroll', 'Scroll', 'The wheel pans; ⇧-wheel pans sideways; a pinch zooms']]);
157
+ const dragSeg = seg(T.dragGroup, 'drag', [['pan', 'Pan', 'Drag pans; ⇧- or ⌘-drag draws a selection'], ['select', 'Select', T.dragSelectTip]]);
158
+ // the view: 3D (the drawing, pins and all) or 2D (its flat layout); offered when the kit has a 2D view
159
+ let mode: '3d' | '2d' = '3d';
160
+ let flat: FlatDrawn | undefined, flatImpl: FlatCanvas | undefined;
161
+ /** the 2D view's implementation, once (the host's to hand over) */
162
+ const loadFlat = async () => (flatImpl ??= await K.flat!.load());
163
+ const viewSeg = h('div', { class: 'segmented view-seg', role: 'group', 'aria-label': 'The view' });
164
+ for (const [v, text, tip] of [['3d', '3D', '3D: the drawing; drag a selected thing to move it'], ['2d', '2D', '2D: select, rename, delete, add from the palette and edit here; moving is in 3D']] as const) {
165
+ const b = h('button', { type: 'button', class: 'seg', 'data-v': v, title: tip }, text);
166
+ b.addEventListener('click', () => setMode(v));
167
+ viewSeg.append(b);
168
+ }
169
+ // what a layer is given (its calls run later, once the drawing and the view are made)
170
+ const ctx: CanvasCtx<D> = {
171
+ host, doc, cd: () => cd, svg: () => svg, elementsFor: p => elementsFor(p), boxOf: e => boxOf(e), union: bs => union(bs), outlinesFor: p => outlinesFor(p),
172
+ scale: () => scale(), full: () => V.full, toSvg: (x, y) => toSvg(x, y), autoFit: () => autoFit(), paint: () => paintOverlay(), reveal: p => zoomIfOutside(p), note: (m, tone) => opts.note(m, tone),
173
+ };
174
+ // the layer's controls first, then the canvas's own
175
+ const layer = opts.layer?.(ctx);
176
+ tools.append(...(layer?.tools ?? []), ...(K.flat ? [viewSeg] : []), wheelSeg, dragSeg, zoomOut, zoomLabel, zoomIn, fitBtn);
177
+ const empty = h('div', { class: 'canvas-empty', hidden: true });
178
+ host.append(stage, tools, empty, ...(layer?.marks ?? []));
179
+ const nav = { wheel: 'zoom' as 'zoom' | 'scroll', drag: 'pan' as 'pan' | 'select' };
180
+ try { Object.assign(nav, JSON.parse(opts.store?.get('canvas-nav') ?? '{}')); } catch { /* defaults */ }
181
+ if (K.flat && opts.store?.get('canvas-view') === '2d') mode = '2d';
182
+ /** switch the view: the drawing again in the other one, fitted (a 2D layout and a 3D one share no coordinates) */
183
+ function setMode(m: '3d' | '2d') {
184
+ if (!K.flat || m === mode) return;
185
+ endMorph();
186
+ const was = mode;
187
+ mode = m;
188
+ opts.store?.set('canvas-view', m);
189
+ paintNav();
190
+ // the drawing on the stage stays there, under the new one, to morph from (0.7.5)
191
+ if (svg && cd && svg.parentNode === stage) morphFrom = { svg, mode: was };
192
+ if (lastS3 !== undefined) { V.view = undefined; lastKey = ''; void render(lastS3, lastData); }
193
+ }
194
+ const saveNav = () => opts.store?.set('canvas-nav', JSON.stringify(nav));
195
+ /** the toolbar, the cursor and the status bar's hint show the current modes */
196
+ function paintNav() {
197
+ for (const [g, v] of [[wheelSeg, nav.wheel], [dragSeg, nav.drag], [viewSeg, mode]] as const) for (const b of g.querySelectorAll<HTMLButtonElement>('.seg')) b.setAttribute('aria-pressed', String(b.dataset.v === v));
198
+ svg?.classList.toggle('mode-pan', nav.drag === 'pan');
199
+ svg?.classList.toggle('mode-select', nav.drag === 'select');
200
+ if (drag?.kind === 'pin' && drag.moved) { svg?.classList.add('dragging'); svg?.classList.toggle('drag-bad', !!drag.invalid); return; } // the drag's own hint stays
201
+ opts.onHint?.(`${nav.drag === 'pan' ? 'Drag: pan · ⇧-drag: select' : 'Drag: select · space-drag: pan'} · Wheel: ${nav.wheel === 'zoom' ? 'zoom' : 'scroll'}`);
202
+ }
203
+ let cd: D | undefined;
204
+ let svg: SVGSVGElement | undefined;
205
+ let overlay: SVGGElement | undefined;
206
+ let lastKey = '';
207
+ let hoverId: string | undefined;
208
+ const fdoc = () => document;
209
+
210
+ /** Draw the file (after each change the reader accepted). */
211
+ let disposed = false;
212
+ async function render(s3: M | undefined, data: unknown) {
213
+ if (disposed) return;
214
+ if (!s3) { showEmpty(T.unreadable); return; }
215
+ const key = JSON.stringify(data);
216
+ // nothing new to draw: repaint the marks, unless a drag is showing its grid (it repaints when it ends)
217
+ if (key === lastKey && svg) { if (!pinDrag()) paintOverlay(); return; }
218
+ if (mode === '2d' && !flatImpl) {
219
+ try { await loadFlat(); } catch (e) { mode = '3d'; paintNav(); opts.note(`The 2D view couldn't load: ${(e as Error).message}`, 'warn'); }
220
+ }
221
+ let next: D;
222
+ try { next = K.draw(s3, data, opts.theme); } catch (e) { showEmpty(`The canvas couldn't draw this: ${(e as Error).message}`); return; }
223
+ if (next.diags.length) { showEmpty(`The canvas couldn't draw this: ${next.diags[0]}`); return; }
224
+ lastKey = key;
225
+ lastS3 = s3; lastData = data;
226
+ if (pinDrag()) { pendingAfterDrag = true; return; } // a model change mid-drag: drawn when the drag ends
227
+ await draw(next);
228
+ if (cd!.pinNotes.length) opts.note(`Pins: ${cd!.pinNotes.join('; ')}`, 'warn');
229
+ }
230
+ let lastS3: M | undefined, lastData: unknown, pendingAfterDrag = false;
231
+ // ---------- the switch's morph (0.7.5): the 2D view's implementation runs it, over the stage ----------
232
+ let morphFrom: { svg: SVGSVGElement; mode: '3d' | '2d' } | undefined;
233
+ let morphing: { m: SvgMorph; from: SVGSVGElement; to: SVGSVGElement } | undefined;
234
+ /** end a morph now: the layer and the old drawing gone, the new one shown */
235
+ function endMorph() {
236
+ if (!morphing) return;
237
+ const r = morphing; morphing = undefined;
238
+ r.m.finish();
239
+ r.from.remove();
240
+ r.to.style.visibility = '';
241
+ }
242
+ /** after a switch draws the new view: the morph from the old one, both on the stage (the old under the new) */
243
+ function startMorph(from: { svg: SVGSVGElement; mode: '3d' | '2d' }, to: SVGSVGElement) {
244
+ const m = flatImpl?.morph?.(stage, cd!.scene, from, to, { motion: K.flat?.motion, duration: K.flat?.duration });
245
+ if (!m) { from.svg.remove(); return; }
246
+ from.svg.style.visibility = 'hidden'; to.style.visibility = 'hidden';
247
+ const me = { m, from: from.svg, to };
248
+ morphing = me;
249
+ stage.classList.add('morphing');
250
+ void m.done.then(() => { if (morphing === me) endMorph(); stage.classList.remove('morphing'); });
251
+ }
252
+ /** put a drawing on the stage (the file's, or a drag's trial layout): built with DOM calls, never from markup */
253
+ async function draw(next: D) {
254
+ endMorph();
255
+ let s: SVGSVGElement;
256
+ let full = next.scene.rendered.viewBox as unknown as number[];
257
+ try {
258
+ if (mode === '2d' && flatImpl) {
259
+ // the 2D view: the host's implementation draws the drawing's board, laid out flat
260
+ flat = flatImpl.draw(next.scene, stage, { styles: K.flat?.styles, title: K.flat?.title, options: K.flat?.options });
261
+ full = flat.full;
262
+ s = buildSvg(flat.svg);
263
+ // the stage takes the keys: the cards aren't stops of their own here
264
+ for (const e of s.querySelectorAll('[tabindex]')) { e.removeAttribute('tabindex'); e.removeAttribute('role'); }
265
+ } else { flat = undefined; s = buildSvg(next.svg); }
266
+ } catch (e) { showEmpty(`The canvas couldn't draw this: ${(e as Error).message}`); return; }
267
+ cd = next;
268
+ s.classList.add('scene');
269
+ s.removeAttribute('width'); s.removeAttribute('height');
270
+ s.setAttribute('preserveAspectRatio', 'xMidYMid meet');
271
+ s.setAttribute('aria-hidden', 'true'); // the stage says it in words; the tree and text say the rest
272
+ overlay = document.createElementNS(SVGNS, 'g') as SVGGElement;
273
+ overlay.setAttribute('class', 'overlay');
274
+ // 0.7.4: safe without any stylesheet: the marks inherit no fill, a thin accent-less stroke, and never take the pointer
275
+ // (a hover mark over its thing would take it, and the hover would flicker); a host's CSS (assets/marks.css) styles them
276
+ overlay.setAttribute('fill', 'none'); overlay.setAttribute('stroke', 'currentColor'); overlay.setAttribute('pointer-events', 'none');
277
+ s.append(overlay, ...(layer?.groups?.() ?? []));
278
+ const from = morphFrom; morphFrom = undefined;
279
+ if (from && svg === from.svg && svg.parentNode === stage) {
280
+ // a switch: the old view stays under the new one until the morph has read both
281
+ from.svg.querySelector('.overlay')?.replaceChildren();
282
+ from.svg.style.position = 'absolute'; from.svg.style.inset = '0';
283
+ stage.append(s);
284
+ } else if (svg?.parentNode === stage) svg.replaceWith(s); else stage.append(s);
285
+ svg = s;
286
+ const [x, y, w, hh] = full;
287
+ V.full = { x, y, w, h: hh };
288
+ if (!V.view) { V.view = { ...V.full }; autoFit(); } else quietly(applyView);
289
+ empty.hidden = true;
290
+ layer?.drawn?.();
291
+ if (pendingReveal && reveal(pendingReveal)) pendingReveal = undefined;
292
+ paintNav();
293
+ paintOverlay();
294
+ if (from && from.svg !== s) {
295
+ if (getComputedStyle(stage).position === 'static') stage.style.position = 'relative';
296
+ startMorph(from, s);
297
+ }
298
+ }
299
+ function showEmpty(t: string) {
300
+ morphFrom = undefined;
301
+ empty.textContent = t;
302
+ empty.hidden = false;
303
+ }
304
+
305
+ // light and dark: the canvas CSS maps the drawing's tokens onto the skin's, which follow the page's colour scheme
306
+ function setTheme(_t: 'light' | 'dark') { paintOverlay(); }
307
+
308
+ // ---------- view: pan and zoom (the viewport, src/iso-viewer/viewport.ts) ----------
309
+ function itemsBox() {
310
+ if (!cd || !svg) return undefined;
311
+ const ptrs = [...new Set([...cd.pathOf.values()].filter(p => { const r = resourceOf(p); return r && r.path === p; }))];
312
+ // what a layer draws is fitted too
313
+ const live = layer?.extent?.() ?? [];
314
+ return union([...ptrs.flatMap(p => elementsFor(p)).filter(e => e.getBBox().width || e.getBBox().height).map(boxOf), ...live]);
315
+ }
316
+ const V = viewport(host, {
317
+ svg: () => svg,
318
+ onApply: k => {
319
+ svg!.classList.toggle('zoom-near', k >= 1); // a layer's detail shows from 100% up
320
+ const pct = Math.round(k * 100);
321
+ zoomLabel.textContent = `${pct}%`;
322
+ opts.onZoom(pct);
323
+ },
324
+ onRezoom: () => paintOverlay(),
325
+ itemsBox: () => itemsBox(),
326
+ marksShowing: () => !!layer?.showing?.(),
327
+ });
328
+ const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
329
+ function zoomToSelection() { const b = unionBox(doc.selection); if (b) fit({ x: b.x - 20, y: b.y - 20, w: b.w + 40, h: b.h + 40 }); }
330
+ zoomIn.addEventListener('click', () => zoomAt(1.25));
331
+ zoomOut.addEventListener('click', () => zoomAt(0.8));
332
+ zoomLabel.addEventListener('click', () => fitItems());
333
+ fitBtn.addEventListener('click', () => fitItems());
334
+
335
+ // ---------- what is where ----------
336
+ const elementsFor = (ptr: string): SVGGraphicsElement[] => {
337
+ if (!svg || !cd) return [];
338
+ const ids = [...cd.pathOf.entries()].filter(([, p]) => p === ptr || (ptr && p.startsWith(ptr + '/') && false)).map(([id]) => id);
339
+ return ids.flatMap(id => [...svg!.querySelectorAll<SVGGraphicsElement>(`[data-id="${CSS.escape(id)}"]`)]).filter(e => !e.closest('.pre') && !e.classList.contains('pre'));
340
+ };
341
+ /** an element's box in the scene's (root) coordinates */
342
+ const boxOf = (e: SVGGraphicsElement) => {
343
+ const b = e.getBBox();
344
+ const m = e.getCTM(), root = svg!.getCTM();
345
+ if (!m || !root) return { x: b.x, y: b.y, w: b.width, h: b.height };
346
+ const t = root.inverse().multiply(m);
347
+ const pts = [[b.x, b.y], [b.x + b.width, b.y], [b.x, b.y + b.height], [b.x + b.width, b.y + b.height]].map(([x, y]) => ({ x: t.a * x + t.c * y + t.e, y: t.b * x + t.d * y + t.f }));
348
+ const xs = pts.map(p => p.x), ys = pts.map(p => p.y);
349
+ return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
350
+ };
351
+ const union = (bs: { x: number; y: number; w: number; h: number }[]) => {
352
+ if (!bs.length) return undefined;
353
+ const x0 = Math.min(...bs.map(b => b.x)), y0 = Math.min(...bs.map(b => b.y)), x1 = Math.max(...bs.map(b => b.x + b.w)), y1 = Math.max(...bs.map(b => b.y + b.h));
354
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
355
+ };
356
+ /** a path's drawn box: its own elements, else its resource's */
357
+ const boxFor = (p: Path) => {
358
+ // the path's own drawing, else (a key inside a resource) its resource's; never the whole file for something else
359
+ const own = toPointer(p);
360
+ let els = elementsFor(own);
361
+ const r = resourceOf(own);
362
+ if (!els.length && r && r.path !== own) els = elementsFor(r.path);
363
+ return els.length ? union(els.filter(e => e.getBBox().width || e.getBBox().height).map(boxOf)) : undefined;
364
+ };
365
+ const unionBox = (ps: Path[]) => union(ps.map(boxFor).filter((b): b is NonNullable<typeof b> => !!b));
366
+ const pathAtEvent = (target: EventTarget | null): string | undefined => {
367
+ const el = (target as Element | null)?.closest?.('[data-id]') as Element | null;
368
+ if (!el || !cd) return undefined;
369
+ // the innermost element that maps
370
+ let e: Element | null = el;
371
+ while (e) { const id = e.getAttribute('data-id'); if (id && cd.pathOf.has(id)) return cd.pathOf.get(id); e = e.parentElement?.closest('[data-id]') ?? null; }
372
+ return undefined;
373
+ };
374
+
375
+ // ---------- the overlay: selection rings, hover, problem badges ----------
376
+ /**
377
+ * A resource's drawn shapes, isometric: a node (or a slab, a VM, a platform) is the silhouette of its box (the hexagon
378
+ * its eight projected corners make); any other region is its floor parallelogram; a route is its own path.
379
+ */
380
+ function outlinesFor(ptr: string): ({ kind: 'poly'; id: string; points: [number, number][] } | { kind: 'route'; d: string })[] {
381
+ if (!cd) return [];
382
+ const out: ({ kind: 'poly'; id: string; points: [number, number][] } | { kind: 'route'; d: string })[] = [];
383
+ const mine = new Set([...cd.pathOf].filter(([, p]) => p === ptr).map(([id]) => id));
384
+ // 2D: a card's or a panel's rect; a link's own path
385
+ if (flat && svg) return flat.outlines(mine, svg);
386
+ for (const [id, p] of cd.pathOf) {
387
+ if (p !== ptr) continue;
388
+ const item = cd.scene.layout.byId.get(id);
389
+ // a thing drawn inside another drawing of the same resource (a VM's /workspace and disk) has no outline of its own
390
+ let up = item?.parent;
391
+ while (up && !mine.has(up.id)) up = up.parent;
392
+ if (up) continue;
393
+ if (item) {
394
+ if (svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) continue;
395
+ const shape = regionKind(K.catalog, item.region?.kind)?.shape;
396
+ const solid = item.type === 'node' || shape === 'slab' || shape === 'block';
397
+ out.push({ kind: 'poly', id, points: solid ? boxSilhouette(item.box) : floorOf(item.box) });
398
+ } else if (cd.scene.rendered.paths[id] && !svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) {
399
+ out.push({ kind: 'route', d: cd.scene.rendered.paths[id] });
400
+ }
401
+ }
402
+ return out;
403
+ }
404
+
405
+ function paintOverlay() {
406
+ V.painted(V.view ? scale() : 0);
407
+ if (!overlay || !svg) return;
408
+ const d = fdoc();
409
+ overlay.replaceChildren();
410
+ const ring = (b: { x: number; y: number; w: number; h: number }, cls: string, pad = 4) => {
411
+ const r = d.createElementNS(SVGNS, 'rect');
412
+ r.setAttribute('class', cls);
413
+ r.setAttribute('x', String(b.x - pad)); r.setAttribute('y', String(b.y - pad));
414
+ r.setAttribute('width', String(b.w + pad * 2)); r.setAttribute('height', String(b.h + pad * 2));
415
+ r.setAttribute('rx', '6');
416
+ overlay!.append(r);
417
+ };
418
+ const draw = (ptr: string, cls: 'ring' | 'hover') => {
419
+ // a key inside a resource is shown by its resource's outline
420
+ const r = resourceOf(ptr);
421
+ let shapes = outlinesFor(ptr);
422
+ if (!shapes.length && r && r.path !== ptr) shapes = outlinesFor(r.path);
423
+ if (!shapes.length) { const b = boxFor(fromPointer(ptr)); if (b) ring(b, cls, cls === 'hover' ? 3 : 4); return; }
424
+ for (const sh of shapes) {
425
+ if (sh.kind === 'route') {
426
+ const r = d.createElementNS(SVGNS, 'path');
427
+ r.setAttribute('class', cls === 'ring' ? 'route-ring' : 'route-hover');
428
+ r.setAttribute('d', sh.d);
429
+ overlay!.append(r);
430
+ } else {
431
+ const r = d.createElementNS(SVGNS, 'polygon');
432
+ r.setAttribute('class', cls);
433
+ r.setAttribute('points', sh.points.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '));
434
+ r.setAttribute('data-for', sh.id);
435
+ overlay!.append(r);
436
+ }
437
+ }
438
+ };
439
+ if (hoverId !== undefined && !doc.selection.some(p => toPointer(p) === hoverId)) draw(hoverId, 'hover');
440
+ for (const p of doc.selection) draw(toPointer(p), 'ring');
441
+ // a badge on each drawn resource with problems
442
+ const counts = new Map<string, { e: number; w: number }>();
443
+ for (const pr of opts.problems()) {
444
+ if (pr.file) continue;
445
+ const r = resourceOf(pr.path);
446
+ if (!r) continue;
447
+ const c = counts.get(r.path) ?? { e: 0, w: 0 };
448
+ if (pr.severity === 'error') c.e++; else c.w++;
449
+ counts.set(r.path, c);
450
+ }
451
+ for (const [ptr, c] of counts) {
452
+ // on the thing itself (its nodes and regions), not on the routes that reach out from it
453
+ const els = elementsFor(ptr).filter(e => cd!.scene.layout.byId.has(e.getAttribute('data-id') ?? ''));
454
+ const b = union(els.map(boxOf));
455
+ if (!b) continue;
456
+ const g = d.createElementNS(SVGNS, 'g');
457
+ g.setAttribute('class', `badge${c.e ? '' : ' warn'}`);
458
+ const k = scale();
459
+ const cx = b.x + b.w, cy = b.y, rr = 9 / k;
460
+ const circle = d.createElementNS(SVGNS, 'circle');
461
+ circle.setAttribute('cx', String(cx)); circle.setAttribute('cy', String(cy)); circle.setAttribute('r', String(rr));
462
+ const t = d.createElementNS(SVGNS, 'text');
463
+ t.setAttribute('x', String(cx)); t.setAttribute('y', String(cy));
464
+ t.style.fontSize = `${(11 / k).toFixed(2)}px`; // through the CSSOM (it must beat the drawing's badge rule)
465
+ t.textContent = String(c.e || c.w);
466
+ g.append(circle, t);
467
+ overlay.append(g);
468
+ }
469
+ layer?.paint?.(d);
470
+ }
471
+
472
+ // ---------- pointer: select, marquee, pan, pin ----------
473
+ let drag: {
474
+ kind: 'pan' | 'marquee' | 'pin' | 'click'; x0: number; y0: number; v0?: View; emptyClick?: boolean;
475
+ // a pin drag: where it started and what it is shown at, its size and floor, its parent and siblings, the move so far
476
+ start?: [number, number]; shown?: [number, number]; z0?: number; size?: [number, number];
477
+ parent?: { w: number; d: number; pad: number; box: { x0: number; y0: number; x1: number; y1: number }; label: string };
478
+ siblings?: { x0: number; y0: number; x1: number; y1: number }[]; move?: Move; invalid?: boolean; step?: number; origCd?: D; gridShown?: boolean;
479
+ /** siblings that flow after the dragged item, pinned where they stand so the drag doesn't push them */
480
+ keep?: [string, [number, number]][]; sel0?: Path[]; add?: boolean; touch?: boolean; name?: string; id?: string; box?: { x: number; y: number; w: number; h: number }; moved?: boolean; ptr?: string; narrow?: string } | undefined;
481
+ let spaceKeyDown = false;
482
+ const ifEvents = () => {
483
+ stage.addEventListener('pointerdown', down);
484
+ stage.addEventListener('pointermove', move);
485
+ stage.addEventListener('pointerup', up);
486
+ stage.addEventListener('pointercancel', up);
487
+ stage.addEventListener('wheel', wheel, { passive: false });
488
+ stage.addEventListener('contextmenu', context);
489
+ stage.addEventListener('dblclick', e => { const p = pathAtEvent(e.target); if (p !== undefined) opts.showInText(fromPointer(p)); });
490
+ };
491
+ // in the page, a pointer's coordinates are already the page's
492
+ const pageXY = (e: PointerEvent | MouseEvent) => ({ x: e.clientX, y: e.clientY });
493
+ /** a drag keeps its pointer's events when the pointer leaves the stage (a synthetic pointer can't be captured) */
494
+ const capture = (e: PointerEvent) => { try { stage.setPointerCapture(e.pointerId); } catch { /* not a real pointer */ } };
495
+
496
+ function down(e: PointerEvent) {
497
+ stage.focus({ preventScroll: true });
498
+ if (layer?.down?.(e)) return;
499
+ const { x, y } = pageXY(e);
500
+ if (e.button === 0 || e.button === 1) capture(e);
501
+ const pan = () => { drag = { kind: 'pan', x0: x, y0: y, v0: { ...V.view! } }; svg?.classList.add('panning'); e.preventDefault(); };
502
+ if (e.button === 1 || spaceKeyDown) { pan(); return; }
503
+ if (e.button !== 0) return;
504
+ const ptr = pathAtEvent(e.target);
505
+ if (ptr === undefined) {
506
+ // nothing under the pointer: Pan mode pans (⇧ or ⌘ draws a selection instead); Select mode draws a selection (the space key pans)
507
+ const mod = e.shiftKey || e.metaKey || e.ctrlKey;
508
+ if (nav.drag === 'pan' && !mod) { drag = { kind: 'pan', x0: x, y0: y, v0: { ...V.view! }, emptyClick: true }; svg?.classList.add('panning'); return; }
509
+ const add = nav.drag === 'select' && mod;
510
+ drag = { kind: 'marquee', x0: x, y0: y, sel0: add ? doc.selection : [], add, touch: e.altKey };
511
+ return;
512
+ }
513
+ const p = fromPointer(ptr);
514
+ const sel = doc.selection.map(toPointer);
515
+ if (e.shiftKey || e.metaKey || e.ctrlKey) {
516
+ doc.select(sel.includes(ptr) ? doc.selection.filter(q => toPointer(q) !== ptr) : [...doc.selection, p], 'canvas');
517
+ return;
518
+ }
519
+ if (!sel.includes(ptr)) doc.select([p], 'canvas');
520
+ // a plain click on one of several selected things selects just it, once the button comes up without a drag
521
+ const narrow = sel.includes(ptr) && sel.length > 1 ? ptr : undefined;
522
+ drag = { kind: 'click', x0: x, y0: y, ptr: narrow };
523
+ // a press on a resource that can be pinned: a drag pins it
524
+ const r = resourceOf(ptr);
525
+ const name = r && r.path === ptr ? r.name : undefined;
526
+ const id = name && mode === '3d' ? cd?.pinId.get(name) : undefined;
527
+ if (id && cd) {
528
+ const item = cd.scene.layout.byId.get(id);
529
+ const start = localAt(cd.scene, id);
530
+ if (item && start) {
531
+ const b = item.box, par = item.parent;
532
+ const siblings = (par ? par.children : cd.scene.layout.items.filter(i => !i.parent)).filter(i => i !== item).map(i => ({ x0: i.box.x0, y0: i.box.y0, x1: i.box.x1, y1: i.box.y1 }));
533
+ drag = {
534
+ kind: 'pin', x0: x, y0: y, name, id, ptr, narrow, start, shown: start, z0: b.z0, size: [b.x1 - b.x0, b.y1 - b.y0], siblings,
535
+ parent: par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region), box: par.box, label: par.region?.label ?? par.id } : undefined,
536
+ origCd: cd,
537
+ };
538
+ }
539
+ }
540
+ }
541
+ function move(e: PointerEvent) {
542
+ const { x, y } = pageXY(e);
543
+ if (!drag) {
544
+ const p = pathAtEvent(e.target);
545
+ if (p !== hoverId) { hoverId = p; paintOverlay(); }
546
+ return;
547
+ }
548
+ const k = scale();
549
+ if (drag.kind === 'click' && mode === '2d' && !drag.moved && Math.hypot(x - drag.x0, y - drag.y0) > 4) {
550
+ drag.moved = true;
551
+ opts.onHint?.('Moving is in 3D: switch to 3D to drag it where it goes');
552
+ return;
553
+ }
554
+ if (drag.kind === 'pan') {
555
+ if (Math.hypot(x - drag.x0, y - drag.y0) > 3) drag.emptyClick = false;
556
+ V.view = { ...drag.v0!, x: drag.v0!.x - (x - drag.x0) / k, y: drag.v0!.y - (y - drag.y0) / k };
557
+ applyView();
558
+ } else if (drag.kind === 'marquee') {
559
+ // the marquee is a rectangle on the floor (grid units), drawn as the parallelogram it projects to
560
+ if (Math.hypot(x - drag.x0, y - drag.y0) < 3) return;
561
+ drag.moved = true;
562
+ const a = toSvg(drag.x0, drag.y0), b = toSvg(x, y);
563
+ if (flat) { marquee2d(a, b); return; }
564
+ const [ax, ay] = screenToGrid(a.x, a.y), [bx, by] = screenToGrid(b.x, b.y);
565
+ const g = { x0: Math.min(ax, bx), y0: Math.min(ay, by), x1: Math.max(ax, bx), y1: Math.max(ay, by) };
566
+ const hits = new Map<string, Path>();
567
+ for (const [ptr, foot] of footprints()) {
568
+ // a thing at height z shows where a thing on the floor at (x − z, y − z) would: compare it there
569
+ const f = foot;
570
+ const inside = f.x0 >= g.x0 && f.y0 >= g.y0 && f.x1 <= g.x1 && f.y1 <= g.y1;
571
+ const touches = f.x0 < g.x1 && f.x1 > g.x0 && f.y0 < g.y1 && f.y1 > g.y0;
572
+ if (drag.touch ? touches : inside) hits.set(ptr, fromPointer(ptr));
573
+ }
574
+ const base = new Map((drag.sel0 ?? []).map(p => [toPointer(p), p]));
575
+ for (const [k2, p] of hits) base.set(k2, p);
576
+ doc.select([...base.values()], 'canvas');
577
+ paintOverlay();
578
+ const poly = fdoc().createElementNS(SVGNS, 'polygon');
579
+ poly.setAttribute('class', 'marquee');
580
+ poly.setAttribute('points', [[g.x0, g.y0], [g.x1, g.y0], [g.x1, g.y1], [g.x0, g.y1]].map(([gx, gy]) => iso(gx, gy, 0).map(v => v.toFixed(1)).join(',')).join(' '));
581
+ overlay!.append(poly);
582
+ lastMarquee = g;
583
+ } else if (drag.kind === 'pin') {
584
+ if (!drag.moved && Math.hypot(x - drag.x0, y - drag.y0) < 4) return;
585
+ drag.moved = true;
586
+ lastPin = { x, y, alt: e.altKey };
587
+ // throttled to animation frames (with a timer for a page that draws none)
588
+ if (!pinFrame) { pinFrame = true; const go = () => { if (pinFrame) { pinFrame = false; pinStep(); } }; requestAnimationFrame(go); setTimeout(go, 32); }
589
+ }
590
+ }
591
+ /** the marquee in 2D: a rectangle, what lies in it (or touches it, with ⌥) */
592
+ function marquee2d(a: { x: number; y: number }, b: { x: number; y: number }) {
593
+ if (!drag || !flat || !cd) return;
594
+ const g = { l: Math.min(a.x, b.x), t: Math.min(a.y, b.y), r: Math.max(a.x, b.x), b: Math.max(a.y, b.y) };
595
+ const hits = new Map<string, Path>();
596
+ for (const id of flat.hits(g, !!drag.touch)) {
597
+ const ptr = cd.pathOf.get(id);
598
+ if (ptr !== undefined && resourceOf(ptr)?.path === ptr) hits.set(ptr, fromPointer(ptr));
599
+ }
600
+ const base = new Map((drag.sel0 ?? []).map(p => [toPointer(p), p]));
601
+ for (const [k2, p] of hits) base.set(k2, p);
602
+ doc.select([...base.values()], 'canvas');
603
+ paintOverlay();
604
+ const r = fdoc().createElementNS(SVGNS, 'rect');
605
+ r.setAttribute('class', 'marquee');
606
+ r.setAttribute('x', String(g.l)); r.setAttribute('y', String(g.t)); r.setAttribute('width', String(g.r - g.l)); r.setAttribute('height', String(g.b - g.t));
607
+ overlay!.append(r);
608
+ }
609
+ let pinFrame = false, lastPin: { x: number; y: number; alt: boolean } | undefined, relayout = 0;
610
+ const pinDrag = () => (drag?.kind === 'pin' && drag.moved ? drag : undefined);
611
+ /** one step of a pin drag: snap, clamp, check, move the drawing, and lay it out again when the cell changes */
612
+ function pinStep() {
613
+ const g = pinDrag();
614
+ if (!g || !lastPin || !cd) return;
615
+ const k = scale();
616
+ const step = lastPin.alt ? 0.5 : 1;
617
+ g.step = step;
618
+ const m = snapMove(g.start!, screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k), step, g.size!, g.parent);
619
+ const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
620
+ const foot = { x0: ox + m.at[0], y0: oy + m.at[1], x1: ox + m.at[0] + g.size![0], y1: oy + m.at[1] + g.size![1] };
621
+ const changed = !g.move || g.move.at[0] !== m.at[0] || g.move.at[1] !== m.at[1];
622
+ g.move = m;
623
+ g.invalid = overlaps(foot, g.siblings!);
624
+ svg?.classList.add('dragging');
625
+ svg?.classList.toggle('drag-bad', g.invalid);
626
+ // at once: the drawn item (and what stands on it) moved by transform, from where the drawing has it
627
+ shiftDragged(g.id!, [m.at[0] - g.shown![0], m.at[1] - g.shown![1]]);
628
+ paintDrag(foot);
629
+ const within = g.parent ? `within ${g.parent.label}` : 'on the canvas';
630
+ opts.onHint?.(`Moving ${g.name} ${within} · ${step === 1 ? 'whole cells (⌥: half cells)' : 'half cells'} · ${g.invalid ? 'overlaps: it won\'t drop here' : 'Esc cancels'}${T.pinHint}`);
631
+ // then the real layout, with its routes and labels, once per cell (and only where it may drop)
632
+ if (changed && !g.invalid && lastS3) {
633
+ clearTimeout(relayout);
634
+ relayout = window.setTimeout(async () => {
635
+ const now = pinDrag();
636
+ if (!now || now.invalid || !now.move) return;
637
+ let next: D;
638
+ try { ({ next, keep: now.keep } = trialLayout(now)); } catch { return; }
639
+ if (pinDrag() !== now) return; // the drag ended meanwhile: don't draw a stale trial
640
+ await draw(next);
641
+ if (pinDrag() !== now) return;
642
+ now.shown = now.move.at;
643
+ shiftDragged(now.id!, [0, 0]);
644
+ paintDrag(now.parent ? { x0: now.parent.box.x0 + now.move.at[0], y0: now.parent.box.y0 + now.move.at[1], x1: now.parent.box.x0 + now.move.at[0] + now.size![0], y1: now.parent.box.y0 + now.move.at[1] + now.size![1] } : foot);
645
+ }, 0);
646
+ }
647
+ }
648
+ /**
649
+ * The drawing with the dragged item pinned at its move. Siblings placed after it (in the flow, or beside it) would move
650
+ * with it; any that did, and can be pinned, are kept where they stood, and the drop pins them too.
651
+ */
652
+ function trialLayout(g: NonNullable<typeof drag>): { next: D; keep: [string, [number, number]][] } {
653
+ const base = JSON.parse(JSON.stringify(lastData ?? {})) as Record<string, Record<string, Record<string, unknown>>>;
654
+ // pins kept under the legacy key are read there; the trial puts them where the drop will (x-editor)
655
+ if (K.pins.legacyOnly(base)) { base[PINS_KEY] = base[K.pins.legacyKey!]; delete base[K.pins.legacyKey!]; }
656
+ base[PINS_KEY] ??= {}; base[PINS_KEY].layout ??= {};
657
+ const pins = base[PINS_KEY].layout;
658
+ pins[g.name!] = { at: g.move!.at };
659
+ let next = K.draw(lastS3!, base, opts.theme);
660
+ const orig = g.origCd!, nameOf = new Map([...orig.pinId].map(([n, id]) => [id, n]));
661
+ const me = orig.scene.layout.byId.get(g.id!)!;
662
+ const sibs = me.parent ? me.parent.children : orig.scene.layout.items.filter(i => !i.parent);
663
+ const keep: [string, [number, number]][] = [];
664
+ for (const sb of sibs) {
665
+ if (sb === me) continue;
666
+ const n = nameOf.get(sb.id), was = localAt(orig.scene, sb.id), now = next.scene.layout.byId.get(sb.id)?.box;
667
+ if (!n || !was || !now || n in pins) continue;
668
+ if (Math.abs(now.x0 - sb.box.x0) > 1e-6 || Math.abs(now.y0 - sb.box.y0) > 1e-6) keep.push([n, was]);
669
+ }
670
+ if (keep.length) { for (const [n, at] of keep) pins[n] = { at }; next = K.draw(lastS3!, base, opts.theme); }
671
+ return { next, keep };
672
+ }
673
+ /** move a drawn item, and everything standing on it, by a grid offset (a transform: the next layout replaces it) */
674
+ function shiftDragged(id: string, [gx, gy]: [number, number]) {
675
+ if (!svg || !cd) return;
676
+ const [sx, sy] = [(gx - gy) * C * S, (gx + gy) * 0.5 * S];
677
+ const ids = new Set([id]);
678
+ for (const it of cd.scene.layout.items) { let p = it.parent; while (p) { if (p.id === id) { ids.add(it.id); break; } p = p.parent; } }
679
+ for (const el of svg.querySelectorAll<SVGElement>('[data-id]')) {
680
+ if (!ids.has(el.getAttribute('data-id') ?? '')) continue;
681
+ if (el.parentElement?.closest(`[data-id="${CSS.escape(el.getAttribute('data-id')!)}"]`)) continue;
682
+ el.setAttribute('transform', gx || gy ? `translate(${sx.toFixed(1)} ${sy.toFixed(1)})` : '');
683
+ }
684
+ }
685
+ /** the drag's overlay: the grid on the parent's floor (half cells too, with ⌥), the drop target, the clamped edges */
686
+ function paintDrag(foot: { x0: number; y0: number; x1: number; y1: number }) {
687
+ const g = pinDrag();
688
+ if (!g || !overlay) return;
689
+ paintOverlay();
690
+ const d = fdoc();
691
+ const wrap = d.createElementNS(SVGNS, 'g');
692
+ wrap.setAttribute('class', g.gridShown ? 'gridwrap' : 'gridwrap fresh'); // fades in once per drag, not per re-layout
693
+ g.gridShown = true;
694
+ const z = g.z0!;
695
+ const P = (x: number, y: number) => iso(x, y, z).map(v => v.toFixed(1)).join(',');
696
+ const area = g.parent ? g.parent.box : { x0: Math.floor(foot.x0) - 8, y0: Math.floor(foot.y0) - 8, x1: Math.ceil(foot.x1) + 8, y1: Math.ceil(foot.y1) + 8 };
697
+ const line = (x1: number, y1: number, x2: number, y2: number, cls: string) => {
698
+ const l = d.createElementNS(SVGNS, 'polyline');
699
+ l.setAttribute('class', cls);
700
+ l.setAttribute('points', `${P(x1, y1)} ${P(x2, y2)}`);
701
+ wrap.append(l);
702
+ };
703
+ // the grid's lines, in the parent's frame: whole cells from its origin, and half cells while ⌥ is held
704
+ const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
705
+ const st = g.step ?? 1;
706
+ for (let v = Math.ceil((area.x0 - ox) / st) * st; ox + v <= area.x1 + 1e-9; v += st) line(ox + v, area.y0, ox + v, area.y1, Number.isInteger(v) ? 'dgrid' : 'dgrid sub');
707
+ for (let v = Math.ceil((area.y0 - oy) / st) * st; oy + v <= area.y1 + 1e-9; v += st) line(area.x0, oy + v, area.x1, oy + v, Number.isInteger(v) ? 'dgrid' : 'dgrid sub');
708
+ overlay.append(wrap);
709
+ // the drop target: the footprint, accent where it may drop, red where it can't
710
+ const t = d.createElementNS(SVGNS, 'polygon');
711
+ t.setAttribute('class', `drop${g.invalid ? ' bad' : ''}`);
712
+ t.setAttribute('points', [[foot.x0, foot.y0], [foot.x1, foot.y0], [foot.x1, foot.y1], [foot.x0, foot.y1]].map(([x, y]) => P(x, y)).join(' '));
713
+ overlay.append(t);
714
+ // the parent's edges the move is held at
715
+ if (g.parent && g.move) {
716
+ const pb = g.parent.box, c = g.move.clamped, pad = g.parent.pad;
717
+ const e = (x1: number, y1: number, x2: number, y2: number) => { const l = d.createElementNS(SVGNS, 'polyline'); l.setAttribute('class', 'edge'); l.setAttribute('points', `${P(x1, y1)} ${P(x2, y2)}`); overlay!.append(l); };
718
+ if (c.left) e(pb.x0 + pad, pb.y0, pb.x0 + pad, pb.y1);
719
+ if (c.right) e(pb.x1 - pad, pb.y0, pb.x1 - pad, pb.y1);
720
+ if (c.top) e(pb.x0, pb.y0 + pad, pb.x1, pb.y0 + pad);
721
+ if (c.bottom) e(pb.x0, pb.y1 - pad, pb.x1, pb.y1 - pad);
722
+ }
723
+ }
724
+ /** end a pin drag: the drop commits one command; an overlap, a cancel or no move puts the drawing back */
725
+ async function endPin(commit: boolean) {
726
+ const g = pinDrag();
727
+ if (!g) return;
728
+ drag = undefined;
729
+ clearTimeout(relayout);
730
+ // the grid and the drop target fade out, then the drop
731
+ const shown = overlay ? [...overlay.querySelectorAll('.gridwrap, .drop, .edge')] : [];
732
+ if (shown.length) {
733
+ for (const e of shown) e.classList.add('out');
734
+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches) await new Promise(r => setTimeout(r, 160));
735
+ }
736
+ lastKey = ''; // the frame may hold a trial layout: the next render redraws
737
+ svg?.classList.remove('dragging', 'drag-bad');
738
+ paintNav();
739
+ const m = g.move;
740
+ const moved = m && (m.at[0] !== g.start![0] || m.at[1] !== g.start![1]);
741
+ if (commit && m && moved && !g.invalid) {
742
+ // the item, and the neighbours the move would have pushed, kept where they stand: one command, one undo step
743
+ const label = `Pin ${describe(fromPointer(g.ptr!))} at [${m.at.join(', ')}]`;
744
+ let keep = g.keep ?? [];
745
+ if (!g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try { keep = trialLayout(g).keep; } catch { /* drop it as it is */ }
746
+ run(doc, keep.length ? pinsCmd([[g.name!, m.at], ...keep], `${label} (${keep.map(([n]) => n).join(', ')} kept in place)`) : withPinsMoved(setCmd([PINS_KEY, 'layout', g.name!], { at: m.at }, label)), 'canvas', opts.note);
747
+ if (pendingAfterDrag && lastS3) { pendingAfterDrag = false; lastKey = ''; render(lastS3, lastData); }
748
+ return;
749
+ }
750
+ if (commit && g.invalid) opts.note(`${g.name} can't go there: it would overlap`, 'warn');
751
+ await draw(g.origCd!);
752
+ if (pendingAfterDrag && lastS3) { pendingAfterDrag = false; lastKey = ''; render(lastS3, lastData); }
753
+ }
754
+
755
+ function up(e: PointerEvent) {
756
+ const d0 = drag;
757
+ drag = undefined;
758
+ svg?.classList.remove('panning');
759
+ if (!d0) return;
760
+ const { x, y } = pageXY(e);
761
+ if ((d0.kind === 'marquee' && !d0.moved && !d0.add) || (d0.kind === 'pan' && d0.emptyClick)) doc.select([], 'canvas');
762
+ const narrow = d0.kind === 'click' ? d0.ptr : d0.kind === 'pin' && !d0.moved ? d0.narrow : undefined;
763
+ if (narrow) doc.select([fromPointer(narrow)], 'canvas');
764
+ if (d0.kind === 'pin' && d0.moved) {
765
+ // the last position the pointer reached, then the drop
766
+ drag = d0;
767
+ lastPin = { x, y, alt: e.altKey };
768
+ pinFrame = false;
769
+ pinStep();
770
+ endPin(true);
771
+ return;
772
+ }
773
+ paintOverlay();
774
+ }
775
+ let lastMarquee: { x0: number; y0: number; x1: number; y1: number } | undefined;
776
+ /** each drawn resource's footprint on the floor, its own height folded in (see the marquee) */
777
+ function footprints(): Map<string, { x0: number; y0: number; x1: number; y1: number }> {
778
+ const out = new Map<string, { x0: number; y0: number; x1: number; y1: number }>();
779
+ if (!cd) return out;
780
+ for (const [id, ptr] of cd.pathOf) {
781
+ const r = resourceOf(ptr);
782
+ if (!r || r.path !== ptr) continue;
783
+ const item = cd.scene.layout.byId.get(id);
784
+ if (!item || svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) continue;
785
+ const b = item.box, z = b.z0;
786
+ const f = { x0: b.x0 - z, y0: b.y0 - z, x1: b.x1 - z, y1: b.y1 - z };
787
+ const prev = out.get(ptr);
788
+ // a resource drawn as several things (one inside another): the union
789
+ out.set(ptr, prev ? { x0: Math.min(prev.x0, f.x0), y0: Math.min(prev.y0, f.y0), x1: Math.max(prev.x1, f.x1), y1: Math.max(prev.y1, f.y1) } : f);
790
+ }
791
+ return out;
792
+ }
793
+ const round = (v: number) => Math.round(v * 2) / 2;
794
+ const snap = ([x, y]: [number, number]): [number, number] => [round(x), round(y)];
795
+ const gridToScreen = (gx: number, gy: number): [number, number] => { const [ux, uy] = screenToGrid(1, 0), [vx, vy] = screenToGrid(0, 1); const det = ux * vy - uy * vx; return [(gx * vy - gy * vx) / det, (gy * ux - gx * uy) / det]; };
796
+
797
+ function wheel(e: WheelEvent) {
798
+ e.preventDefault();
799
+ const { x, y } = pageXY(e);
800
+ const k = scale();
801
+ // a pinch (ctrlKey on a wheel event) or ⌘-wheel always zooms; ⇧-wheel always pans sideways
802
+ if (e.ctrlKey || e.metaKey) { zoomAt(Math.exp(-e.deltaY * 0.01), x, y); return; }
803
+ if (e.shiftKey) { V.view = { ...V.view!, x: V.view!.x + (e.deltaX || e.deltaY) / k }; applyView(); return; }
804
+ if (nav.wheel === 'zoom') zoomAt(Math.exp(-e.deltaY * 0.0025), x, y);
805
+ else { V.view = { ...V.view!, x: V.view!.x + e.deltaX / k, y: V.view!.y + e.deltaY / k }; applyView(); }
806
+ }
807
+
808
+ // ---------- the menu ----------
809
+ function context(e: MouseEvent) {
810
+ e.preventDefault();
811
+ const { x, y } = pageXY(e);
812
+ if (layer?.context?.(e, { x, y })) return;
813
+ const ptr = pathAtEvent(e.target);
814
+ if (ptr !== undefined && !doc.selection.some(p => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], 'canvas');
815
+ openMenu(menuItems(ptr), { x, y }, 'Canvas');
816
+ }
817
+ function menuItems(ptr: string | undefined): MenuItem[] {
818
+ const sel = doc.selection;
819
+ const items: MenuItem[] = [];
820
+ const ro = !doc.doc.ok;
821
+ if (ptr === undefined || !sel.length) {
822
+ for (const s of ui.newOrder) items.push({ label: `New ${kindOf(s).singular}`, icon: 'plus', disabled: ro, onSelect: () => addResource(s) });
823
+ if (opts.clipItems) items.push({ sep: true }, ...opts.clipItems().filter(i => 'label' in i && i.label === 'Paste'));
824
+ items.push({ sep: true }, { label: 'Fit', keys: '0', onSelect: () => fitItems() }, { label: 'Fit the whole drawing', onSelect: () => fit() }, { label: 'Zoom 100%', keys: '1', onSelect: () => actual() });
825
+ const hasPins = !!K.pins.of(doc.goodDoc.data);
826
+ items.push({ label: 'Reset layout', icon: 'rotate-ccw', desc: 'Remove every pin (x-editor.layout)', disabled: ro || !hasPins, why: 'Nothing is pinned', onSelect: resetLayout });
827
+ return items;
828
+ }
829
+ const one = sel.length === 1 ? sel[0] : undefined;
830
+ const isRes = one && resourceOf(toPointer(one))?.path === toPointer(one);
831
+ if (one) {
832
+ items.push(...K.objectItems(doc, one, 'canvas', opts.note));
833
+ if (items.length) items.push({ sep: true });
834
+ items.push({ label: 'Rename…', icon: 'pencil', keys: 'F2', disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, 'canvas', opts.note) });
835
+ items.push({ label: 'Duplicate', icon: 'copy', keys: '⌘D', disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, 'canvas', opts.note) });
836
+ const name = isRes ? resourceOf(toPointer(one))!.name : '';
837
+ const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
838
+ if (pinned) items.push({ label: 'Unpin', icon: 'rotate-ccw', desc: 'Let the layout place it again', onSelect: () => run(doc, withPinsMoved({ ...deleteCmd([PINS_KEY, 'layout', name]), label: `Unpin ${describe(one)}` }), 'canvas', opts.note) });
839
+ items.push({ sep: true });
840
+ items.push({ label: 'Show in text', icon: 'code-xml', onSelect: () => opts.showInText(one) });
841
+ items.push({ label: 'Show in tree', icon: 'list-tree', onSelect: () => opts.showInTree(one) });
842
+ }
843
+ items.push({ label: 'Select parent', icon: 'arrow-up-right', keys: '⌘↑', onSelect: selectParent });
844
+ items.push({ label: 'Select connected', icon: 'link', desc: 'What refers to it, and what it refers to', onSelect: () => doc.select(connected(doc, sel), 'canvas') });
845
+ items.push({ label: 'Zoom to selection', keys: '⇧2', onSelect: zoomToSelection });
846
+ if (opts.clipItems) items.push({ sep: true }, ...opts.clipItems());
847
+ items.push({ sep: true }, { label: sel.length > 1 ? `Delete ${sel.length} items` : 'Delete', icon: 'trash-2', keys: '⌫', danger: true, disabled: ro, onSelect: () => deletePaths(doc, sel, 'canvas', opts.note) });
848
+ return items;
849
+ }
850
+ function addResource(s: string) {
851
+ const k = kindOf(s);
852
+ const name = freshName(doc.text, k.singular);
853
+ const p = [...k.section, name];
854
+ if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), 'canvas', opts.note)) {
855
+ doc.select([p], 'canvas');
856
+ renameDialog(doc, p, 'canvas', opts.note);
857
+ }
858
+ }
859
+ // ---------- E11: the palette: add a resource by a click, or by a drag onto the canvas ----------
860
+ /** Where a drop lands, as a pin: the new thing laid out once (a trial), then moved from where the layout put it to
861
+ * the point, in its parent's frame and on the grid. Undefined: the spot is taken, or it can't be placed. */
862
+ function placeAt(name: string, add: Command, at: { x: number; y: number }): [number, number] | undefined {
863
+ if (!cd || !svg) return undefined;
864
+ const text = add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
865
+ let trial: D | undefined;
866
+ try { trial = K.trial(text, opts.theme); } catch { return undefined; }
867
+ if (!trial) return undefined;
868
+ const id = trial.pinId.get(name), item = id ? trial.scene.layout.byId.get(id) : undefined, start = id ? localAt(trial.scene, id) : undefined;
869
+ if (!item || !start) return undefined;
870
+ const b = item.box, par = item.parent;
871
+ // the drawing's coordinates are the projection's: the trial's centre and the drop point, in the same units
872
+ const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
873
+ const centre = [(cx - cy) * C * S, (cx + cy) * 0.5 * S - b.z0 * S], drop = toSvg(at.x, at.y);
874
+ const m = snapMove(start, screenToGrid(drop.x - centre[0], drop.y - centre[1]), 1, [b.x1 - b.x0, b.y1 - b.y0],
875
+ par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region) } : undefined);
876
+ const dx = m.at[0] - start[0], dy = m.at[1] - start[1];
877
+ const moved = { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy };
878
+ const siblings = (par ? par.children : trial.scene.layout.items.filter(i => !i.parent)).filter(i => i !== item).map(i => i.box);
879
+ return overlaps(moved, siblings) ? undefined : m.at;
880
+ }
881
+ /** The container (of the kind given) whose floor a point is on (its footprint, as drawn), if any. */
882
+ function containerAt(kind: string, at: { x: number; y: number }): string | undefined {
883
+ if (!cd) return undefined;
884
+ const p = toSvg(at.x, at.y);
885
+ if (flat) {
886
+ // 2D: the innermost panel of that kind under the point
887
+ for (const id of flat.panelsAt(p.x, p.y)) {
888
+ const name = [...cd.pinId].find(([, pid]) => pid === id)?.[0];
889
+ if (name && resourceOf(cd.pathOf.get(id) ?? '')?.kind === kind) return name;
890
+ }
891
+ return undefined;
892
+ }
893
+ const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > p.y) !== (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c; } return c; };
894
+ for (const [name, id] of cd.pinId) {
895
+ if (resourceOf(cd.pathOf.get(id) ?? '')?.kind !== kind) continue;
896
+ const item = cd.scene.layout.byId.get(id);
897
+ if (item && inside(floorOf(item.box))) return name;
898
+ }
899
+ return undefined;
900
+ }
901
+ /** Add an object from the palette: dropped at a point, it is pinned there; dropped on a container the kit names, it
902
+ * is made inside it; else the layout places it. One command (one undo step); then it is selected and named. */
903
+ function addFromPalette(sec: string, at?: { x: number; y: number }): Path | undefined {
904
+ if (!doc.doc.ok) { opts.note('Fix the YAML first', 'warn'); return undefined; }
905
+ const k = kindOf(sec);
906
+ const name = freshName(doc.text, k.singular);
907
+ const p = [...k.section, name] as Path;
908
+ let value = k.template() as Record<string, unknown>;
909
+ let into: string | undefined;
910
+ const drop = at ? K.dropInto?.(sec) : undefined;
911
+ if (at && drop) {
912
+ const c = containerAt(drop.container, at);
913
+ if (c) { into = c; value = drop.value(c) as Record<string, unknown>; }
914
+ }
915
+ const label = `Add ${k.singular} ${name}${into ? drop!.label(into) : ''}`;
916
+ const add = insertCmd(p.slice(0, -1), name, value, { label });
917
+ const pin = at && !into && mode === '3d' ? placeAt(name, add, at) : undefined;
918
+ const cmd = pin ? seqCmd(`${label} at [${pin.join(', ')}]`, [add, withPinsMoved(setCmd([PINS_KEY, 'layout', name], { at: pin }))]) : add;
919
+ if (!run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) return undefined;
920
+ if (at && !into && !pin) opts.note(mode === '2d' ? `${k.singular} ${name} added; the layout placed it (in 3D a drop pins it where it lands)` : `${k.singular} ${name} added; that spot is taken, so the layout placed it`);
921
+ doc.select([p], 'canvas');
922
+ renameDialog(doc, p, 'canvas', opts.note);
923
+ return p;
924
+ }
925
+ const palette = h('div', { class: 'palette', role: 'toolbar', 'aria-label': T.palette, 'aria-orientation': 'vertical' });
926
+ for (const { kind: sec, icon: ic, label } of ui.palette) {
927
+ const b = h('button', { type: 'button', class: 'pal-item', 'data-section': sec, title: `Add ${label.toLowerCase()} (click), or drag it where it goes` }, icon(ic), h('span', { class: 'pal-label' }, label));
928
+ b.addEventListener('pointerdown', e => {
929
+ if (e.button !== 0) return;
930
+ e.preventDefault();
931
+ try { b.setPointerCapture(e.pointerId); } catch { /* a synthetic pointer: the events come to the button anyway */ }
932
+ const x0 = e.clientX, y0 = e.clientY;
933
+ let ghost: HTMLElement | undefined;
934
+ const over = (ev: PointerEvent) => { const r = stage.getBoundingClientRect(); return ev.clientX >= r.left && ev.clientX <= r.right && ev.clientY >= r.top && ev.clientY <= r.bottom && !palette.contains(document.elementFromPoint(ev.clientX, ev.clientY)); };
935
+ const mv = (ev: PointerEvent) => {
936
+ if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
937
+ if (!ghost) { ghost = h('div', { class: 'pal-ghost', 'aria-hidden': 'true' }, icon(ic), label); host.append(ghost); }
938
+ const hr = host.getBoundingClientRect();
939
+ ghost.style.left = `${ev.clientX - hr.left + 8}px`; ghost.style.top = `${ev.clientY - hr.top + 8}px`;
940
+ ghost.classList.toggle('bad', !over(ev));
941
+ };
942
+ const done = (ev: PointerEvent, drop: boolean) => {
943
+ b.removeEventListener('pointermove', mv); b.removeEventListener('pointerup', upH); b.removeEventListener('pointercancel', cancelH); removeEventListener('keydown', esc, true);
944
+ const dragged = !!ghost;
945
+ ghost?.remove();
946
+ if (!drop) return;
947
+ if (!dragged) addFromPalette(sec);
948
+ else if (over(ev)) addFromPalette(sec, { x: ev.clientX, y: ev.clientY });
949
+ };
950
+ const upH = (ev: PointerEvent) => done(ev, true), cancelH = (ev: PointerEvent) => done(ev, false);
951
+ const esc = (ev: KeyboardEvent) => { if (ev.key === 'Escape') { ev.stopPropagation(); ev.preventDefault(); done(e, false); } };
952
+ b.addEventListener('pointermove', mv); b.addEventListener('pointerup', upH); b.addEventListener('pointercancel', cancelH); addEventListener('keydown', esc, true);
953
+ });
954
+ // the keyboard: Enter or the space key adds (the layout places it)
955
+ b.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); addFromPalette(sec); } });
956
+ palette.append(b);
957
+ }
958
+ host.append(palette);
959
+
960
+ function resetLayout() {
961
+ // wherever the pins are (x-editor, or the legacy key): removed, and their key too if it holds nothing else
962
+ const key = K.pins.keyOf(doc.goodDoc.data);
963
+ const x = (doc.goodDoc.data as Record<string, Record<string, unknown>> | undefined)?.[key];
964
+ const only = x && Object.keys(x).length === 1;
965
+ run(doc, { ...deleteCmd(only ? [key] : [key, 'layout']), label: 'Reset the layout' }, 'canvas', opts.note);
966
+ }
967
+ function selectParent() {
968
+ const up = new Map<string, Path>();
969
+ for (const p of doc.selection) {
970
+ const r = resourceOf(toPointer(p));
971
+ // a property → its object; an object → its kind's section; a section → the root
972
+ const q = r && r.path !== toPointer(p) ? fromPointer(r.path) : r ? kindOf(r.kind).section : [];
973
+ up.set(toPointer(q), q);
974
+ }
975
+ doc.select([...up.values()], 'canvas');
976
+ }
977
+
978
+ // ---------- keys ----------
979
+ function key(e: KeyboardEvent) {
980
+ if (e.type === 'keyup' && e.key !== ' ') return;
981
+ if (e.key === ' ') { spaceKeyDown = e.type === 'keydown'; svg?.classList.toggle(ui.panKeyClass, spaceKeyDown); e.preventDefault(); return; }
982
+ const lk = layer?.key?.(e);
983
+ if (lk === 'ignore') return;
984
+ if (lk === 'handled') { e.preventDefault(); e.stopPropagation(); return; }
985
+ const mod = e.metaKey || e.ctrlKey;
986
+ const sel = doc.selection;
987
+ const drawn = [...new Set([...(cd?.pathOf.values() ?? [])].filter(p => resourceOf(p)?.path === p))];
988
+ const ro = !doc.doc.ok;
989
+ switch (e.key) {
990
+ case '+': case '=': zoomAt(1.25); break;
991
+ case '-': case '_': zoomAt(0.8); break;
992
+ case '0': fitItems(); break;
993
+ case '1': actual(); break;
994
+ case '@': case '2': if (e.shiftKey || e.key === '@') zoomToSelection(); else return; break;
995
+ case 'Escape': if (pinDrag()) { endPin(false); break; } doc.select([], 'canvas'); break;
996
+ case 'Delete': case 'Backspace': if (sel.length && !ro) deletePaths(doc, sel, 'canvas', opts.note); break;
997
+ case 'F2': if (sel.length === 1 && !ro) renameDialog(doc, sel[0], 'canvas', opts.note); break;
998
+ case 'ArrowUp': if (mod) { selectParent(); break; } return;
999
+ case 'Tab': case 'ArrowRight': case 'ArrowLeft': case 'ArrowDown': {
1000
+ // move through what is drawn, in the file's order
1001
+ if (!drawn.length) return;
1002
+ const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
1003
+ const back = e.key === 'ArrowLeft' || (e.key === 'Tab' && e.shiftKey);
1004
+ const j = i < 0 ? 0 : (i + (back ? -1 : 1) + drawn.length) % drawn.length;
1005
+ doc.select([fromPointer(drawn[j])], 'canvas');
1006
+ zoomIfOutside(fromPointer(drawn[j]));
1007
+ break;
1008
+ }
1009
+ case 'ContextMenu': case 'F10':
1010
+ if (e.key === 'F10' && !e.shiftKey) return;
1011
+ { const b = unionBox(sel); const r = host.getBoundingClientRect(); const k = scale(); openMenu(menuItems(sel.length ? toPointer(sel[0]) : undefined), b ? { x: r.left + (b.x + b.w - V.view!.x) * k, y: r.top + (b.y - V.view!.y) * k } : { x: r.left + 40, y: r.top + 40 }, 'Canvas'); }
1012
+ break;
1013
+ default:
1014
+ if (mod && e.key.toLowerCase() === 'd' && sel.length === 1 && !ro) { duplicate(doc, sel[0], 'canvas', opts.note); break; }
1015
+ if (mod && e.key.toLowerCase() === 'a') { doc.select(drawn.map(fromPointer), 'canvas'); break; }
1016
+ return;
1017
+ }
1018
+ e.preventDefault();
1019
+ e.stopPropagation();
1020
+ }
1021
+ stage.addEventListener('keydown', key);
1022
+ stage.addEventListener('keyup', key);
1023
+ const focusMark = (on: boolean) => host.classList.toggle('has-focus', on);
1024
+ stage.addEventListener('focus', () => focusMark(true));
1025
+ stage.addEventListener('blur', () => focusMark(false));
1026
+ paintNav();
1027
+ function zoomIfOutside(p: Path) {
1028
+ const b = boxFor(p);
1029
+ if (!b || !V.view) return;
1030
+ if (b.x < V.view.x || b.y < V.view.y || b.x + b.w > V.view.x + V.view.w || b.y + b.h > V.view.y + V.view.h) { V.view = { ...V.view, x: b.x + b.w / 2 - V.view.w / 2, y: b.y + b.h / 2 - V.view.h / 2 }; applyView(); }
1031
+ }
1032
+
1033
+ /** bring these into view: pan to them, and zoom out if they don't fit (never in) */
1034
+ function reveal(paths: Path[]): boolean {
1035
+ if (!V.view || !paths.length) return true;
1036
+ const bs = paths.map(boxFor);
1037
+ if (bs.some(b => !b)) return false; // not drawn yet (just pasted): after the next render
1038
+ const b = union(bs as { x: number; y: number; w: number; h: number }[])!;
1039
+ const m = 24 / scale();
1040
+ if (b.x - m >= V.view.x && b.y - m >= V.view.y && b.x + b.w + m <= V.view.x + V.view.w && b.y + b.h + m <= V.view.y + V.view.h) return true;
1041
+ if (b.w + 2 * m > V.view.w || b.h + 2 * m > V.view.h) { fit({ x: b.x - m, y: b.y - m, w: b.w + 2 * m, h: b.h + 2 * m }); return true; }
1042
+ V.view = { ...V.view, x: b.x + b.w / 2 - V.view.w / 2, y: b.y + b.h / 2 - V.view.h / 2 };
1043
+ applyView();
1044
+ return true;
1045
+ }
1046
+ let pendingReveal: Path[] | undefined;
1047
+ ifEvents();
1048
+ doc.onSelect(c => {
1049
+ paintOverlay();
1050
+ if (c.origin === 'canvas' || !c.paths.length) return;
1051
+ // a selection made elsewhere (the tree, a paste): shown here, once it is drawn
1052
+ pendingReveal = reveal(c.paths) ? undefined : c.paths;
1053
+ });
1054
+
1055
+ const base = {
1056
+ addFromPalette, palette,
1057
+ render, setTheme, paintOverlay, fit: fitItems, fitAll: fit, actual, zoomAt, itemsBox, get moved() { return V.moved; }, settled, get zoom() { return V.zoom; },
1058
+ dispose() { endMorph(); clearTimeout(relayout); V.dispose(); disposed = true; },
1059
+ focus: () => stage.focus(),
1060
+ /** for the tests */
1061
+ get view() { return V.view; },
1062
+ get doc() { return cd; },
1063
+ /** the view (3D or 2D), and the 2D layout while it shows */
1064
+ get mode() { return mode; }, setMode, get flat() { return flat?.layout; },
1065
+ stage, key, scale: () => scale(), nav, paintNav, outlinesFor, footprints, get drag() { return pinDrag(); }, get lastMarquee() { return lastMarquee; },
1066
+ boxFor, pageXYOf: (p: Path) => { const b = boxFor(p); const r = host.getBoundingClientRect(); const k = scale(); return b && V.view ? { x: r.left + (b.x + b.w / 2 - V.view.x) * k, y: r.top + (b.y + b.h / 2 - V.view.y) * k } : undefined; },
1067
+ };
1068
+ // the layer's calls, as they are (its getters stay getters)
1069
+ if (layer) Object.defineProperties(base, Object.getOwnPropertyDescriptors(layer.api));
1070
+ return base as typeof base & A;
1071
+ }