@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,37 @@
1
+ // node:crypto for the browser build (the build maps it here): createHash('sha256') only, as the readers that hash
2
+ // each source file they load use it. A plain SHA-256 (FIPS 180-4) over UTF-8.
3
+ const K = new Uint32Array([0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
4
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d,
5
+ 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
6
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
7
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]);
8
+ export function sha256Hex(text: string): string {
9
+ const msg = new TextEncoder().encode(text);
10
+ const len = msg.length, blocks = Math.ceil((len + 9) / 64);
11
+ const buf = new Uint8Array(blocks * 64);
12
+ buf.set(msg); buf[len] = 0x80;
13
+ const dv = new DataView(buf.buffer);
14
+ dv.setUint32(buf.length - 4, (len * 8) >>> 0); dv.setUint32(buf.length - 8, Math.floor(len / 0x20000000));
15
+ const H = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
16
+ const W = new Uint32Array(64);
17
+ const r = (x: number, n: number) => (x >>> n) | (x << (32 - n));
18
+ for (let b = 0; b < blocks; b++) {
19
+ for (let i = 0; i < 16; i++) W[i] = dv.getUint32(b * 64 + i * 4);
20
+ for (let i = 16; i < 64; i++) { const s0 = r(W[i - 15], 7) ^ r(W[i - 15], 18) ^ (W[i - 15] >>> 3), s1 = r(W[i - 2], 17) ^ r(W[i - 2], 19) ^ (W[i - 2] >>> 10); W[i] = (W[i - 16] + s0 + W[i - 7] + s1) >>> 0; }
21
+ let [a, bb, c, d, e, f, g, h] = H;
22
+ for (let i = 0; i < 64; i++) {
23
+ const t1 = (h + (r(e, 6) ^ r(e, 11) ^ r(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + W[i]) >>> 0;
24
+ const t2 = ((r(a, 2) ^ r(a, 13) ^ r(a, 22)) + ((a & bb) ^ (a & c) ^ (bb & c))) >>> 0;
25
+ h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = bb; bb = a; a = (t1 + t2) >>> 0;
26
+ }
27
+ H[0] += a; H[1] += bb; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h;
28
+ }
29
+ return [...H].map(x => x.toString(16).padStart(8, '0')).join('');
30
+ }
31
+ export function createHash(alg: string) {
32
+ if (alg !== 'sha256') throw new Error(`only sha256 here, not ${alg}`);
33
+ let t = '';
34
+ const h = { update(s: string) { t += s; return h; }, digest(_enc: 'hex') { return sha256Hex(t); } };
35
+ return h;
36
+ }
37
+ export default { createHash };
@@ -0,0 +1,24 @@
1
+ // node:path for the browser build (the build maps it here): the posix functions the readers use to resolve the files a
2
+ // file extends, on paths inside the folder the person chose (the browser-only mode resolves them with these).
3
+ export const sep = '/';
4
+ export function isAbsolute(p: string) { return p.startsWith('/'); }
5
+ export function normalize(p: string) {
6
+ const abs = p.startsWith('/');
7
+ const out: string[] = [];
8
+ for (const s of p.split('/')) { if (!s || s === '.') continue; if (s === '..') { if (out.length && out[out.length - 1] !== '..') out.pop(); else if (!abs) out.push('..'); } else out.push(s); }
9
+ return (abs ? '/' : '') + out.join('/') || (abs ? '/' : '.');
10
+ }
11
+ export function resolve(...parts: string[]) {
12
+ let p = '';
13
+ for (const x of parts) p = x.startsWith('/') ? x : p ? `${p}/${x}` : x;
14
+ return normalize(p.startsWith('/') ? p : '/' + p);
15
+ }
16
+ export function dirname(p: string) { const i = p.replace(/\/+$/, '').lastIndexOf('/'); return i <= 0 ? (p.startsWith('/') ? '/' : '.') : p.slice(0, i); }
17
+ export function basename(p: string) { return p.replace(/\/+$/, '').split('/').pop() ?? ''; }
18
+ export function join(...parts: string[]) { return normalize(parts.join('/')); }
19
+ export function relative(from: string, to: string) {
20
+ const a = normalize(from).split('/').filter(Boolean), b = normalize(to).split('/').filter(Boolean);
21
+ let i = 0; while (i < a.length && a[i] === b[i]) i++;
22
+ return [...a.slice(i).map(() => '..'), ...b.slice(i)].join('/');
23
+ }
24
+ export default { sep, isAbsolute, normalize, resolve, dirname, basename, join, relative };
@@ -0,0 +1,103 @@
1
+ // The canvas's drawing, built with DOM calls: never innerHTML, srcdoc or a parser of the browser's. The renderer writes
2
+ // SVG as text (the same text a standalone page embeds), escaping every value through one function (tag() in
3
+ // src/iso-core/kernel.ts). Here that text is read by a small parser that knows only the renderer's own output, and each
4
+ // element is made with createElementNS, each attribute set with setAttribute, each text as a text node.
5
+ //
6
+ // Even if a name, prompt or label in a source file got past the escaping, nothing it says can run: only the SVG
7
+ // elements and attributes on these lists are made (no script, foreignObject, style, image, a or iframe; no on…
8
+ // attributes; references only to #ids in the drawing), and anything else is dropped with its contents. The diagram's
9
+ // custom properties are renamed --iso-* on the way (see canvas-css.ts).
10
+ // parseSvg is pure (tested in Node); buildSvg makes the DOM.
11
+
12
+ export interface SvgNode { name: string; attrs: [string, string][]; children: (SvgNode | string)[] }
13
+
14
+ const ELEMENTS = new Set([
15
+ 'svg', 'g', 'defs', 'marker', 'symbol', 'title', 'desc',
16
+ 'path', 'polygon', 'polyline', 'line', 'rect', 'circle', 'ellipse', 'text', 'tspan',
17
+ 'linearGradient', 'radialGradient', 'stop', 'clipPath',
18
+ ]);
19
+ const ATTRIBUTES = new Set([
20
+ 'id', 'class', 'role', 'transform', 'viewBox', 'width', 'height', 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy', 'r', 'rx', 'ry',
21
+ 'fx', 'fy', 'd', 'points', 'offset', 'gradientUnits', 'gradientTransform', 'markerWidth', 'markerHeight', 'refX', 'refY', 'orient',
22
+ 'markerUnits', 'text-anchor', 'dominant-baseline', 'font-size', 'font-weight', 'letter-spacing', 'fill', 'stroke', 'stroke-width',
23
+ 'stroke-dasharray', 'stroke-linecap', 'stroke-linejoin', 'opacity', 'fill-opacity', 'stroke-opacity', 'stop-color', 'stop-opacity',
24
+ 'marker-start', 'marker-mid', 'marker-end', 'clip-path', 'preserveAspectRatio', 'vector-effect', 'paint-order', 'style',
25
+ ]);
26
+ /** attributes whose value may name a reference: only url(#id) is kept */
27
+ const REFERENCES = new Set(['fill', 'stroke', 'marker-start', 'marker-mid', 'marker-end', 'clip-path', 'style']);
28
+
29
+ const ENTITY: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'" };
30
+ const unescape = (s: string) => s.replace(/&(amp|lt|gt|quot|apos|#39);/g, (_m, e: string) => ENTITY[e]);
31
+
32
+ /** may this attribute be set, with this value? */
33
+ export function allowed(name: string, value: string): boolean {
34
+ if (name.startsWith('data-') || name.startsWith('aria-')) return /^[a-z][\w-]*$/.test(name);
35
+ if (!ATTRIBUTES.has(name)) return false;
36
+ // a reference to anything but an id in the drawing (or a script: url, javascript:, expression()…) is dropped
37
+ if (REFERENCES.has(name) && /url\(\s*(?!['"]?#)|javascript:|expression\(|@import/i.test(value)) return false;
38
+ return true;
39
+ }
40
+
41
+ /**
42
+ * Read the renderer's SVG text into a tree of allowed elements (their attributes filtered, their texts unescaped).
43
+ * A disallowed element is dropped with everything inside it; comments are dropped; anything that isn't the renderer's
44
+ * well-formed output (an unclosed tag, a stray close) throws, so a broken drawing is never half-built.
45
+ */
46
+ export function parseSvg(markup: string): SvgNode {
47
+ const root: SvgNode = { name: '#root', attrs: [], children: [] };
48
+ const stack: { node: SvgNode; dropped: boolean }[] = [{ node: root, dropped: false }];
49
+ // (a comment as <(?:!--): a bundle inlined in an HTML page must hold no "<!--", which switches the page's parser
50
+ // out of the script; the same pattern, and no minifier folds it back)
51
+ const re = /<(?:!--)[\s\S]*?-->|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:\s+[\w:-]+="[^"]*")*)\s*(\/?)>|([^<]+)/g;
52
+ let m: RegExpExecArray | null, at = 0;
53
+ while ((m = re.exec(markup))) {
54
+ if (m.index !== at) throw new Error(`not the renderer's SVG at ${at}: ${JSON.stringify(markup.slice(at, at + 40))}`);
55
+ at = re.lastIndex;
56
+ const top = stack[stack.length - 1];
57
+ if (m[0].charAt(1) === '!') continue; // a comment (the only match starting <!)
58
+ if (m[1]) {
59
+ if (stack.length < 2 || top.node.name !== m[1]) throw new Error(`a stray </${m[1]}>`);
60
+ stack.pop();
61
+ continue;
62
+ }
63
+ if (m[2]) {
64
+ const name = m[2];
65
+ const attrs: [string, string][] = [];
66
+ for (const a of m[3].matchAll(/([\w:-]+)="([^"]*)"/g)) {
67
+ const k = a[1], v = unescape(a[2]);
68
+ if (k === 'xmlns' || k.startsWith('xmlns:')) continue; // createElementNS gives the namespace
69
+ if (allowed(k, v)) attrs.push([k, v]);
70
+ }
71
+ const node: SvgNode = { name, attrs, children: [] };
72
+ const dropped = top.dropped || !ELEMENTS.has(name);
73
+ if (!dropped) top.node.children.push(node);
74
+ if (!m[4]) stack.push({ node, dropped });
75
+ continue;
76
+ }
77
+ if (!top.dropped && m[5].trim()) top.node.children.push(unescape(m[5]));
78
+ }
79
+ if (at !== markup.length) throw new Error(`not the renderer's SVG at ${at}`);
80
+ if (stack.length !== 1) throw new Error(`<${stack[stack.length - 1].node.name}> is never closed`);
81
+ return root;
82
+ }
83
+
84
+ const SVGNS = 'http://www.w3.org/2000/svg';
85
+ /** the diagram's custom properties, --iso-* in the page (as canvas.css names them) */
86
+ const isoVars = (v: string) => v.replace(/var\(--([a-zA-Z][\w-]*)/g, 'var(--iso-$1');
87
+
88
+ /** Make the drawing: the tree's first element (an <svg>), as DOM. */
89
+ export function buildSvg(markup: string, d: Document = document): SVGSVGElement {
90
+ const make = (n: SvgNode): Element => {
91
+ const el = d.createElementNS(SVGNS, n.name);
92
+ for (const [k, v] of n.attrs) {
93
+ // a style is set through the CSSOM, not as an attribute (the page could forbid inline style attributes)
94
+ if (k === 'style') (el as SVGElement).style.cssText = isoVars(v);
95
+ else el.setAttribute(k, /var\(--/.test(v) ? isoVars(v) : v);
96
+ }
97
+ for (const c of n.children) el.append(typeof c === 'string' ? d.createTextNode(c) : make(c));
98
+ return el;
99
+ };
100
+ const top = parseSvg(markup).children.find((c): c is SvgNode => typeof c !== 'string' && c.name === 'svg');
101
+ if (!top) throw new Error('the drawing has no <svg>');
102
+ return make(top) as SVGSVGElement;
103
+ }
@@ -0,0 +1,64 @@
1
+ // Themes are data (themes/*.yaml). This turns one into CSS custom properties for light and dark,
2
+ // following prefers-color-scheme unless the page sets data-theme, exactly as the reference pages do.
3
+
4
+ import { parse as parseYaml } from 'yaml';
5
+
6
+ /** a colour role: a hue and saturation the theme's shades are made from */
7
+ export interface RawRole { h: number; s: number; top?: string; tint?: number }
8
+ /** a route kind's look: its colour (or a role's, by like:), its dash and its legend */
9
+ export interface RawKind { legend?: string; like?: string; color?: string; dash?: 'solid' | 'dashed' | 'dotted' }
10
+ /** a theme: CSS tokens for light and dark, and the route kinds and colour roles drawings name */
11
+ export interface Theme {
12
+ name: string;
13
+ light: Record<string, string>;
14
+ dark: Record<string, string>;
15
+ kinds: Record<string, { color: string; dash: 'solid' | 'dashed' | 'dotted'; legend: string }>;
16
+ roles: Record<string, RawRole>;
17
+ }
18
+
19
+ export function loadTheme(text: string): Theme {
20
+ const t = parseYaml(text) as Theme;
21
+ for (const k of ['light', 'dark', 'kinds', 'roles'] as const) if (!t || typeof t[k] !== 'object') throw new Error(`theme: missing "${k}"`);
22
+ return t;
23
+ }
24
+
25
+ /** The theme with a file's own roles and kinds added. */
26
+ export function extendTheme(t: Theme, roles: Record<string, RawRole> = {}, kinds: Record<string, RawKind> = {}): Theme {
27
+ const k = { ...t.kinds };
28
+ for (const [name, def] of Object.entries(kinds)) {
29
+ const base = k[def.like ?? name] ?? k.control;
30
+ k[name] = { color: def.color ?? base.color, dash: def.dash ?? base.dash, legend: def.legend ?? base.legend };
31
+ }
32
+ return { ...t, roles: { ...t.roles, ...roles }, kinds: k };
33
+ }
34
+
35
+ const vars = (o: Record<string, string>) => Object.entries(o).map(([k, v]) => `--${k}:${v}`).join(';');
36
+
37
+ /** A colour value usable in CSS: a theme token name or a literal colour. */
38
+ export function colorRef(t: Theme, c: string): string {
39
+ return c in t.light ? `var(--${c})` : c;
40
+ }
41
+
42
+ export function themeCss(t: Theme): string {
43
+ const { light: L, dark: Dk, rest } = themeParts(t);
44
+ return `:root{${L}}\n@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){${Dk}}}\n:root[data-theme="dark"]{${Dk}}\n${rest}`;
45
+ }
46
+
47
+ /** The theme's CSS in pieces: the light and dark tokens (declarations), and the rules for its roles and kinds. */
48
+ export function themeParts(t: Theme): { light: string; dark: string; rest: string } {
49
+ let css = '';
50
+ // colour roles: hue and saturation per role; the face lightness comes from the theme
51
+ for (const [name, r] of Object.entries(t.roles)) {
52
+ css += `.k-${name}{--h:${r.h};--s:${r.s}%}`;
53
+ if (r.top) css += `.k-${name} .top{fill:${r.top}}`;
54
+ else if (r.tint) css += `.k-${name} .top{fill:color-mix(in srgb,hsl(${r.h} ${Math.min(100, r.s + 15)}% 50%) ${r.tint}%,var(--pad-top))}`;
55
+ css += '\n';
56
+ }
57
+ // flow kinds
58
+ for (const [name, k] of Object.entries(t.kinds)) {
59
+ const c = colorRef(t, k.color);
60
+ const dash = k.dash === 'dashed' ? ';stroke-dasharray:7 6;stroke-width:2.4' : k.dash === 'dotted' ? ';stroke-dasharray:3 6;stroke-width:2.4' : '';
61
+ css += `.f-${name}{stroke:${c}${dash}} .t-${name}{fill:${c}} .c-${name}{--c:${c}}\n`;
62
+ }
63
+ return { light: vars(t.light), dark: vars(t.dark), rest: css };
64
+ }
@@ -0,0 +1,41 @@
1
+ // A small virtual document for the render-only entry (a still render): just what the overlay's painters use
2
+ // (createElementNS, setAttribute, getAttribute, append, textContent, style.*), so the same painters that draw into the
3
+ // editor's DOM can draw into a tree that is written out as text, with no DOM at all (Node, a background thread, a server).
4
+
5
+ export interface VNode { name: string; attrs: [string, string][]; children: (VNode | string)[] }
6
+
7
+ const kebab = (k: string) => k.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
8
+
9
+ export class VEl implements VNode {
10
+ name: string;
11
+ attrs: [string, string][] = [];
12
+ children: (VNode | string)[] = [];
13
+ /** style properties as set (fontSize, transformOrigin…), written out as one style attribute */
14
+ style: Record<string, string> = {};
15
+ constructor(name: string) { this.name = name; }
16
+ setAttribute(k: string, v: string) { const i = this.attrs.findIndex(a => a[0] === k); if (i >= 0) this.attrs[i][1] = String(v); else this.attrs.push([k, String(v)]); }
17
+ getAttribute(k: string) { return this.attrs.find(a => a[0] === k)?.[1] ?? null; }
18
+ append(...ns: (VEl | string)[]) { for (const n of ns) if (n !== null && n !== undefined) this.children.push(n); }
19
+ set textContent(t: string) { this.children = [String(t)]; }
20
+ get textContent() { return this.children.map(c => (typeof c === 'string' ? c : (c as VEl).textContent)).join(''); }
21
+ /** as a plain node, its style folded into a style attribute */
22
+ toNode(): VNode {
23
+ const st = Object.entries(this.style).filter(([, v]) => v !== '' && v !== undefined).map(([k, v]) => `${kebab(k)}:${v}`).join(';');
24
+ return { name: this.name, attrs: st ? [...this.attrs, ['style', st]] : [...this.attrs], children: this.children.map(c => (c instanceof VEl ? c.toNode() : c)) };
25
+ }
26
+ }
27
+
28
+ /** a stand-in for document, as far as the painters go */
29
+ export const vdoc = { createElementNS: (_ns: string, name: string) => new VEl(name) };
30
+
31
+ const escText = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
32
+ const escAttr = (s: string) => escText(s).replace(/"/g, '&quot;');
33
+
34
+ /** a tree as SVG text (every value escaped; raw text only where the caller says, for its own <style>) */
35
+ export function serialize(n: VNode | string, raw = new Set<string>(['style'])): string {
36
+ if (typeof n === 'string') return escText(n);
37
+ const a = n.attrs.map(([k, v]) => ` ${k}="${escAttr(v)}"`).join('');
38
+ if (!n.children.length) return `<${n.name}${a}/>`;
39
+ const inner = raw.has(n.name) ? n.children.map(c => (typeof c === 'string' ? c.replace(/<\//g, '<\\/') : serialize(c, raw))).join('') : n.children.map(c => serialize(c, raw)).join('');
40
+ return `<${n.name}${a}>${inner}</${n.name}>`;
41
+ }
@@ -0,0 +1,128 @@
1
+ // The domain adapter (docs/editor/LAYERS.md §4): everything the editor needs to know of a file format, so the model,
2
+ // the commands, the clipboard, completion, the outline, problems and the text pane's providers stay domain-free.
3
+ // A domain writes one; the editor's modules are given it.
4
+
5
+ import type { Path } from './path.ts';
6
+ import type { Diag } from '../iso-core/errors.ts';
7
+
8
+ /** what a file is to the domain: its main kind, a base that files extend, or something else */
9
+ export type FileRole = 'main' | 'base' | 'other';
10
+
11
+ /** one kind of thing a file holds, by name, in a map of its own (its section) */
12
+ export interface ObjectKindInfo {
13
+ /** the kind's name (what references target) */
14
+ kind: string;
15
+ /** where its entries live: their map's path */
16
+ section: Path;
17
+ /** what one is called ("node"), and its group in the outline ("Nodes") */
18
+ singular: string;
19
+ group: string;
20
+ /** what a new one starts as */
21
+ template(): unknown;
22
+ }
23
+
24
+ /** a place in a file whose value names another thing */
25
+ export interface RefSlot {
26
+ /** path segments; '*' is any name, '#' any list index */
27
+ at: string[];
28
+ /** the kinds a value here may name */
29
+ targets: string[];
30
+ /** words that are allowed here and aren't names */
31
+ extra?: string[];
32
+ /** the name inside a value, or undefined when the value names nothing */
33
+ name?(value: string): string | undefined;
34
+ /** the value with its name replaced */
35
+ rename?(value: string, to: string): string;
36
+ /** what the completion list shows for a name */
37
+ write?(name: string): string;
38
+ /** a value that is a path, not a name */
39
+ pathOk?: boolean;
40
+ /** the key itself is the reference */
41
+ key?: boolean;
42
+ what: string;
43
+ }
44
+ export interface Ref {
45
+ /** the JSON pointer of the value (or of the key, for key slots) */
46
+ path: string;
47
+ slot: RefSlot;
48
+ value: string;
49
+ /** the name it refers to, if it refers to one */
50
+ name?: string;
51
+ }
52
+
53
+ /** a thing at a pointer: its kind, its name and its own pointer */
54
+ export interface ObjectRef { kind: string; name: string; path: string }
55
+
56
+ /** what the domain's reader says of a text */
57
+ export interface ReadOutcome {
58
+ diags: Diag[];
59
+ /** each object's tag (the outline shows it), by name */
60
+ tags?: Map<string, string>;
61
+ /** the domain's own reading, for its views */
62
+ read?: unknown;
63
+ }
64
+
65
+ /** what each part of the editor asks of an adapter (a domain may give a part only what it asks: smaller bundles) */
66
+ export type CommandsAdapter = Pick<DomainAdapter, 'kinds' | 'objectOf' | 'describe' | 'refs' | 'renameRef' | 'refDeletePath' | 'copyValue' | 'topOrder' | 'pins'>;
67
+ export type ClipboardAdapter = CommandsAdapter & Pick<DomainAdapter, 'entryGroups' | 'pasteDrops' | 'noun'>;
68
+ export type CompleteAdapter = Pick<DomainAdapter, 'snippets' | 'slotAt' | 'kinds' | 'extraDetail'>;
69
+ export type OutlineAdapter = Pick<DomainAdapter, 'outline' | 'kinds'>;
70
+ export type PlaceAdapter = Pick<DomainAdapter, 'objectOf' | 'keyMessage'>;
71
+ export type ReadAdapter = PlaceAdapter & Pick<DomainAdapter, 'read' | 'role'>;
72
+ export type ProvidersAdapter = CompleteAdapter & Pick<DomainAdapter, 'schema' | 'role' | 'refs'>;
73
+
74
+ export interface DomainAdapter {
75
+ /** the format it reads ("boxes/1") */
76
+ id: string;
77
+ role(text: string): FileRole;
78
+ /** the JSON Schema for a role (completion, hover, the properties panel); `text` (0.8.0) is the file's, for a format whose
79
+ * version line picks its schema (the same object for the same schema: the editor keeps one navigator per object) */
80
+ schema(role: FileRole, text?: string): object;
81
+ /** the problems in a text, from the domain's reader (with the files it extends, as the host resolved them) */
82
+ read(text: string, o: { fileName: string; defaults?: { name: string; text: string }[]; profiles?: string[]; role: FileRole }): ReadOutcome;
83
+ /** a reader's message that is about a key (placed on the key, not its value) */
84
+ keyMessage: RegExp;
85
+
86
+ /** the kinds, in the order the clipboard keeps them; names are unique across every kind */
87
+ kinds: ObjectKindInfo[];
88
+ /** what the domain calls an object, in words ("resource") */
89
+ noun: string;
90
+ /** the object a pointer is inside, if any */
91
+ objectOf(ptr: string): ObjectRef | undefined;
92
+ /** a path in words: "node web"; anything else its dotted path */
93
+ describe(p: Path): string;
94
+ /** named maps that aren't kinds (their names a pool of their own): copied, pasted and renamed like objects */
95
+ entryGroups: Path[];
96
+
97
+ /** every reference in the data, and the slot at a pointer */
98
+ refs(data: unknown): Ref[];
99
+ slotAt(ptr: string): RefSlot | undefined;
100
+ /** a reference's new text when what it names is renamed to `to`; undefined: it stays as written */
101
+ renameRef(ref: Ref, to: string): string | undefined;
102
+ /** what deleting a reference (with the thing it names) removes: the reference, or the entry holding it */
103
+ refDeletePath(p: Path): Path;
104
+ /** a copy of an object's value (duplicate): what it can't keep (a flag only one may have) dropped */
105
+ copyValue(kind: string, value: unknown): unknown;
106
+ /** a paste into this data: keys a pasted object drops (the path), and why, in words */
107
+ pasteDrops?(target: unknown, pasted: { kind: string; path: Path; value: unknown }): { path: Path; why: string } | undefined;
108
+ /** what a completion list says of an extra word in a slot */
109
+ extraDetail?(word: string, data: unknown): string | undefined;
110
+
111
+ /** the top-level key order: where a new section goes */
112
+ topOrder: readonly string[];
113
+ /** the layout pins: the key they live under, a legacy key read too, and whether a file has only the legacy one */
114
+ pins: { key: string; legacyKey?: string; legacyOnly(data: unknown): boolean };
115
+ /** new-entry snippets (Monaco syntax), by the pointer of the map they go in ('#…' tells several apart) */
116
+ snippets: Record<string, { label: string; body: string; doc: string }>;
117
+ /** the outline: the settings shown first, the setting groups after the kinds, and the root's label */
118
+ outline: {
119
+ /** the kinds' groups, in this order */
120
+ kinds: readonly string[];
121
+ first: readonly string[];
122
+ /** the setting groups; `when` (0.8.0): whether a missing one is offered, by the file's data (a version's own keys) */
123
+ groups: readonly { key: string; label: string; when?(data: Record<string, unknown>): boolean }[];
124
+ rootLabel(data: Record<string, unknown>, role: FileRole): string;
125
+ /** an object's tag from this file alone (when the reader's isn't known) */
126
+ tag?(kind: string, name: string, value: unknown, data: Record<string, unknown>): string | undefined;
127
+ };
128
+ }
@@ -0,0 +1,163 @@
1
+ // The clipboard: what is copied is plain YAML, so it pastes into the text pane, another file or another program.
2
+ // - Objects (and the entries of an entry group) are copied from their source text, comments and all, wrapped in
3
+ // their sections (a section nested in a map is wrapped in both).
4
+ // - Anything else (a key inside an object, a setting) is copied as its own "key: value" lines.
5
+ // Pasting objects: a name already used gets -2, -3…; references inside the pasted set are rewritten to the new names
6
+ // (the adapter's one table); references to things outside it are kept, and the problems list shows any the target
7
+ // doesn't have. Pasting plain keys sets them on the selected object(s). Each paste is one command. Pure.
8
+
9
+ import { parseDocument } from 'yaml';
10
+ import { pairText, insertRawPair, insertKey, setValue, renameKey, deleteAt, applyStep, type Splice, type Step } from './splice.ts';
11
+ import { toPointer, fromPointer, isPrefix, type Path } from './path.ts';
12
+ import type { Command } from './model.ts';
13
+ import { commandsFor, chain } from './commands.ts';
14
+ import type { ClipboardAdapter } from './adapter.ts';
15
+
16
+ type Raw = Record<string, unknown>;
17
+ const isMap = (v: unknown): v is Raw => !!v && typeof v === 'object' && !Array.isArray(v);
18
+
19
+ /** What a paste would do, described (for the menu), or why it can't. */
20
+ export interface PastePlan { cmd?: Command; what: string; names?: Map<string, string>; error?: string }
21
+
22
+ /** The clipboard, for one domain. */
23
+ export function clipboardFor(a: ClipboardAdapter) {
24
+ const { deleteCmd, describe, setCmd } = commandsFor(a);
25
+ const order = a.topOrder;
26
+ const sectionPtrs = a.kinds.map(k => toPointer(k.section));
27
+ const kindOfSection = new Map(a.kinds.map(k => [toPointer(k.section), k]));
28
+ const groupPtrs = a.entryGroups.map(g => toPointer(g));
29
+
30
+ /** the top-level path a copied thing lives under: an object's section, or its entry group */
31
+ function holderOf(p: Path): Path | undefined {
32
+ const r = a.objectOf(toPointer(p));
33
+ if (r && r.path === toPointer(p)) return a.kinds.find(k => k.kind === r.kind)!.section;
34
+ const g = a.entryGroups.find(g => p.length === g.length + 1 && isPrefix(g, p));
35
+ if (g) return g;
36
+ return undefined;
37
+ }
38
+
39
+ /** What is copied for these paths, as YAML text (and a short description of it). */
40
+ function copyText(text: string, paths: Path[]): { text: string; what: string } | undefined {
41
+ const top = paths.filter(p => p.length && !paths.some(o => o !== p && o.length < p.length && isPrefix(o, p)));
42
+ if (!top.length) return undefined;
43
+ const whole = top.filter(p => holderOf(p));
44
+ if (whole.length === top.length) {
45
+ // grouped by where they live, in the spec's order; each pair's own source text, indented under its section
46
+ const groups = new Map<string, Path[]>();
47
+ for (const p of whole) { const k = toPointer(holderOf(p)!); groups.set(k, [...(groups.get(k) ?? []), p]); }
48
+ const out: string[] = [];
49
+ const holders = [...sectionPtrs, ...groupPtrs];
50
+ for (const g of [...groups.keys()].sort((x, y) => holders.indexOf(x) - holders.indexOf(y))) {
51
+ const h = fromPointer(g);
52
+ const pairs = groups.get(g)!.map(p => pairText(text, p)).filter((x): x is string => !!x);
53
+ const indent = ' '.repeat(h.length);
54
+ out.push(h.map((k, i) => `${' '.repeat(i)}${k}:`).join('\n') + '\n' + pairs.map(t => t.replace(/\n$/, '').split('\n').map(l => (l ? indent + l : l)).join('\n')).join('\n') + '\n');
55
+ }
56
+ const n = whole.length;
57
+ return { text: out.join(''), what: n === 1 ? describe(whole[0]) : `${n} items` };
58
+ }
59
+ // keys inside something: their own lines, at indent 0
60
+ const lines = top.map(p => (typeof p[p.length - 1] === 'string' ? pairText(text, p) : undefined)).filter((x): x is string => !!x);
61
+ if (!lines.length) return undefined;
62
+ return { text: lines.join(''), what: top.length === 1 ? describe(top[0]) : `${top.length} keys` };
63
+ }
64
+
65
+ /** Paste YAML into the file: objects into their sections, or keys onto the selected objects. */
66
+ function pasteCmd(text: string, clip: string, selection: Path[] = []): PastePlan {
67
+ const parsed = parseDocument(clip);
68
+ if (parsed.errors.length) return { what: 'nothing', error: `the clipboard isn't YAML: ${parsed.errors[0].message.split('\n')[0]}` };
69
+ const data = parsed.toJS() as unknown;
70
+ if (!isMap(data) || !Object.keys(data).length) return { what: 'nothing', error: 'the clipboard holds no YAML map' };
71
+ const tops = new Set([...a.kinds.map(k => String(k.section[0])), ...a.entryGroups.map(g => String(g[0]))]);
72
+ const resourcesPaste = Object.keys(data).every(k => tops.has(k));
73
+ if (resourcesPaste) return pasteResources(text, clip, data);
74
+ // keys onto the selected resources
75
+ const targets = [...new Map(selection.map(p => a.objectOf(toPointer(p))).filter((r): r is NonNullable<typeof r> => !!r).map(r => [r.path, fromPointer(r.path)])).values()];
76
+ if (!targets.length) return { what: 'nothing', error: `select a ${a.noun} to paste these keys onto` };
77
+ const keys = Object.entries(data);
78
+ const label = `Paste ${keys.map(([k]) => k).join(', ')} onto ${targets.length === 1 ? describe(targets[0]) : `${targets.length} items`}`;
79
+ return {
80
+ what: label,
81
+ cmd: {
82
+ label, touched: targets,
83
+ build: t => chain(t, targets.flatMap(p => keys.map(([k, v]) => (x: string) => setCmd([...p, k], v).build(x)))),
84
+ },
85
+ };
86
+ }
87
+
88
+ function pasteResources(text: string, clip: string, data: Raw): PastePlan {
89
+ const target = parseDocument(text).toJS() as Raw | null;
90
+ // the names in the target, across every kind: a pasted name that clashes gets -2, -3… (an entry group's names are a
91
+ // pool of their own)
92
+ const taken = new Set<string>();
93
+ for (const k of a.kinds) { const m = getIn(target, k.section); if (isMap(m)) for (const n of Object.keys(m)) taken.add(n); }
94
+ const pools = new Map(a.entryGroups.map(g => { const m = getIn(target, g); return [toPointer(g), new Set(Object.keys(isMap(m) ? m : {}))] as const; }));
95
+ const items: { holder: Path; name: string; to: string }[] = [];
96
+ for (const p of [...sectionPtrs, ...groupPtrs]) {
97
+ const m = getIn(data, fromPointer(p));
98
+ if (!isMap(m)) continue;
99
+ for (const name of Object.keys(m)) {
100
+ const pool = pools.get(p) ?? taken;
101
+ let to = name;
102
+ if (pool.has(to)) { const stem = name.replace(/-\d+$/, ''); let i = 2; while (pool.has(`${stem}-${i}`)) i++; to = `${stem}-${i}`; }
103
+ pool.add(to);
104
+ items.push({ holder: fromPointer(p), name, to });
105
+ }
106
+ }
107
+ if (!items.length) return { what: 'nothing', error: 'nothing to paste' };
108
+ const renamed = new Map(items.filter(i => !pools.has(toPointer(i.holder)) && i.name !== i.to).map(i => [i.name, i.to]));
109
+ // the clipboard text, with its pasted things renamed and the references among them following (its own splices)
110
+ let frag = clip;
111
+ const step = (s: Splice) => { for (const st of s.steps) frag = applyStep(frag, st); };
112
+ const sectionOf = (kind: string) => a.kinds.find(k => k.kind === kind)?.section ?? [];
113
+ for (const r of a.refs(data)) {
114
+ if (r.slot.key) continue;
115
+ const to = r.name !== undefined ? renamed.get(r.name) : undefined;
116
+ if (!to || !(r.slot.targets.some(s => isMap(getIn(data, sectionOf(s))) && r.name! in (getIn(data, sectionOf(s)) as Raw)))) continue;
117
+ step(setValue(frag, fromPointer(r.path), r.slot.rename ? r.slot.rename(r.value, to) : to));
118
+ }
119
+ // what a pasted object can't keep in this target (the adapter says: a flag only one may have)
120
+ const dropped: string[] = [];
121
+ let dropWhy = '';
122
+ for (const i of items) {
123
+ const k = kindOfSection.get(toPointer(i.holder));
124
+ const drop = k && a.pasteDrops?.(target, { kind: k.kind, path: [...i.holder, i.name], value: getIn(data, [...i.holder, i.name]) });
125
+ if (drop) { step(deleteAt(frag, drop.path)); dropped.push(i.to); dropWhy = drop.why; }
126
+ }
127
+ for (const i of items) if (i.name !== i.to) step(renameKey(frag, [...i.holder, i.name], i.to));
128
+ const fragDoc = parseDocument(frag).toJS() as Raw;
129
+ const n = items.length;
130
+ const label = n === 1 ? `Paste ${kindOfSection.get(toPointer(items[0].holder))?.singular ?? a.kinds[0]?.singular ?? 'entry'} ${items[0].to}` : `Paste ${n} items`;
131
+ return {
132
+ what: label + (dropped.length ? ` (${dropped.join(', ')}: ${dropWhy})` : ''), names: new Map(items.map(i => [i.name, i.to])),
133
+ cmd: {
134
+ label: pools.has(toPointer(items[0].holder)) && n === 1 ? `Paste ${items[0].holder.join('.')} entry ${items[0].to}` : label,
135
+ select: items.map(i => [...i.holder, i.to]),
136
+ build: t => chain(t, items.map(i => (x: string) => {
137
+ const holder = i.holder;
138
+ const exists = isMap(getIn(parseDocument(x).toJS(), holder));
139
+ if (!exists) return insertKey(x, holder.slice(0, -1), String(holder[holder.length - 1]), { [i.to]: getIn(fragDoc, [...holder, i.to]) }, { order });
140
+ const raw = pairText(frag, [...holder, i.to]);
141
+ return raw ? insertRawPair(x, holder, i.to, raw, order) : insertKey(x, holder, i.to, getIn(fragDoc, [...holder, i.to]), { order });
142
+ })),
143
+ },
144
+ };
145
+ }
146
+
147
+ /** Cut: copy, then delete, as one command (the references to what is cut stay, for a paste to satisfy). */
148
+ function cutCmd(text: string, paths: Path[]): { text: string; cmd: Command } | undefined {
149
+ const c = copyText(text, paths);
150
+ if (!c) return undefined;
151
+ const top = paths.filter(p => p.length && !paths.some(o => o !== p && o.length < p.length && isPrefix(o, p)));
152
+ const order = [...top].sort((a, b) => (typeof a.at(-1) === 'number' && typeof b.at(-1) === 'number' ? (b.at(-1) as number) - (a.at(-1) as number) : 0));
153
+ return {
154
+ text: c.text,
155
+ cmd: { label: `Cut ${c.what}`, remap: p => (top.some(t => isPrefix(t, p)) ? null : p), build: t => chain(t, order.map(p => (x: string) => deleteCmd(p).build(x))) },
156
+ };
157
+ }
158
+
159
+ return { copyText, pasteCmd, cutCmd };
160
+ }
161
+ export type Clipboard = ReturnType<typeof clipboardFor>;
162
+
163
+ const getIn = (o: unknown, p: Path) => p.reduce<unknown>((x, k) => (x && typeof x === 'object' ? (x as Raw)[k as string] : undefined), o);