@johnoscott/isometric-engine 0.0.0-stage → 0.10.1

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 +355 -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 +269 -0
  8. package/assets/default-theme.yaml +99 -0
  9. package/assets/icons.svg +1 -0
  10. package/assets/marks.css +39 -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 +443 -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 +1403 -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 +149 -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 +511 -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 +147 -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 +477 -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 +1227 -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 +39 -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 +153 -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 +178 -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 +307 -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 +49 -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,1403 @@
1
+ import { h, icon } from "./icons.js";
2
+ import { openMenu } from "./menu.js";
3
+ import { run } from "./actions.js";
4
+ import { screenToGrid, localAt, boxSilhouette, floorOf, snapMove, overlaps, paddingOf } from "../../iso-objects/geometry.js";
5
+ import { regionKind } from "../../iso-objects/kinds.js";
6
+ import { iso, C, S } from "../../iso-core/kernel.js";
7
+ import { applyStep } from "../splice.js";
8
+ import { seqCmd } from "../commands.js";
9
+ import { fromPointer, toPointer } from "../path.js";
10
+ import { buildSvg } from "../../iso-core/svg-dom.js";
11
+ import { viewport } from "../../iso-viewer/viewport.js";
12
+ const SVGNS = "http://www.w3.org/2000/svg";
13
+ function canvasView(host, doc, opts) {
14
+ const K = opts.kit, ui = K.ui, T = ui.text;
15
+ const { setCmd, deleteCmd, insertCmd, insertItemCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
16
+ const { deletePaths, renameDialog, duplicate, connected } = K.actions;
17
+ const resourceOf = (ptr) => K.objectOf(ptr);
18
+ const kindOf = (k) => K.kinds.find((x) => x.kind === k);
19
+ const PINS_KEY = K.pins.key;
20
+ let linking;
21
+ host.classList.add("canvas");
22
+ const stage = h("div", { class: `${ui.rootClass} canvas-stage`, tabindex: "0", role: "application", "aria-label": T.stage });
23
+ const tools = h("div", { class: "canvas-tools", role: "toolbar", "aria-label": "Canvas" });
24
+ const zoomOut = h("button", { type: "button", class: "btn sm quiet icon-only", "aria-label": "Zoom out (\u2212)", title: "Zoom out (\u2212)" }, "\u2212");
25
+ const zoomLabel = h("button", { type: "button", class: "btn sm quiet zoom-label", title: "Fit (0) \xB7 100% (1)" }, "100%");
26
+ const zoomIn = h("button", { type: "button", class: "btn sm quiet icon-only", "aria-label": "Zoom in (+)", title: "Zoom in (+)" }, "+");
27
+ const fitBtn = h("button", { type: "button", class: "btn sm quiet", title: "Fit (0)" }, "Fit");
28
+ const seg = (label, key2, values) => {
29
+ const g = h("div", { class: "segmented", role: "group", "aria-label": label, title: label });
30
+ for (const [v, text, tip] of values) {
31
+ const b = h("button", { type: "button", class: "seg", "data-v": v, title: tip }, text);
32
+ b.addEventListener("click", () => {
33
+ nav[key2] = v;
34
+ saveNav();
35
+ paintNav();
36
+ });
37
+ g.append(b);
38
+ }
39
+ return g;
40
+ };
41
+ const wheelSeg = seg("The wheel", "wheel", [["zoom", "Zoom", "The wheel zooms around the pointer; \u21E7-wheel pans sideways"], ["scroll", "Scroll", "The wheel pans; \u21E7-wheel pans sideways; a pinch zooms"]]);
42
+ const dragSeg = seg(T.dragGroup, "drag", [["pan", "Pan", "Drag pans; \u21E7- or \u2318-drag draws a selection"], ["select", "Select", T.dragSelectTip]]);
43
+ let mode = "3d";
44
+ let flat, flatImpl;
45
+ const loadFlat = async () => flatImpl ??= await K.flat.load();
46
+ const viewSeg = h("div", { class: "segmented view-seg", role: "group", "aria-label": "The view" });
47
+ 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"]]) {
48
+ const b = h("button", { type: "button", class: "seg", "data-v": v, title: tip }, text);
49
+ b.addEventListener("click", () => setMode(v));
50
+ viewSeg.append(b);
51
+ }
52
+ const ctx = {
53
+ host,
54
+ doc,
55
+ cd: () => cd,
56
+ svg: () => svg,
57
+ elementsFor: (p) => elementsFor(p),
58
+ boxOf: (e) => boxOf(e),
59
+ union: (bs) => union(bs),
60
+ outlinesFor: (p) => outlinesFor(p),
61
+ scale: () => scale(),
62
+ full: () => V.full,
63
+ toSvg: (x, y) => toSvg(x, y),
64
+ autoFit: () => autoFit(),
65
+ paint: () => paintOverlay(),
66
+ reveal: (p) => zoomIfOutside(p),
67
+ note: (m, tone) => opts.note(m, tone)
68
+ };
69
+ const layer = opts.layer?.(ctx);
70
+ tools.append(...layer?.tools ?? [], ...K.flat ? [viewSeg] : [], wheelSeg, dragSeg, zoomOut, zoomLabel, zoomIn, fitBtn);
71
+ const empty = h("div", { class: "canvas-empty", hidden: true });
72
+ host.append(stage, tools, empty, ...layer?.marks ?? []);
73
+ const nav = { wheel: "zoom", drag: "pan" };
74
+ try {
75
+ Object.assign(nav, JSON.parse(opts.store?.get("canvas-nav") ?? "{}"));
76
+ } catch {
77
+ }
78
+ if (K.flat && opts.store?.get("canvas-view") === "2d") mode = "2d";
79
+ function setMode(m) {
80
+ if (!K.flat || m === mode) return;
81
+ endMorph();
82
+ const was = mode;
83
+ mode = m;
84
+ opts.store?.set("canvas-view", m);
85
+ paintNav();
86
+ if (svg && cd && svg.parentNode === stage) morphFrom = { svg, mode: was };
87
+ if (lastS3 !== void 0) {
88
+ V.view = void 0;
89
+ lastKey = "";
90
+ void render(lastS3, lastData);
91
+ }
92
+ }
93
+ const saveNav = () => opts.store?.set("canvas-nav", JSON.stringify(nav));
94
+ function paintNav() {
95
+ for (const [g, v] of [[wheelSeg, nav.wheel], [dragSeg, nav.drag], [viewSeg, mode]]) for (const b of g.querySelectorAll(".seg")) b.setAttribute("aria-pressed", String(b.dataset.v === v));
96
+ svg?.classList.toggle("mode-pan", nav.drag === "pan");
97
+ svg?.classList.toggle("mode-select", nav.drag === "select");
98
+ if (drag?.kind === "pin" && drag.moved) {
99
+ svg?.classList.add("dragging");
100
+ svg?.classList.toggle("drag-bad", !!drag.invalid);
101
+ return;
102
+ }
103
+ opts.onHint?.(`${nav.drag === "pan" ? "Drag: pan \xB7 \u21E7-drag: select" : "Drag: select \xB7 space-drag: pan"} \xB7 Wheel: ${nav.wheel === "zoom" ? "zoom" : "scroll"}`);
104
+ }
105
+ let cd;
106
+ let svg;
107
+ let overlay;
108
+ let lastKey = "";
109
+ let hoverId;
110
+ const fdoc = () => document;
111
+ let disposed = false;
112
+ async function render(s3, data) {
113
+ if (disposed) return;
114
+ if (!s3) {
115
+ showEmpty(T.unreadable);
116
+ return;
117
+ }
118
+ const key2 = JSON.stringify(data);
119
+ if (key2 === lastKey && svg) {
120
+ if (!pinDrag()) paintOverlay();
121
+ return;
122
+ }
123
+ if (mode === "2d" && !flatImpl) {
124
+ try {
125
+ await loadFlat();
126
+ } catch (e) {
127
+ mode = "3d";
128
+ paintNav();
129
+ opts.note(`The 2D view couldn't load: ${e.message}`, "warn");
130
+ }
131
+ }
132
+ let next;
133
+ try {
134
+ next = K.draw(s3, data, opts.theme);
135
+ } catch (e) {
136
+ showEmpty(`The canvas couldn't draw this: ${e.message}`);
137
+ return;
138
+ }
139
+ if (next.diags.length) {
140
+ showEmpty(`The canvas couldn't draw this: ${next.diags[0]}`);
141
+ return;
142
+ }
143
+ lastKey = key2;
144
+ lastS3 = s3;
145
+ lastData = data;
146
+ if (pinDrag()) {
147
+ pendingAfterDrag = true;
148
+ return;
149
+ }
150
+ await draw(next);
151
+ if (cd.pinNotes.length) opts.note(`Pins: ${cd.pinNotes.join("; ")}`, "warn");
152
+ }
153
+ let lastS3, lastData, pendingAfterDrag = false;
154
+ let morphFrom;
155
+ let morphing;
156
+ function endMorph() {
157
+ if (!morphing) return;
158
+ const r = morphing;
159
+ morphing = void 0;
160
+ r.m.finish();
161
+ r.from.remove();
162
+ r.to.style.visibility = "";
163
+ }
164
+ function startMorph(from, to) {
165
+ const m = flatImpl?.morph?.(stage, cd.scene, from, to, { motion: K.flat?.motion, duration: K.flat?.duration });
166
+ if (!m) {
167
+ from.svg.remove();
168
+ return;
169
+ }
170
+ from.svg.style.visibility = "hidden";
171
+ to.style.visibility = "hidden";
172
+ const me = { m, from: from.svg, to };
173
+ morphing = me;
174
+ stage.classList.add("morphing");
175
+ void m.done.then(() => {
176
+ if (morphing === me) endMorph();
177
+ stage.classList.remove("morphing");
178
+ });
179
+ }
180
+ async function draw(next) {
181
+ endMorph();
182
+ let s;
183
+ let full = next.scene.rendered.viewBox;
184
+ try {
185
+ if (mode === "2d" && flatImpl) {
186
+ flat = flatImpl.draw(next.scene, stage, { styles: K.flat?.styles, title: K.flat?.title, options: K.flat?.options });
187
+ full = flat.full;
188
+ s = buildSvg(flat.svg);
189
+ for (const e of s.querySelectorAll("[tabindex]")) {
190
+ e.removeAttribute("tabindex");
191
+ e.removeAttribute("role");
192
+ }
193
+ } else {
194
+ flat = void 0;
195
+ s = buildSvg(next.svg);
196
+ }
197
+ } catch (e) {
198
+ showEmpty(`The canvas couldn't draw this: ${e.message}`);
199
+ return;
200
+ }
201
+ cd = next;
202
+ s.classList.add("scene");
203
+ s.removeAttribute("width");
204
+ s.removeAttribute("height");
205
+ s.setAttribute("preserveAspectRatio", "xMidYMid meet");
206
+ s.setAttribute("aria-hidden", "true");
207
+ overlay = document.createElementNS(SVGNS, "g");
208
+ overlay.setAttribute("class", "overlay");
209
+ overlay.setAttribute("fill", "none");
210
+ overlay.setAttribute("stroke", "currentColor");
211
+ overlay.setAttribute("pointer-events", "none");
212
+ s.append(overlay, ...layer?.groups?.() ?? []);
213
+ const from = morphFrom;
214
+ morphFrom = void 0;
215
+ if (from && svg === from.svg && svg.parentNode === stage) {
216
+ from.svg.querySelector(".overlay")?.replaceChildren();
217
+ from.svg.style.position = "absolute";
218
+ from.svg.style.inset = "0";
219
+ stage.append(s);
220
+ } else if (svg?.parentNode === stage) svg.replaceWith(s);
221
+ else stage.append(s);
222
+ svg = s;
223
+ const [x, y, w, hh] = full;
224
+ V.full = { x, y, w, h: hh };
225
+ if (!V.view) {
226
+ V.view = { ...V.full };
227
+ autoFit();
228
+ } else quietly(applyView);
229
+ empty.hidden = true;
230
+ layer?.drawn?.();
231
+ if (pendingReveal && reveal(pendingReveal)) pendingReveal = void 0;
232
+ paintNav();
233
+ paintOverlay();
234
+ if (from && from.svg !== s) {
235
+ if (getComputedStyle(stage).position === "static") stage.style.position = "relative";
236
+ startMorph(from, s);
237
+ }
238
+ }
239
+ function showEmpty(t) {
240
+ morphFrom = void 0;
241
+ empty.textContent = t;
242
+ empty.hidden = false;
243
+ }
244
+ function setTheme(_t) {
245
+ paintOverlay();
246
+ }
247
+ function itemsBox() {
248
+ if (!cd || !svg) return void 0;
249
+ const ptrs = [...new Set([...cd.pathOf.values()].filter((p) => {
250
+ const r = resourceOf(p);
251
+ return r && r.path === p;
252
+ }))];
253
+ const live = layer?.extent?.() ?? [];
254
+ return union([...ptrs.flatMap((p) => elementsFor(p)).filter((e) => e.getBBox().width || e.getBBox().height).map(boxOf), ...live]);
255
+ }
256
+ const V = viewport(host, {
257
+ svg: () => svg,
258
+ onApply: (k) => {
259
+ svg.classList.toggle("zoom-near", k >= 1);
260
+ const pct = Math.round(k * 100);
261
+ zoomLabel.textContent = `${pct}%`;
262
+ opts.onZoom(pct);
263
+ },
264
+ onRezoom: () => paintOverlay(),
265
+ itemsBox: () => itemsBox(),
266
+ marksShowing: () => !!layer?.showing?.()
267
+ });
268
+ const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
269
+ function zoomToSelection() {
270
+ const b = unionBox(doc.selection);
271
+ if (b) fit({ x: b.x - 20, y: b.y - 20, w: b.w + 40, h: b.h + 40 });
272
+ }
273
+ zoomIn.addEventListener("click", () => zoomAt(1.25));
274
+ zoomOut.addEventListener("click", () => zoomAt(0.8));
275
+ zoomLabel.addEventListener("click", () => fitItems());
276
+ fitBtn.addEventListener("click", () => fitItems());
277
+ const elementsFor = (ptr) => {
278
+ if (!svg || !cd) return [];
279
+ const ids = [...cd.pathOf.entries()].filter(([, p]) => p === ptr || ptr && p.startsWith(ptr + "/") && false).map(([id]) => id);
280
+ return ids.flatMap((id) => [...svg.querySelectorAll(`[data-id="${CSS.escape(id)}"]`)]).filter((e) => !e.closest(".pre") && !e.classList.contains("pre"));
281
+ };
282
+ const boxOf = (e) => {
283
+ const b = e.getBBox();
284
+ const m = e.getCTM(), root = svg.getCTM();
285
+ if (!m || !root) return { x: b.x, y: b.y, w: b.width, h: b.height };
286
+ const t = root.inverse().multiply(m);
287
+ 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 }));
288
+ const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y);
289
+ return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
290
+ };
291
+ const union = (bs) => {
292
+ if (!bs.length) return void 0;
293
+ 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));
294
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
295
+ };
296
+ const boxFor = (p) => {
297
+ const own = toPointer(p);
298
+ let els = elementsFor(own);
299
+ const r = resourceOf(own);
300
+ if (!els.length && r && r.path !== own) els = elementsFor(r.path);
301
+ return els.length ? union(els.filter((e) => e.getBBox().width || e.getBBox().height).map(boxOf)) : void 0;
302
+ };
303
+ const unionBox = (ps) => union(ps.map(boxFor).filter((b) => !!b));
304
+ const pathAtEvent = (target) => {
305
+ const el = target?.closest?.("[data-id]");
306
+ if (!el || !cd) return void 0;
307
+ let e = el;
308
+ while (e) {
309
+ const id = e.getAttribute("data-id");
310
+ if (id && cd.pathOf.has(id)) return cd.pathOf.get(id);
311
+ e = e.parentElement?.closest("[data-id]") ?? null;
312
+ }
313
+ return void 0;
314
+ };
315
+ function outlinesFor(ptr) {
316
+ if (!cd) return [];
317
+ const out = [];
318
+ const mine = new Set([...cd.pathOf].filter(([, p]) => p === ptr).map(([id]) => id));
319
+ if (flat && svg) return flat.outlines(mine, svg);
320
+ for (const [id, p] of cd.pathOf) {
321
+ if (p !== ptr) continue;
322
+ const item = cd.scene.layout.byId.get(id);
323
+ let up2 = item?.parent;
324
+ while (up2 && !mine.has(up2.id)) up2 = up2.parent;
325
+ if (up2) continue;
326
+ if (item) {
327
+ if (svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) continue;
328
+ const shape = regionKind(K.catalog, item.region?.kind)?.shape;
329
+ const solid = item.type === "node" || shape === "slab" || shape === "block";
330
+ out.push({ kind: "poly", id, points: solid ? boxSilhouette(item.box) : floorOf(item.box) });
331
+ } else if (cd.scene.rendered.paths[id] && !svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) {
332
+ out.push({ kind: "route", d: cd.scene.rendered.paths[id] });
333
+ }
334
+ }
335
+ return out;
336
+ }
337
+ function paintOverlay() {
338
+ V.painted(V.view ? scale() : 0);
339
+ if (!overlay || !svg) return;
340
+ const d = fdoc();
341
+ overlay.replaceChildren();
342
+ const ring = (b, cls, pad = 4) => {
343
+ const r = d.createElementNS(SVGNS, "rect");
344
+ r.setAttribute("class", cls);
345
+ r.setAttribute("x", String(b.x - pad));
346
+ r.setAttribute("y", String(b.y - pad));
347
+ r.setAttribute("width", String(b.w + pad * 2));
348
+ r.setAttribute("height", String(b.h + pad * 2));
349
+ r.setAttribute("rx", "6");
350
+ overlay.append(r);
351
+ };
352
+ const draw2 = (ptr, cls) => {
353
+ const r = resourceOf(ptr);
354
+ let shapes = outlinesFor(ptr);
355
+ if (!shapes.length && r && r.path !== ptr) shapes = outlinesFor(r.path);
356
+ if (!shapes.length) {
357
+ const b = boxFor(fromPointer(ptr));
358
+ if (b) ring(b, cls, cls === "hover" ? 3 : 4);
359
+ return;
360
+ }
361
+ for (const sh of shapes) {
362
+ if (sh.kind === "route") {
363
+ const r2 = d.createElementNS(SVGNS, "path");
364
+ r2.setAttribute("class", cls === "ring" ? "route-ring" : "route-hover");
365
+ r2.setAttribute("d", sh.d);
366
+ overlay.append(r2);
367
+ } else {
368
+ const r2 = d.createElementNS(SVGNS, "polygon");
369
+ r2.setAttribute("class", cls);
370
+ r2.setAttribute("points", sh.points.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(" "));
371
+ r2.setAttribute("data-for", sh.id);
372
+ overlay.append(r2);
373
+ }
374
+ }
375
+ };
376
+ if (hoverId !== void 0 && !doc.selection.some((p) => toPointer(p) === hoverId)) draw2(hoverId, "hover");
377
+ for (const p of doc.selection) draw2(toPointer(p), "ring");
378
+ const one = connectable();
379
+ const from = linking?.from ?? one;
380
+ const fb = from ? boxFor(fromPointer(from.path)) : void 0;
381
+ if (fb && K.connect) {
382
+ const k = scale(), hx = fb.x + fb.w + 10 / k, hy = fb.y + fb.h / 2;
383
+ if (linking && linking.x !== void 0 && linking.y !== void 0) {
384
+ if (linking.over) draw2(linking.over, "hover");
385
+ const l = d.createElementNS(SVGNS, "line");
386
+ l.setAttribute("class", `connect-line${linking.over ? " ok" : ""}`);
387
+ l.setAttribute("x1", String(hx));
388
+ l.setAttribute("y1", String(hy));
389
+ l.setAttribute("x2", String(linking.x));
390
+ l.setAttribute("y2", String(linking.y));
391
+ overlay.append(l);
392
+ }
393
+ if (!linking) {
394
+ const c = d.createElementNS(SVGNS, "circle");
395
+ c.setAttribute("class", "connect-handle");
396
+ c.setAttribute("cx", String(hx));
397
+ c.setAttribute("cy", String(hy));
398
+ c.setAttribute("r", String(7 / k));
399
+ c.style.pointerEvents = "all";
400
+ c.style.cursor = "crosshair";
401
+ const t = d.createElementNS(SVGNS, "title");
402
+ t.textContent = `Drag to what ${from.name} connects to`;
403
+ c.append(t);
404
+ overlay.append(c);
405
+ }
406
+ }
407
+ const counts = /* @__PURE__ */ new Map();
408
+ for (const pr of opts.problems()) {
409
+ if (pr.file) continue;
410
+ const r = resourceOf(pr.path);
411
+ if (!r) continue;
412
+ const c = counts.get(r.path) ?? { e: 0, w: 0 };
413
+ if (pr.severity === "error") c.e++;
414
+ else c.w++;
415
+ counts.set(r.path, c);
416
+ }
417
+ for (const [ptr, c] of counts) {
418
+ const els = elementsFor(ptr).filter((e) => cd.scene.layout.byId.has(e.getAttribute("data-id") ?? ""));
419
+ const b = union(els.map(boxOf));
420
+ if (!b) continue;
421
+ const g = d.createElementNS(SVGNS, "g");
422
+ g.setAttribute("class", `badge${c.e ? "" : " warn"}`);
423
+ const k = scale();
424
+ const cx = b.x + b.w, cy = b.y, rr = 9 / k;
425
+ const circle = d.createElementNS(SVGNS, "circle");
426
+ circle.setAttribute("cx", String(cx));
427
+ circle.setAttribute("cy", String(cy));
428
+ circle.setAttribute("r", String(rr));
429
+ const t = d.createElementNS(SVGNS, "text");
430
+ t.setAttribute("x", String(cx));
431
+ t.setAttribute("y", String(cy));
432
+ t.style.fontSize = `${(11 / k).toFixed(2)}px`;
433
+ t.textContent = String(c.e || c.w);
434
+ g.append(circle, t);
435
+ overlay.append(g);
436
+ }
437
+ layer?.paint?.(d);
438
+ }
439
+ let drag;
440
+ let spaceKeyDown = false;
441
+ const ifEvents = () => {
442
+ stage.addEventListener("pointerdown", down);
443
+ stage.addEventListener("pointermove", move);
444
+ stage.addEventListener("pointerup", up);
445
+ stage.addEventListener("pointercancel", up);
446
+ stage.addEventListener("wheel", wheel, { passive: false });
447
+ stage.addEventListener("contextmenu", context);
448
+ stage.addEventListener("dblclick", (e) => {
449
+ const p = pathAtEvent(e.target);
450
+ if (p !== void 0) opts.showInText(fromPointer(p));
451
+ });
452
+ };
453
+ const pageXY = (e) => ({ x: e.clientX, y: e.clientY });
454
+ const capture = (e) => {
455
+ try {
456
+ stage.setPointerCapture(e.pointerId);
457
+ } catch {
458
+ }
459
+ };
460
+ function down(e) {
461
+ stage.focus({ preventScroll: true });
462
+ if (layer?.down?.(e)) return;
463
+ const { x, y } = pageXY(e);
464
+ if (e.button === 0 && linking?.pick) {
465
+ e.preventDefault();
466
+ endConnect(pathAtEvent(e.target));
467
+ return;
468
+ }
469
+ if (e.button === 0 && e.target?.closest?.(".connect-handle")) {
470
+ const one = connectable();
471
+ if (one) {
472
+ capture(e);
473
+ e.preventDefault();
474
+ const p2 = toSvg(x, y);
475
+ linking = { from: one, x: p2.x, y: p2.y };
476
+ paintOverlay();
477
+ return;
478
+ }
479
+ }
480
+ if (e.button === 0 || e.button === 1) capture(e);
481
+ const pan = () => {
482
+ drag = { kind: "pan", x0: x, y0: y, v0: { ...V.view } };
483
+ svg?.classList.add("panning");
484
+ e.preventDefault();
485
+ };
486
+ if (e.button === 1 || spaceKeyDown) {
487
+ pan();
488
+ return;
489
+ }
490
+ if (e.button !== 0) return;
491
+ const ptr = pathAtEvent(e.target);
492
+ if (ptr === void 0) {
493
+ const mod = e.shiftKey || e.metaKey || e.ctrlKey;
494
+ if (nav.drag === "pan" && !mod) {
495
+ drag = { kind: "pan", x0: x, y0: y, v0: { ...V.view }, emptyClick: true };
496
+ svg?.classList.add("panning");
497
+ return;
498
+ }
499
+ const add = nav.drag === "select" && mod;
500
+ drag = { kind: "marquee", x0: x, y0: y, sel0: add ? doc.selection : [], add, touch: e.altKey };
501
+ return;
502
+ }
503
+ const p = fromPointer(ptr);
504
+ const sel = doc.selection.map(toPointer);
505
+ if (e.shiftKey || e.metaKey || e.ctrlKey) {
506
+ doc.select(sel.includes(ptr) ? doc.selection.filter((q) => toPointer(q) !== ptr) : [...doc.selection, p], "canvas");
507
+ return;
508
+ }
509
+ if (!sel.includes(ptr)) doc.select([p], "canvas");
510
+ const narrow = sel.includes(ptr) && sel.length > 1 ? ptr : void 0;
511
+ drag = { kind: "click", x0: x, y0: y, ptr: narrow };
512
+ const r = resourceOf(ptr);
513
+ const name = r && r.path === ptr ? r.name : void 0;
514
+ const id = name && mode === "3d" ? cd?.pinId.get(name) : void 0;
515
+ if (id && cd) {
516
+ const item = cd.scene.layout.byId.get(id);
517
+ const start = localAt(cd.scene, id);
518
+ if (item && start) {
519
+ const b = item.box, par = item.parent;
520
+ 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 }));
521
+ drag = {
522
+ kind: "pin",
523
+ x0: x,
524
+ y0: y,
525
+ name,
526
+ id,
527
+ ptr,
528
+ narrow,
529
+ start,
530
+ shown: start,
531
+ z0: b.z0,
532
+ size: [b.x1 - b.x0, b.y1 - b.y0],
533
+ siblings,
534
+ 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 } : void 0,
535
+ origCd: cd
536
+ };
537
+ }
538
+ }
539
+ }
540
+ function move(e) {
541
+ const { x, y } = pageXY(e);
542
+ if (linking) {
543
+ const p = toSvg(x, y), under = pathAtEvent(document.elementFromPoint(x, y));
544
+ const r = under === void 0 ? void 0 : resourceOf(under);
545
+ linking = { ...linking, x: p.x, y: p.y, over: r && r.path !== linking.from.path ? r.path : void 0 };
546
+ paintOverlay();
547
+ return;
548
+ }
549
+ if (!drag) {
550
+ const p = pathAtEvent(e.target);
551
+ if (p !== hoverId) {
552
+ hoverId = p;
553
+ paintOverlay();
554
+ }
555
+ return;
556
+ }
557
+ const k = scale();
558
+ if (drag.kind === "click" && mode === "2d" && !drag.moved && Math.hypot(x - drag.x0, y - drag.y0) > 4) {
559
+ drag.moved = true;
560
+ opts.onHint?.("Moving is in 3D: switch to 3D to drag it where it goes");
561
+ return;
562
+ }
563
+ if (drag.kind === "pan") {
564
+ if (Math.hypot(x - drag.x0, y - drag.y0) > 3) drag.emptyClick = false;
565
+ V.view = { ...drag.v0, x: drag.v0.x - (x - drag.x0) / k, y: drag.v0.y - (y - drag.y0) / k };
566
+ applyView();
567
+ } else if (drag.kind === "marquee") {
568
+ if (Math.hypot(x - drag.x0, y - drag.y0) < 3) return;
569
+ drag.moved = true;
570
+ const a = toSvg(drag.x0, drag.y0), b = toSvg(x, y);
571
+ if (flat) {
572
+ marquee2d(a, b);
573
+ return;
574
+ }
575
+ const [ax, ay] = screenToGrid(a.x, a.y), [bx, by] = screenToGrid(b.x, b.y);
576
+ const g = { x0: Math.min(ax, bx), y0: Math.min(ay, by), x1: Math.max(ax, bx), y1: Math.max(ay, by) };
577
+ const hits = /* @__PURE__ */ new Map();
578
+ for (const [ptr, foot] of footprints()) {
579
+ const f = foot;
580
+ const inside = f.x0 >= g.x0 && f.y0 >= g.y0 && f.x1 <= g.x1 && f.y1 <= g.y1;
581
+ const touches = f.x0 < g.x1 && f.x1 > g.x0 && f.y0 < g.y1 && f.y1 > g.y0;
582
+ if (drag.touch ? touches : inside) hits.set(ptr, fromPointer(ptr));
583
+ }
584
+ const base2 = new Map((drag.sel0 ?? []).map((p) => [toPointer(p), p]));
585
+ for (const [k2, p] of hits) base2.set(k2, p);
586
+ doc.select([...base2.values()], "canvas");
587
+ paintOverlay();
588
+ const poly = fdoc().createElementNS(SVGNS, "polygon");
589
+ poly.setAttribute("class", "marquee");
590
+ 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(" "));
591
+ overlay.append(poly);
592
+ lastMarquee = g;
593
+ } else if (drag.kind === "pin") {
594
+ if (!drag.moved && Math.hypot(x - drag.x0, y - drag.y0) < 4) return;
595
+ drag.moved = true;
596
+ lastPin = { x, y, alt: e.altKey };
597
+ if (!pinFrame) {
598
+ pinFrame = true;
599
+ const go = () => {
600
+ if (pinFrame) {
601
+ pinFrame = false;
602
+ pinStep();
603
+ }
604
+ };
605
+ requestAnimationFrame(go);
606
+ setTimeout(go, 32);
607
+ }
608
+ }
609
+ }
610
+ function marquee2d(a, b) {
611
+ if (!drag || !flat || !cd) return;
612
+ 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) };
613
+ const hits = /* @__PURE__ */ new Map();
614
+ for (const id of flat.hits(g, !!drag.touch)) {
615
+ const ptr = cd.pathOf.get(id);
616
+ if (ptr !== void 0 && resourceOf(ptr)?.path === ptr) hits.set(ptr, fromPointer(ptr));
617
+ }
618
+ const base2 = new Map((drag.sel0 ?? []).map((p) => [toPointer(p), p]));
619
+ for (const [k2, p] of hits) base2.set(k2, p);
620
+ doc.select([...base2.values()], "canvas");
621
+ paintOverlay();
622
+ const r = fdoc().createElementNS(SVGNS, "rect");
623
+ r.setAttribute("class", "marquee");
624
+ r.setAttribute("x", String(g.l));
625
+ r.setAttribute("y", String(g.t));
626
+ r.setAttribute("width", String(g.r - g.l));
627
+ r.setAttribute("height", String(g.b - g.t));
628
+ overlay.append(r);
629
+ }
630
+ let pinFrame = false, lastPin, relayout = 0;
631
+ const pinDrag = () => drag?.kind === "pin" && drag.moved ? drag : void 0;
632
+ function pinStep() {
633
+ const g = pinDrag();
634
+ if (!g || !lastPin || !cd) return;
635
+ const k = scale();
636
+ const step = lastPin.alt ? 0.5 : 1;
637
+ g.step = step;
638
+ const m = snapMove(g.start, screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k), step, g.size, g.parent);
639
+ const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
640
+ 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] };
641
+ const changed = !g.move || g.move.at[0] !== m.at[0] || g.move.at[1] !== m.at[1];
642
+ g.move = m;
643
+ g.invalid = overlaps(foot, g.siblings);
644
+ svg?.classList.add("dragging");
645
+ svg?.classList.toggle("drag-bad", g.invalid);
646
+ shiftDragged(g.id, [m.at[0] - g.shown[0], m.at[1] - g.shown[1]]);
647
+ paintDrag(foot);
648
+ const within = g.parent ? `within ${g.parent.label}` : "on the canvas";
649
+ opts.onHint?.(`Moving ${g.name} ${within} \xB7 ${step === 1 ? "whole cells (\u2325: half cells)" : "half cells"} \xB7 ${g.invalid ? "overlaps: it won't drop here" : "Esc cancels"}${T.pinHint}`);
650
+ if (changed && !g.invalid && lastS3) {
651
+ clearTimeout(relayout);
652
+ relayout = window.setTimeout(async () => {
653
+ const now = pinDrag();
654
+ if (!now || now.invalid || !now.move) return;
655
+ let next;
656
+ try {
657
+ ({ next, keep: now.keep } = trialLayout(now));
658
+ } catch {
659
+ return;
660
+ }
661
+ if (pinDrag() !== now) return;
662
+ await draw(next);
663
+ if (pinDrag() !== now) return;
664
+ now.shown = now.move.at;
665
+ shiftDragged(now.id, [0, 0]);
666
+ 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);
667
+ }, 0);
668
+ }
669
+ }
670
+ function trialLayout(g) {
671
+ const base2 = JSON.parse(JSON.stringify(lastData ?? {}));
672
+ if (K.pins.legacyOnly(base2)) {
673
+ base2[PINS_KEY] = base2[K.pins.legacyKey];
674
+ delete base2[K.pins.legacyKey];
675
+ }
676
+ base2[PINS_KEY] ??= {};
677
+ base2[PINS_KEY].layout ??= {};
678
+ const pins = base2[PINS_KEY].layout;
679
+ pins[g.name] = { at: g.move.at };
680
+ let next = K.draw(lastS3, base2, opts.theme);
681
+ const orig = g.origCd, nameOf = new Map([...orig.pinId].map(([n, id]) => [id, n]));
682
+ const me = orig.scene.layout.byId.get(g.id);
683
+ const sibs = me.parent ? me.parent.children : orig.scene.layout.items.filter((i) => !i.parent);
684
+ const keep = [];
685
+ for (const sb of sibs) {
686
+ if (sb === me) continue;
687
+ const n = nameOf.get(sb.id), was = localAt(orig.scene, sb.id), now = next.scene.layout.byId.get(sb.id)?.box;
688
+ if (!n || !was || !now || n in pins) continue;
689
+ if (Math.abs(now.x0 - sb.box.x0) > 1e-6 || Math.abs(now.y0 - sb.box.y0) > 1e-6) keep.push([n, was]);
690
+ }
691
+ if (keep.length) {
692
+ for (const [n, at] of keep) pins[n] = { at };
693
+ next = K.draw(lastS3, base2, opts.theme);
694
+ }
695
+ return { next, keep };
696
+ }
697
+ function shiftDragged(id, [gx, gy]) {
698
+ if (!svg || !cd) return;
699
+ const [sx, sy] = [(gx - gy) * C * S, (gx + gy) * 0.5 * S];
700
+ const ids = /* @__PURE__ */ new Set([id]);
701
+ for (const it of cd.scene.layout.items) {
702
+ let p = it.parent;
703
+ while (p) {
704
+ if (p.id === id) {
705
+ ids.add(it.id);
706
+ break;
707
+ }
708
+ p = p.parent;
709
+ }
710
+ }
711
+ for (const el of svg.querySelectorAll("[data-id]")) {
712
+ if (!ids.has(el.getAttribute("data-id") ?? "")) continue;
713
+ if (el.parentElement?.closest(`[data-id="${CSS.escape(el.getAttribute("data-id"))}"]`)) continue;
714
+ el.setAttribute("transform", gx || gy ? `translate(${sx.toFixed(1)} ${sy.toFixed(1)})` : "");
715
+ }
716
+ }
717
+ function paintDrag(foot) {
718
+ const g = pinDrag();
719
+ if (!g || !overlay) return;
720
+ paintOverlay();
721
+ const d = fdoc();
722
+ const wrap = d.createElementNS(SVGNS, "g");
723
+ wrap.setAttribute("class", g.gridShown ? "gridwrap" : "gridwrap fresh");
724
+ g.gridShown = true;
725
+ const z = g.z0;
726
+ const P = (x, y) => iso(x, y, z).map((v) => v.toFixed(1)).join(",");
727
+ 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 };
728
+ const line = (x1, y1, x2, y2, cls) => {
729
+ const l = d.createElementNS(SVGNS, "polyline");
730
+ l.setAttribute("class", cls);
731
+ l.setAttribute("points", `${P(x1, y1)} ${P(x2, y2)}`);
732
+ wrap.append(l);
733
+ };
734
+ const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
735
+ const st = g.step ?? 1;
736
+ 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");
737
+ 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");
738
+ overlay.append(wrap);
739
+ const t = d.createElementNS(SVGNS, "polygon");
740
+ t.setAttribute("class", `drop${g.invalid ? " bad" : ""}`);
741
+ 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(" "));
742
+ overlay.append(t);
743
+ if (g.parent && g.move) {
744
+ const pb = g.parent.box, c = g.move.clamped, pad = g.parent.pad;
745
+ const e = (x1, y1, x2, y2) => {
746
+ const l = d.createElementNS(SVGNS, "polyline");
747
+ l.setAttribute("class", "edge");
748
+ l.setAttribute("points", `${P(x1, y1)} ${P(x2, y2)}`);
749
+ overlay.append(l);
750
+ };
751
+ if (c.left) e(pb.x0 + pad, pb.y0, pb.x0 + pad, pb.y1);
752
+ if (c.right) e(pb.x1 - pad, pb.y0, pb.x1 - pad, pb.y1);
753
+ if (c.top) e(pb.x0, pb.y0 + pad, pb.x1, pb.y0 + pad);
754
+ if (c.bottom) e(pb.x0, pb.y1 - pad, pb.x1, pb.y1 - pad);
755
+ }
756
+ }
757
+ async function endPin(commit) {
758
+ const g = pinDrag();
759
+ if (!g) return;
760
+ drag = void 0;
761
+ clearTimeout(relayout);
762
+ const shown = overlay ? [...overlay.querySelectorAll(".gridwrap, .drop, .edge")] : [];
763
+ if (shown.length) {
764
+ for (const e of shown) e.classList.add("out");
765
+ if (!matchMedia("(prefers-reduced-motion: reduce)").matches) await new Promise((r) => setTimeout(r, 160));
766
+ }
767
+ lastKey = "";
768
+ svg?.classList.remove("dragging", "drag-bad");
769
+ paintNav();
770
+ const m = g.move;
771
+ const moved = m && (m.at[0] !== g.start[0] || m.at[1] !== g.start[1]);
772
+ if (commit && m && moved && !g.invalid) {
773
+ const label = `Pin ${describe(fromPointer(g.ptr))} at [${m.at.join(", ")}]`;
774
+ let keep = g.keep ?? [];
775
+ if (!g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try {
776
+ keep = trialLayout(g).keep;
777
+ } catch {
778
+ }
779
+ 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);
780
+ if (pendingAfterDrag && lastS3) {
781
+ pendingAfterDrag = false;
782
+ lastKey = "";
783
+ render(lastS3, lastData);
784
+ }
785
+ return;
786
+ }
787
+ if (commit && g.invalid) opts.note(`${g.name} can't go there: it would overlap`, "warn");
788
+ await draw(g.origCd);
789
+ if (pendingAfterDrag && lastS3) {
790
+ pendingAfterDrag = false;
791
+ lastKey = "";
792
+ render(lastS3, lastData);
793
+ }
794
+ }
795
+ function up(e) {
796
+ if (linking && !linking.pick) {
797
+ const { x: x2, y: y2 } = pageXY(e);
798
+ endConnect(pathAtEvent(document.elementFromPoint(x2, y2)));
799
+ return;
800
+ }
801
+ const d0 = drag;
802
+ drag = void 0;
803
+ svg?.classList.remove("panning");
804
+ if (!d0) return;
805
+ const { x, y } = pageXY(e);
806
+ if (d0.kind === "marquee" && !d0.moved && !d0.add || d0.kind === "pan" && d0.emptyClick) doc.select([], "canvas");
807
+ const narrow = d0.kind === "click" ? d0.ptr : d0.kind === "pin" && !d0.moved ? d0.narrow : void 0;
808
+ if (narrow) doc.select([fromPointer(narrow)], "canvas");
809
+ if (d0.kind === "pin" && d0.moved) {
810
+ drag = d0;
811
+ lastPin = { x, y, alt: e.altKey };
812
+ pinFrame = false;
813
+ pinStep();
814
+ endPin(true);
815
+ return;
816
+ }
817
+ paintOverlay();
818
+ }
819
+ let lastMarquee;
820
+ function footprints() {
821
+ const out = /* @__PURE__ */ new Map();
822
+ if (!cd) return out;
823
+ for (const [id, ptr] of cd.pathOf) {
824
+ const r = resourceOf(ptr);
825
+ if (!r || r.path !== ptr) continue;
826
+ const item = cd.scene.layout.byId.get(id);
827
+ if (!item || svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) continue;
828
+ const b = item.box, z = b.z0;
829
+ const f = { x0: b.x0 - z, y0: b.y0 - z, x1: b.x1 - z, y1: b.y1 - z };
830
+ const prev = out.get(ptr);
831
+ 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);
832
+ }
833
+ return out;
834
+ }
835
+ const round = (v) => Math.round(v * 2) / 2;
836
+ const snap = ([x, y]) => [round(x), round(y)];
837
+ const gridToScreen = (gx, gy) => {
838
+ const [ux, uy] = screenToGrid(1, 0), [vx, vy] = screenToGrid(0, 1);
839
+ const det = ux * vy - uy * vx;
840
+ return [(gx * vy - gy * vx) / det, (gy * ux - gx * uy) / det];
841
+ };
842
+ function wheel(e) {
843
+ e.preventDefault();
844
+ const { x, y } = pageXY(e);
845
+ const k = scale();
846
+ if (e.ctrlKey || e.metaKey) {
847
+ zoomAt(Math.exp(-e.deltaY * 0.01), x, y);
848
+ return;
849
+ }
850
+ if (e.shiftKey) {
851
+ V.view = { ...V.view, x: V.view.x + (e.deltaX || e.deltaY) / k };
852
+ applyView();
853
+ return;
854
+ }
855
+ if (nav.wheel === "zoom") zoomAt(Math.exp(-e.deltaY * 25e-4), x, y);
856
+ else {
857
+ V.view = { ...V.view, x: V.view.x + e.deltaX / k, y: V.view.y + e.deltaY / k };
858
+ applyView();
859
+ }
860
+ }
861
+ function context(e) {
862
+ e.preventDefault();
863
+ const { x, y } = pageXY(e);
864
+ if (layer?.context?.(e, { x, y })) return;
865
+ const ptr = pathAtEvent(e.target);
866
+ if (ptr !== void 0 && !doc.selection.some((p) => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], "canvas");
867
+ openMenu(menuItems(ptr), { x, y }, "Canvas");
868
+ }
869
+ function menuItems(ptr) {
870
+ const sel = doc.selection;
871
+ const items = [];
872
+ const ro = !doc.doc.ok;
873
+ if (ptr === void 0 || !sel.length) {
874
+ for (const s of ui.newOrder) items.push({ label: `New ${kindOf(s).singular}`, icon: "plus", disabled: ro, onSelect: () => addResource(s) });
875
+ if (opts.clipItems) items.push({ sep: true }, ...opts.clipItems().filter((i) => "label" in i && i.label === "Paste"));
876
+ items.push({ sep: true }, { label: "Fit", keys: "0", onSelect: () => fitItems() }, { label: "Fit the whole drawing", onSelect: () => fit() }, { label: "Zoom 100%", keys: "1", onSelect: () => actual() });
877
+ const hasPins = !!K.pins.of(doc.goodDoc.data);
878
+ items.push({ label: "Reset layout", icon: "rotate-ccw", desc: "Remove every pin (x-editor.layout)", disabled: ro || !hasPins, why: "Nothing is pinned", onSelect: resetLayout });
879
+ return items;
880
+ }
881
+ const one = sel.length === 1 ? sel[0] : void 0;
882
+ const isRes = one && resourceOf(toPointer(one))?.path === toPointer(one);
883
+ if (one) {
884
+ items.push(...K.objectItems(doc, one, "canvas", opts.note));
885
+ if (items.length) items.push({ sep: true });
886
+ items.push({ label: "Rename\u2026", icon: "pencil", keys: "F2", disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, "canvas", opts.note) });
887
+ items.push({ label: "Duplicate", icon: "copy", keys: "\u2318D", disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, "canvas", opts.note) });
888
+ const name = isRes ? resourceOf(toPointer(one)).name : "";
889
+ const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
890
+ 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) });
891
+ items.push({ sep: true });
892
+ items.push({ label: "Show in text", icon: "code-xml", onSelect: () => opts.showInText(one) });
893
+ items.push({ label: "Show in tree", icon: "list-tree", onSelect: () => opts.showInTree(one) });
894
+ }
895
+ if (K.connect && one && isRes) items.push({ label: "Connect to\u2026", icon: "link", desc: "Then click what it connects to (Esc cancels)", disabled: ro, onSelect: () => startPick() });
896
+ if (K.group) items.push({ label: sel.length > 1 ? `Group ${sel.length} items` : "Group", icon: "box", keys: "\u2318G", desc: "Into a new container, as one step", disabled: ro || !members().length, why: "Only objects are grouped", onSelect: groupSelection });
897
+ items.push({ label: "Select parent", icon: "arrow-up-right", keys: "\u2318\u2191", onSelect: selectParent });
898
+ items.push({ label: "Select connected", icon: "link", desc: "What refers to it, and what it refers to", onSelect: () => doc.select(connected(doc, sel), "canvas") });
899
+ items.push({ label: "Zoom to selection", keys: "\u21E72", onSelect: zoomToSelection });
900
+ if (opts.clipItems) items.push({ sep: true }, ...opts.clipItems());
901
+ items.push({ sep: true }, { label: sel.length > 1 ? `Delete ${sel.length} items` : "Delete", icon: "trash-2", keys: "\u232B", danger: true, disabled: ro, onSelect: () => deletePaths(doc, sel, "canvas", opts.note) });
902
+ return items;
903
+ }
904
+ function connectable() {
905
+ if (!K.connect || !doc.doc.ok || doc.selection.length !== 1) return void 0;
906
+ const ptr = toPointer(doc.selection[0]), r = resourceOf(ptr);
907
+ return r && r.path === ptr ? r : void 0;
908
+ }
909
+ function startPick() {
910
+ const from = connectable();
911
+ if (!from) return;
912
+ linking = { from, pick: true };
913
+ opts.note(`Click what ${from.name} connects to (Esc cancels)`);
914
+ paintOverlay();
915
+ }
916
+ function endConnect(ptr) {
917
+ const from = linking?.from;
918
+ linking = void 0;
919
+ paintOverlay();
920
+ if (!from || ptr === void 0) return;
921
+ const to = resourceOf(ptr);
922
+ if (!to || to.path === from.path) {
923
+ opts.note("Not connected: drop it on another object", "warn");
924
+ return;
925
+ }
926
+ const data = doc.goodDoc.data;
927
+ const plan = K.connect?.(from, to, data);
928
+ if (!plan) {
929
+ opts.note(`${from.name} and ${to.name} can't be connected`, "warn");
930
+ return;
931
+ }
932
+ const label = plan.label ?? `Connect ${from.name} to ${to.name}`;
933
+ let cmd, path;
934
+ if (plan.name !== void 0) {
935
+ const name = freshName(doc.text, plan.name);
936
+ cmd = insertCmd(plan.at, name, plan.value, { label });
937
+ path = [...plan.at, name];
938
+ } else {
939
+ const list = plan.at.reduce((x, k) => x && typeof x === "object" ? x[k] : void 0, data);
940
+ path = [...plan.at, Array.isArray(list) ? list.length : 0];
941
+ cmd = insertItemCmd(plan.at, plan.value, void 0, label);
942
+ }
943
+ if (run(doc, { ...cmd, select: [path] }, "canvas", opts.note)) doc.select([path], "canvas");
944
+ }
945
+ function members() {
946
+ const out = /* @__PURE__ */ new Map();
947
+ for (const p of doc.selection) {
948
+ const r = resourceOf(toPointer(p));
949
+ if (r) out.set(r.path, r);
950
+ }
951
+ return [...out.values()];
952
+ }
953
+ function groupSelection() {
954
+ if (!K.group || !doc.doc.ok) return;
955
+ const ms = members();
956
+ if (!ms.length) {
957
+ opts.note("Only objects are grouped", "warn");
958
+ return;
959
+ }
960
+ const plan = K.group(ms, doc.goodDoc.data);
961
+ if (!plan) {
962
+ opts.note(ms.length > 1 ? `These ${ms.length} can't be grouped` : `${ms[0].name} can't be grouped`, "warn");
963
+ return;
964
+ }
965
+ const name = freshName(doc.text, plan.name);
966
+ const pins = K.pins.of(doc.goodDoc.data) ?? {};
967
+ const unpin = ms.filter((m) => pins[m.name] !== void 0).map((m) => withPinsMoved(deleteCmd([PINS_KEY, "layout", m.name])));
968
+ const label = plan.label ?? `Group ${ms.length > 1 ? `${ms.length} items` : ms[0].name} into ${name}`;
969
+ const p = [...plan.at, name];
970
+ const cmd = seqCmd(label, [insertCmd(plan.at, name, plan.value, { label }), ...plan.members(name).map((m) => setCmd(m.path, m.value)), ...unpin]);
971
+ if (run(doc, { ...cmd, select: [p] }, "canvas", opts.note)) doc.select([p], "canvas");
972
+ }
973
+ function addResource(s) {
974
+ const k = kindOf(s);
975
+ const name = freshName(doc.text, k.singular);
976
+ const p = [...k.section, name];
977
+ if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), "canvas", opts.note)) {
978
+ doc.select([p], "canvas");
979
+ renameDialog(doc, p, "canvas", opts.note);
980
+ }
981
+ }
982
+ function placeAt(name, add, at) {
983
+ if (!cd || !svg) return void 0;
984
+ const text = add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
985
+ let trial;
986
+ try {
987
+ trial = K.trial(text, opts.theme);
988
+ } catch {
989
+ return void 0;
990
+ }
991
+ if (!trial) return void 0;
992
+ const id = trial.pinId.get(name), item = id ? trial.scene.layout.byId.get(id) : void 0, start = id ? localAt(trial.scene, id) : void 0;
993
+ if (!item || !start) return void 0;
994
+ const b = item.box, par = item.parent;
995
+ const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
996
+ const centre = [(cx - cy) * C * S, (cx + cy) * 0.5 * S - b.z0 * S], drop = toSvg(at.x, at.y);
997
+ const m = snapMove(
998
+ start,
999
+ screenToGrid(drop.x - centre[0], drop.y - centre[1]),
1000
+ 1,
1001
+ [b.x1 - b.x0, b.y1 - b.y0],
1002
+ par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region) } : void 0
1003
+ );
1004
+ const dx = m.at[0] - start[0], dy = m.at[1] - start[1];
1005
+ const moved = { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy };
1006
+ const siblings = (par ? par.children : trial.scene.layout.items.filter((i) => !i.parent)).filter((i) => i !== item).map((i) => i.box);
1007
+ return overlaps(moved, siblings) ? void 0 : m.at;
1008
+ }
1009
+ function containerAt(kind, at) {
1010
+ if (!cd) return void 0;
1011
+ const p = toSvg(at.x, at.y);
1012
+ if (flat) {
1013
+ for (const id of flat.panelsAt(p.x, p.y)) {
1014
+ const name = [...cd.pinId].find(([, pid]) => pid === id)?.[0];
1015
+ if (name && resourceOf(cd.pathOf.get(id) ?? "")?.kind === kind) return name;
1016
+ }
1017
+ return void 0;
1018
+ }
1019
+ const inside = (poly) => {
1020
+ let c = false;
1021
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
1022
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
1023
+ if (yi > p.y !== yj > p.y && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c;
1024
+ }
1025
+ return c;
1026
+ };
1027
+ for (const [name, id] of cd.pinId) {
1028
+ if (resourceOf(cd.pathOf.get(id) ?? "")?.kind !== kind) continue;
1029
+ const item = cd.scene.layout.byId.get(id);
1030
+ if (item && inside(floorOf(item.box))) return name;
1031
+ }
1032
+ return void 0;
1033
+ }
1034
+ function objectsUnder(at) {
1035
+ if (!cd) return [];
1036
+ const p = toSvg(at.x, at.y);
1037
+ const refOf = (id) => {
1038
+ const ptr = cd.pathOf.get(id);
1039
+ const r = ptr === void 0 ? void 0 : resourceOf(ptr);
1040
+ return r && r.path === ptr ? r : void 0;
1041
+ };
1042
+ if (flat) return flat.panelsAt(p.x, p.y).map(refOf).filter((r) => !!r);
1043
+ const inside = (poly) => {
1044
+ let c = false;
1045
+ for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
1046
+ const [xi, yi] = poly[i], [xj, yj] = poly[j];
1047
+ if (yi > p.y !== yj > p.y && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c;
1048
+ }
1049
+ return c;
1050
+ };
1051
+ const depth = (i) => {
1052
+ let n = 0;
1053
+ for (let q = i.parent; q; q = q.parent) n++;
1054
+ return n;
1055
+ };
1056
+ const seen = /* @__PURE__ */ new Map();
1057
+ for (const e of fdoc().elementsFromPoint(at.x, at.y)) {
1058
+ if (!svg?.contains(e)) continue;
1059
+ for (let el = e.closest("[data-id]"); el; el = el.parentElement?.closest("[data-id]") ?? null) {
1060
+ const r = refOf(el.getAttribute("data-id") ?? "");
1061
+ if (r && !seen.has(r.path)) seen.set(r.path, r);
1062
+ }
1063
+ }
1064
+ const hits = [];
1065
+ for (const [, id] of cd.pinId) {
1066
+ const item = cd.scene.layout.byId.get(id), r = refOf(id);
1067
+ if (item && r && !seen.has(r.path) && inside(floorOf(item.box))) hits.push({ r, d: depth(item), a: (item.box.x1 - item.box.x0) * (item.box.y1 - item.box.y0) });
1068
+ }
1069
+ return [...seen.values(), ...hits.sort((x, y) => y.d - x.d || x.a - y.a).map((h2) => h2.r)];
1070
+ }
1071
+ function addFromPalette(sec, at, item) {
1072
+ if (!doc.doc.ok) {
1073
+ opts.note("Fix the YAML first", "warn");
1074
+ return void 0;
1075
+ }
1076
+ const k = kindOf(sec);
1077
+ const preset = item?.value?.();
1078
+ const what = item && preset !== void 0 ? item.label.toLowerCase() : k.singular;
1079
+ const name = freshName(doc.text, item?.name ?? k.singular);
1080
+ const p = [...k.section, name];
1081
+ let value = preset ?? k.template();
1082
+ let into;
1083
+ const drop = at ? K.dropInto?.(sec) : void 0;
1084
+ if (at && drop) {
1085
+ const c = containerAt(drop.container, at);
1086
+ if (c) {
1087
+ into = c;
1088
+ value = { ...drop.value(c), ...preset ?? {} };
1089
+ }
1090
+ }
1091
+ let intoLabel = into ? drop.label(into) : "";
1092
+ if (at && !into && K.dropOnto) {
1093
+ for (const t of objectsUnder(at)) {
1094
+ const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
1095
+ if (plan) {
1096
+ into = t.name;
1097
+ value = plan.value;
1098
+ intoLabel = plan.label ? ` ${plan.label}` : ` in ${t.name}`;
1099
+ break;
1100
+ }
1101
+ }
1102
+ }
1103
+ const label = `Add ${what} ${name}${intoLabel}`;
1104
+ const add = insertCmd(p.slice(0, -1), name, value, { label });
1105
+ const pin = at && !into && mode === "3d" ? placeAt(name, add, at) : void 0;
1106
+ const cmd = pin ? seqCmd(`${label} at [${pin.join(", ")}]`, [add, withPinsMoved(setCmd([PINS_KEY, "layout", name], { at: pin }))]) : add;
1107
+ if (!run(doc, { ...cmd, select: [p] }, "canvas", opts.note)) return void 0;
1108
+ 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`);
1109
+ doc.select([p], "canvas");
1110
+ stage.focus({ preventScroll: true });
1111
+ renameDialog(doc, p, "canvas", opts.note);
1112
+ return p;
1113
+ }
1114
+ const palette = h("div", { class: "palette", role: "toolbar", "aria-label": T.palette, "aria-orientation": "vertical" });
1115
+ ui.palette.forEach((item, idx) => {
1116
+ const { kind: sec, icon: ic, label } = item;
1117
+ const b = h("button", { type: "button", class: "pal-item", "data-section": sec, "data-entry": String(idx), title: `Add ${label.toLowerCase()} (click), or drag it where it goes` }, icon(ic), h("span", { class: "pal-label" }, label));
1118
+ b.addEventListener("pointerdown", (e) => {
1119
+ if (e.button !== 0) return;
1120
+ e.preventDefault();
1121
+ try {
1122
+ b.setPointerCapture(e.pointerId);
1123
+ } catch {
1124
+ }
1125
+ const x0 = e.clientX, y0 = e.clientY;
1126
+ let ghost;
1127
+ const over = (ev) => {
1128
+ const r = stage.getBoundingClientRect();
1129
+ 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));
1130
+ };
1131
+ const mv = (ev) => {
1132
+ if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
1133
+ if (!ghost) {
1134
+ ghost = h("div", { class: "pal-ghost", "aria-hidden": "true" }, icon(ic), label);
1135
+ host.append(ghost);
1136
+ }
1137
+ const hr = host.getBoundingClientRect();
1138
+ ghost.style.left = `${ev.clientX - hr.left + 8}px`;
1139
+ ghost.style.top = `${ev.clientY - hr.top + 8}px`;
1140
+ ghost.classList.toggle("bad", !over(ev));
1141
+ };
1142
+ const done = (ev, drop) => {
1143
+ b.removeEventListener("pointermove", mv);
1144
+ b.removeEventListener("pointerup", upH);
1145
+ b.removeEventListener("pointercancel", cancelH);
1146
+ removeEventListener("keydown", esc, true);
1147
+ const dragged = !!ghost;
1148
+ ghost?.remove();
1149
+ if (!drop) return;
1150
+ if (!dragged) addFromPalette(sec, void 0, item);
1151
+ else if (over(ev)) addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item);
1152
+ };
1153
+ const upH = (ev) => done(ev, true), cancelH = (ev) => done(ev, false);
1154
+ const esc = (ev) => {
1155
+ if (ev.key === "Escape") {
1156
+ ev.stopPropagation();
1157
+ ev.preventDefault();
1158
+ done(e, false);
1159
+ }
1160
+ };
1161
+ b.addEventListener("pointermove", mv);
1162
+ b.addEventListener("pointerup", upH);
1163
+ b.addEventListener("pointercancel", cancelH);
1164
+ addEventListener("keydown", esc, true);
1165
+ });
1166
+ b.addEventListener("keydown", (e) => {
1167
+ if (e.key === "Enter" || e.key === " ") {
1168
+ e.preventDefault();
1169
+ addFromPalette(sec, void 0, item);
1170
+ }
1171
+ });
1172
+ palette.append(b);
1173
+ });
1174
+ host.append(palette);
1175
+ function resetLayout() {
1176
+ const key2 = K.pins.keyOf(doc.goodDoc.data);
1177
+ const x = doc.goodDoc.data?.[key2];
1178
+ const only = x && Object.keys(x).length === 1;
1179
+ run(doc, { ...deleteCmd(only ? [key2] : [key2, "layout"]), label: "Reset the layout" }, "canvas", opts.note);
1180
+ }
1181
+ function selectParent() {
1182
+ const up2 = /* @__PURE__ */ new Map();
1183
+ for (const p of doc.selection) {
1184
+ const r = resourceOf(toPointer(p));
1185
+ const q = r && r.path !== toPointer(p) ? fromPointer(r.path) : r ? kindOf(r.kind).section : [];
1186
+ up2.set(toPointer(q), q);
1187
+ }
1188
+ doc.select([...up2.values()], "canvas");
1189
+ }
1190
+ function key(e) {
1191
+ if (e.type === "keyup" && e.key !== " ") return;
1192
+ if (e.key === " ") {
1193
+ spaceKeyDown = e.type === "keydown";
1194
+ svg?.classList.toggle(ui.panKeyClass, spaceKeyDown);
1195
+ e.preventDefault();
1196
+ return;
1197
+ }
1198
+ const lk = layer?.key?.(e);
1199
+ if (lk === "ignore") return;
1200
+ if (lk === "handled") {
1201
+ e.preventDefault();
1202
+ e.stopPropagation();
1203
+ return;
1204
+ }
1205
+ const mod = e.metaKey || e.ctrlKey;
1206
+ const sel = doc.selection;
1207
+ const drawn = [...new Set([...cd?.pathOf.values() ?? []].filter((p) => resourceOf(p)?.path === p))];
1208
+ const ro = !doc.doc.ok;
1209
+ switch (e.key) {
1210
+ case "+":
1211
+ case "=":
1212
+ zoomAt(1.25);
1213
+ break;
1214
+ case "-":
1215
+ case "_":
1216
+ zoomAt(0.8);
1217
+ break;
1218
+ case "0":
1219
+ fitItems();
1220
+ break;
1221
+ case "1":
1222
+ actual();
1223
+ break;
1224
+ case "@":
1225
+ case "2":
1226
+ if (e.shiftKey || e.key === "@") zoomToSelection();
1227
+ else return;
1228
+ break;
1229
+ case "Escape":
1230
+ if (linking) {
1231
+ linking = void 0;
1232
+ paintOverlay();
1233
+ opts.note("Not connected");
1234
+ break;
1235
+ }
1236
+ if (pinDrag()) {
1237
+ endPin(false);
1238
+ break;
1239
+ }
1240
+ doc.select([], "canvas");
1241
+ break;
1242
+ case "Delete":
1243
+ case "Backspace":
1244
+ if (sel.length && !ro) deletePaths(doc, sel, "canvas", opts.note);
1245
+ break;
1246
+ case "F2":
1247
+ if (sel.length === 1 && !ro) renameDialog(doc, sel[0], "canvas", opts.note);
1248
+ break;
1249
+ case "ArrowUp":
1250
+ if (mod) {
1251
+ selectParent();
1252
+ break;
1253
+ }
1254
+ return;
1255
+ case "Tab":
1256
+ case "ArrowRight":
1257
+ case "ArrowLeft":
1258
+ case "ArrowDown": {
1259
+ if (!drawn.length) return;
1260
+ const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
1261
+ const back = e.key === "ArrowLeft" || e.key === "Tab" && e.shiftKey;
1262
+ const j = i < 0 ? 0 : (i + (back ? -1 : 1) + drawn.length) % drawn.length;
1263
+ doc.select([fromPointer(drawn[j])], "canvas");
1264
+ zoomIfOutside(fromPointer(drawn[j]));
1265
+ break;
1266
+ }
1267
+ case "ContextMenu":
1268
+ case "F10":
1269
+ if (e.key === "F10" && !e.shiftKey) return;
1270
+ {
1271
+ const b = unionBox(sel);
1272
+ const r = host.getBoundingClientRect();
1273
+ const k = scale();
1274
+ openMenu(menuItems(sel.length ? toPointer(sel[0]) : void 0), 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");
1275
+ }
1276
+ break;
1277
+ default:
1278
+ if (mod && e.key.toLowerCase() === "d" && sel.length === 1 && !ro) {
1279
+ duplicate(doc, sel[0], "canvas", opts.note);
1280
+ break;
1281
+ }
1282
+ if (mod && e.key.toLowerCase() === "a") {
1283
+ doc.select(drawn.map(fromPointer), "canvas");
1284
+ break;
1285
+ }
1286
+ if (mod && e.key.toLowerCase() === "g" && K.group && sel.length && !ro) {
1287
+ groupSelection();
1288
+ break;
1289
+ }
1290
+ return;
1291
+ }
1292
+ e.preventDefault();
1293
+ e.stopPropagation();
1294
+ }
1295
+ stage.addEventListener("keydown", key);
1296
+ stage.addEventListener("keyup", key);
1297
+ const focusMark = (on) => host.classList.toggle("has-focus", on);
1298
+ stage.addEventListener("focus", () => focusMark(true));
1299
+ stage.addEventListener("blur", () => focusMark(false));
1300
+ paintNav();
1301
+ function zoomIfOutside(p) {
1302
+ const b = boxFor(p);
1303
+ if (!b || !V.view) return;
1304
+ 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) {
1305
+ V.view = { ...V.view, x: b.x + b.w / 2 - V.view.w / 2, y: b.y + b.h / 2 - V.view.h / 2 };
1306
+ applyView();
1307
+ }
1308
+ }
1309
+ function reveal(paths) {
1310
+ if (!V.view || !paths.length) return true;
1311
+ const bs = paths.map(boxFor);
1312
+ if (bs.some((b2) => !b2)) return false;
1313
+ const b = union(bs);
1314
+ const m = 24 / scale();
1315
+ 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;
1316
+ if (b.w + 2 * m > V.view.w || b.h + 2 * m > V.view.h) {
1317
+ fit({ x: b.x - m, y: b.y - m, w: b.w + 2 * m, h: b.h + 2 * m });
1318
+ return true;
1319
+ }
1320
+ V.view = { ...V.view, x: b.x + b.w / 2 - V.view.w / 2, y: b.y + b.h / 2 - V.view.h / 2 };
1321
+ applyView();
1322
+ return true;
1323
+ }
1324
+ let pendingReveal;
1325
+ ifEvents();
1326
+ doc.onSelect((c) => {
1327
+ paintOverlay();
1328
+ if (c.origin === "canvas" || !c.paths.length) return;
1329
+ pendingReveal = reveal(c.paths) ? void 0 : c.paths;
1330
+ });
1331
+ const base = {
1332
+ addFromPalette,
1333
+ palette,
1334
+ groupSelection,
1335
+ startPick,
1336
+ objectsUnder,
1337
+ get linking() {
1338
+ return linking;
1339
+ },
1340
+ render,
1341
+ setTheme,
1342
+ paintOverlay,
1343
+ fit: fitItems,
1344
+ fitAll: fit,
1345
+ actual,
1346
+ zoomAt,
1347
+ itemsBox,
1348
+ get moved() {
1349
+ return V.moved;
1350
+ },
1351
+ settled,
1352
+ get zoom() {
1353
+ return V.zoom;
1354
+ },
1355
+ dispose() {
1356
+ endMorph();
1357
+ clearTimeout(relayout);
1358
+ V.dispose();
1359
+ disposed = true;
1360
+ },
1361
+ focus: () => stage.focus(),
1362
+ /** for the tests */
1363
+ get view() {
1364
+ return V.view;
1365
+ },
1366
+ get doc() {
1367
+ return cd;
1368
+ },
1369
+ /** the view (3D or 2D), and the 2D layout while it shows */
1370
+ get mode() {
1371
+ return mode;
1372
+ },
1373
+ setMode,
1374
+ get flat() {
1375
+ return flat?.layout;
1376
+ },
1377
+ stage,
1378
+ key,
1379
+ scale: () => scale(),
1380
+ nav,
1381
+ paintNav,
1382
+ outlinesFor,
1383
+ footprints,
1384
+ get drag() {
1385
+ return pinDrag();
1386
+ },
1387
+ get lastMarquee() {
1388
+ return lastMarquee;
1389
+ },
1390
+ boxFor,
1391
+ pageXYOf: (p) => {
1392
+ const b = boxFor(p);
1393
+ const r = host.getBoundingClientRect();
1394
+ const k = scale();
1395
+ 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 } : void 0;
1396
+ }
1397
+ };
1398
+ if (layer) Object.defineProperties(base, Object.getOwnPropertyDescriptors(layer.api));
1399
+ return base;
1400
+ }
1401
+ export {
1402
+ canvasView
1403
+ };