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