@johnoscott/isometric-engine 0.0.0-stage → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (310) hide show
  1. package/EDITOR-GUIDE.md +355 -0
  2. package/LICENSE +21 -0
  3. package/LICENSES/ajv.txt +22 -0
  4. package/LICENSES/lucide-static.txt +43 -0
  5. package/LICENSES/yaml.txt +13 -0
  6. package/README.md +62 -2
  7. package/assets/app.css +269 -0
  8. package/assets/default-theme.yaml +99 -0
  9. package/assets/icons.svg +1 -0
  10. package/assets/marks.css +39 -0
  11. package/assets/skin.css +181 -0
  12. package/iso-editor.d.ts +4 -0
  13. package/iso-editor.js +550 -0
  14. package/iso-render.d.ts +3 -0
  15. package/iso-render.js +388 -0
  16. package/iso-systems.d.ts +4 -0
  17. package/iso-systems.js +389 -0
  18. package/js/iso-core/compile-schema.js +22 -0
  19. package/js/iso-core/depth.js +55 -0
  20. package/js/iso-core/errors.js +65 -0
  21. package/js/iso-core/glyphs.js +100 -0
  22. package/js/iso-core/index.js +55 -0
  23. package/js/iso-core/kernel.js +158 -0
  24. package/js/iso-core/metrics.json +1 -0
  25. package/js/iso-core/package.json +6 -0
  26. package/js/iso-core/parse.js +79 -0
  27. package/js/iso-core/schema-errors.js +170 -0
  28. package/js/iso-core/shims/crypto.js +125 -0
  29. package/js/iso-core/shims/path.js +49 -0
  30. package/js/iso-core/svg-dom.js +144 -0
  31. package/js/iso-core/theme.js +48 -0
  32. package/js/iso-core/vdom.js +48 -0
  33. package/js/iso-editor/adapter.js +0 -0
  34. package/js/iso-editor/clipboard.js +152 -0
  35. package/js/iso-editor/commands.js +173 -0
  36. package/js/iso-editor/complete.js +55 -0
  37. package/js/iso-editor/doc.js +182 -0
  38. package/js/iso-editor/index.js +105 -0
  39. package/js/iso-editor/model.js +210 -0
  40. package/js/iso-editor/outline.js +111 -0
  41. package/js/iso-editor/package.json +6 -0
  42. package/js/iso-editor/path.js +19 -0
  43. package/js/iso-editor/providers.js +96 -0
  44. package/js/iso-editor/schema-nav.js +117 -0
  45. package/js/iso-editor/splice.js +443 -0
  46. package/js/iso-editor/storage-keys.js +6 -0
  47. package/js/iso-editor/ui/actions.js +116 -0
  48. package/js/iso-editor/ui/canvas-layer.js +0 -0
  49. package/js/iso-editor/ui/canvas.js +1403 -0
  50. package/js/iso-editor/ui/clip.js +133 -0
  51. package/js/iso-editor/ui/dialog.js +26 -0
  52. package/js/iso-editor/ui/flat-canvas.js +54 -0
  53. package/js/iso-editor/ui/icons.js +15 -0
  54. package/js/iso-editor/ui/keys.js +26 -0
  55. package/js/iso-editor/ui/later.js +28 -0
  56. package/js/iso-editor/ui/layer.js +11 -0
  57. package/js/iso-editor/ui/menu.js +105 -0
  58. package/js/iso-editor/ui/monaco-entry.js +2 -0
  59. package/js/iso-editor/ui/mount-kit.js +0 -0
  60. package/js/iso-editor/ui/mount.js +767 -0
  61. package/js/iso-editor/ui/pane.js +0 -0
  62. package/js/iso-editor/ui/part.js +0 -0
  63. package/js/iso-editor/ui/plain-icons.js +34 -0
  64. package/js/iso-editor/ui/props.js +314 -0
  65. package/js/iso-editor/ui/scope-css.js +81 -0
  66. package/js/iso-editor/ui/setup.js +149 -0
  67. package/js/iso-editor/ui/text.js +323 -0
  68. package/js/iso-editor/ui/tree.js +728 -0
  69. package/js/iso-editor/validate.js +33 -0
  70. package/js/iso-editor/window/protocol.js +8 -0
  71. package/js/iso-objects/assemble.js +43 -0
  72. package/js/iso-objects/assets.js +88 -0
  73. package/js/iso-objects/board.js +162 -0
  74. package/js/iso-objects/compile.js +60 -0
  75. package/js/iso-objects/css.js +154 -0
  76. package/js/iso-objects/flat.js +696 -0
  77. package/js/iso-objects/focus.js +16 -0
  78. package/js/iso-objects/geometry.js +76 -0
  79. package/js/iso-objects/index.js +93 -0
  80. package/js/iso-objects/kinds.js +12 -0
  81. package/js/iso-objects/labels.js +325 -0
  82. package/js/iso-objects/package.json +6 -0
  83. package/js/iso-objects/place.js +347 -0
  84. package/js/iso-objects/route.js +461 -0
  85. package/js/iso-objects/scene.js +350 -0
  86. package/js/iso-objects/steps.js +246 -0
  87. package/js/iso-objects/types.js +0 -0
  88. package/js/iso-systems/catalog.js +42 -0
  89. package/js/iso-systems/compile.js +34 -0
  90. package/js/iso-systems/css.js +8 -0
  91. package/js/iso-systems/index.js +16 -0
  92. package/js/iso-systems/nodes.js +124 -0
  93. package/js/iso-systems/package.json +6 -0
  94. package/js/iso-systems/schema.json +311 -0
  95. package/js/iso-systems/validate.js +35 -0
  96. package/js/iso-viewer/bundle.js +20 -0
  97. package/js/iso-viewer/card-motion.js +228 -0
  98. package/js/iso-viewer/dom.js +14 -0
  99. package/js/iso-viewer/dual-view.js +212 -0
  100. package/js/iso-viewer/flat-view.js +124 -0
  101. package/js/iso-viewer/history.js +990 -0
  102. package/js/iso-viewer/index.js +98 -0
  103. package/js/iso-viewer/morph.js +192 -0
  104. package/js/iso-viewer/overlay.js +199 -0
  105. package/js/iso-viewer/package.json +6 -0
  106. package/js/iso-viewer/page.js +138 -0
  107. package/js/iso-viewer/player.js +409 -0
  108. package/js/iso-viewer/still.js +81 -0
  109. package/js/iso-viewer/timeline-contract.js +14 -0
  110. package/js/iso-viewer/timeline-engine.js +475 -0
  111. package/js/iso-viewer/timeline-export.js +36 -0
  112. package/js/iso-viewer/timeline-scale.js +116 -0
  113. package/js/iso-viewer/timeline-scope.js +58 -0
  114. package/js/iso-viewer/timeline-search.js +216 -0
  115. package/js/iso-viewer/timeline-time.js +55 -0
  116. package/js/iso-viewer/view-css.js +68 -0
  117. package/js/iso-viewer/viewport.js +177 -0
  118. package/package.json +511 -4
  119. package/src/iso-core/compile-schema.ts +23 -0
  120. package/src/iso-core/depth.ts +56 -0
  121. package/src/iso-core/errors.ts +73 -0
  122. package/src/iso-core/glyphs.ts +108 -0
  123. package/src/iso-core/index.ts +27 -0
  124. package/src/iso-core/kernel.ts +163 -0
  125. package/src/iso-core/metrics.json +1 -0
  126. package/src/iso-core/package.json +6 -0
  127. package/src/iso-core/parse.ts +91 -0
  128. package/src/iso-core/schema-errors.ts +163 -0
  129. package/src/iso-core/shims/crypto.ts +37 -0
  130. package/src/iso-core/shims/path.ts +24 -0
  131. package/src/iso-core/svg-dom.ts +103 -0
  132. package/src/iso-core/theme.ts +64 -0
  133. package/src/iso-core/vdom.ts +41 -0
  134. package/src/iso-editor/adapter.ts +147 -0
  135. package/src/iso-editor/clipboard.ts +163 -0
  136. package/src/iso-editor/commands.ts +191 -0
  137. package/src/iso-editor/complete.ts +73 -0
  138. package/src/iso-editor/doc.ts +207 -0
  139. package/src/iso-editor/index.ts +67 -0
  140. package/src/iso-editor/model.ts +234 -0
  141. package/src/iso-editor/outline.ts +126 -0
  142. package/src/iso-editor/package.json +6 -0
  143. package/src/iso-editor/path.ts +18 -0
  144. package/src/iso-editor/providers.ts +113 -0
  145. package/src/iso-editor/schema-nav.ts +129 -0
  146. package/src/iso-editor/splice.ts +477 -0
  147. package/src/iso-editor/storage-keys.ts +6 -0
  148. package/src/iso-editor/ui/actions.ts +119 -0
  149. package/src/iso-editor/ui/app.css +230 -0
  150. package/src/iso-editor/ui/canvas-layer.ts +56 -0
  151. package/src/iso-editor/ui/canvas.ts +1227 -0
  152. package/src/iso-editor/ui/clip.ts +97 -0
  153. package/src/iso-editor/ui/dialog.ts +25 -0
  154. package/src/iso-editor/ui/flat-canvas.ts +51 -0
  155. package/src/iso-editor/ui/icons.ts +21 -0
  156. package/src/iso-editor/ui/keys.ts +30 -0
  157. package/src/iso-editor/ui/later.ts +22 -0
  158. package/src/iso-editor/ui/layer.ts +7 -0
  159. package/src/iso-editor/ui/marks.css +39 -0
  160. package/src/iso-editor/ui/menu.ts +67 -0
  161. package/src/iso-editor/ui/monaco-entry.ts +6 -0
  162. package/src/iso-editor/ui/mount-kit.ts +35 -0
  163. package/src/iso-editor/ui/mount.ts +684 -0
  164. package/src/iso-editor/ui/pane.ts +45 -0
  165. package/src/iso-editor/ui/part.ts +45 -0
  166. package/src/iso-editor/ui/plain-icons.ts +83 -0
  167. package/src/iso-editor/ui/props.ts +347 -0
  168. package/src/iso-editor/ui/scope-css.ts +65 -0
  169. package/src/iso-editor/ui/setup.ts +153 -0
  170. package/src/iso-editor/ui/skin.css +181 -0
  171. package/src/iso-editor/ui/text.ts +262 -0
  172. package/src/iso-editor/ui/tree.ts +657 -0
  173. package/src/iso-editor/validate.ts +62 -0
  174. package/src/iso-editor/window/protocol.ts +33 -0
  175. package/src/iso-objects/assemble.ts +57 -0
  176. package/src/iso-objects/assets.ts +122 -0
  177. package/src/iso-objects/board.ts +169 -0
  178. package/src/iso-objects/compile.ts +76 -0
  179. package/src/iso-objects/css.ts +163 -0
  180. package/src/iso-objects/flat.ts +653 -0
  181. package/src/iso-objects/focus.ts +14 -0
  182. package/src/iso-objects/geometry.ts +86 -0
  183. package/src/iso-objects/index.ts +33 -0
  184. package/src/iso-objects/kinds.ts +56 -0
  185. package/src/iso-objects/labels.ts +310 -0
  186. package/src/iso-objects/package.json +6 -0
  187. package/src/iso-objects/place.ts +318 -0
  188. package/src/iso-objects/route.ts +444 -0
  189. package/src/iso-objects/scene.ts +376 -0
  190. package/src/iso-objects/steps.ts +234 -0
  191. package/src/iso-objects/types.ts +68 -0
  192. package/src/iso-systems/catalog.ts +31 -0
  193. package/src/iso-systems/compile.ts +39 -0
  194. package/src/iso-systems/css.ts +9 -0
  195. package/src/iso-systems/index.ts +12 -0
  196. package/src/iso-systems/nodes.ts +126 -0
  197. package/src/iso-systems/package.json +6 -0
  198. package/src/iso-systems/schema.json +311 -0
  199. package/src/iso-systems/validate.ts +34 -0
  200. package/src/iso-viewer/bundle.ts +15 -0
  201. package/src/iso-viewer/card-motion.ts +237 -0
  202. package/src/iso-viewer/dom.ts +13 -0
  203. package/src/iso-viewer/dual-view.ts +212 -0
  204. package/src/iso-viewer/flat-view.ts +127 -0
  205. package/src/iso-viewer/history.ts +781 -0
  206. package/src/iso-viewer/index.ts +40 -0
  207. package/src/iso-viewer/morph.ts +191 -0
  208. package/src/iso-viewer/overlay.ts +212 -0
  209. package/src/iso-viewer/package.json +6 -0
  210. package/src/iso-viewer/page.ts +150 -0
  211. package/src/iso-viewer/player.ts +321 -0
  212. package/src/iso-viewer/still.ts +74 -0
  213. package/src/iso-viewer/timeline-contract.ts +342 -0
  214. package/src/iso-viewer/timeline-engine.ts +420 -0
  215. package/src/iso-viewer/timeline-export.ts +31 -0
  216. package/src/iso-viewer/timeline-scale.ts +129 -0
  217. package/src/iso-viewer/timeline-scope.ts +56 -0
  218. package/src/iso-viewer/timeline-search.ts +198 -0
  219. package/src/iso-viewer/timeline-time.ts +54 -0
  220. package/src/iso-viewer/view-css.ts +59 -0
  221. package/src/iso-viewer/viewport.ts +142 -0
  222. package/types/iso-core/compile-schema.d.ts +11 -0
  223. package/types/iso-core/depth.d.ts +6 -0
  224. package/types/iso-core/errors.d.ts +24 -0
  225. package/types/iso-core/glyphs.d.ts +19 -0
  226. package/types/iso-core/index.d.ts +17 -0
  227. package/types/iso-core/kernel.d.ts +130 -0
  228. package/types/iso-core/metrics.json +1 -0
  229. package/types/iso-core/parse.d.ts +18 -0
  230. package/types/iso-core/schema-errors.d.ts +14 -0
  231. package/types/iso-core/shims/crypto.d.ts +9 -0
  232. package/types/iso-core/svg-dom.d.ts +15 -0
  233. package/types/iso-core/theme.d.ts +38 -0
  234. package/types/iso-core/vdom.d.ts +26 -0
  235. package/types/iso-editor/adapter.d.ts +178 -0
  236. package/types/iso-editor/clipboard.d.ts +23 -0
  237. package/types/iso-editor/commands.d.ts +32 -0
  238. package/types/iso-editor/complete.d.ts +25 -0
  239. package/types/iso-editor/doc.d.ts +50 -0
  240. package/types/iso-editor/index.d.ts +57 -0
  241. package/types/iso-editor/model.d.ts +96 -0
  242. package/types/iso-editor/outline.d.ts +28 -0
  243. package/types/iso-editor/path.d.ts +7 -0
  244. package/types/iso-editor/providers.d.ts +43 -0
  245. package/types/iso-editor/schema-nav.d.ts +34 -0
  246. package/types/iso-editor/splice.d.ts +53 -0
  247. package/types/iso-editor/storage-keys.d.ts +5 -0
  248. package/types/iso-editor/ui/actions.d.ts +23 -0
  249. package/types/iso-editor/ui/canvas-layer.d.ts +65 -0
  250. package/types/iso-editor/ui/canvas.d.ts +307 -0
  251. package/types/iso-editor/ui/clip.d.ts +14 -0
  252. package/types/iso-editor/ui/dialog.d.ts +7 -0
  253. package/types/iso-editor/ui/flat-canvas.d.ts +2 -0
  254. package/types/iso-editor/ui/icons.d.ts +5 -0
  255. package/types/iso-editor/ui/keys.d.ts +7 -0
  256. package/types/iso-editor/ui/later.d.ts +12 -0
  257. package/types/iso-editor/ui/layer.d.ts +2 -0
  258. package/types/iso-editor/ui/menu.d.ts +21 -0
  259. package/types/iso-editor/ui/mount-kit.d.ts +31 -0
  260. package/types/iso-editor/ui/mount.d.ts +146 -0
  261. package/types/iso-editor/ui/pane.d.ts +60 -0
  262. package/types/iso-editor/ui/part.d.ts +40 -0
  263. package/types/iso-editor/ui/plain-icons.d.ts +10 -0
  264. package/types/iso-editor/ui/props.d.ts +57 -0
  265. package/types/iso-editor/ui/scope-css.d.ts +5 -0
  266. package/types/iso-editor/ui/setup.d.ts +49 -0
  267. package/types/iso-editor/ui/text.d.ts +19 -0
  268. package/types/iso-editor/ui/tree.d.ts +100 -0
  269. package/types/iso-editor/validate.d.ts +36 -0
  270. package/types/iso-editor/window/protocol.d.ts +60 -0
  271. package/types/iso-objects/assemble.d.ts +35 -0
  272. package/types/iso-objects/assets.d.ts +49 -0
  273. package/types/iso-objects/board.d.ts +36 -0
  274. package/types/iso-objects/compile.d.ts +35 -0
  275. package/types/iso-objects/css.d.ts +16 -0
  276. package/types/iso-objects/flat.d.ts +130 -0
  277. package/types/iso-objects/focus.d.ts +1 -0
  278. package/types/iso-objects/geometry.d.ts +59 -0
  279. package/types/iso-objects/index.d.ts +26 -0
  280. package/types/iso-objects/kinds.d.ts +53 -0
  281. package/types/iso-objects/labels.d.ts +92 -0
  282. package/types/iso-objects/place.d.ts +25 -0
  283. package/types/iso-objects/route.d.ts +67 -0
  284. package/types/iso-objects/scene.d.ts +63 -0
  285. package/types/iso-objects/steps.d.ts +90 -0
  286. package/types/iso-objects/types.d.ts +140 -0
  287. package/types/iso-systems/catalog.d.ts +4 -0
  288. package/types/iso-systems/compile.d.ts +6 -0
  289. package/types/iso-systems/css.d.ts +3 -0
  290. package/types/iso-systems/index.d.ts +5 -0
  291. package/types/iso-systems/nodes.d.ts +3 -0
  292. package/types/iso-viewer/card-motion.d.ts +56 -0
  293. package/types/iso-viewer/dom.d.ts +1 -0
  294. package/types/iso-viewer/dual-view.d.ts +44 -0
  295. package/types/iso-viewer/flat-view.d.ts +25 -0
  296. package/types/iso-viewer/history.d.ts +91 -0
  297. package/types/iso-viewer/index.d.ts +31 -0
  298. package/types/iso-viewer/morph.d.ts +28 -0
  299. package/types/iso-viewer/overlay.d.ts +135 -0
  300. package/types/iso-viewer/page.d.ts +13 -0
  301. package/types/iso-viewer/still.d.ts +26 -0
  302. package/types/iso-viewer/timeline-contract.d.ts +345 -0
  303. package/types/iso-viewer/timeline-engine.d.ts +20 -0
  304. package/types/iso-viewer/timeline-export.d.ts +5 -0
  305. package/types/iso-viewer/timeline-scale.d.ts +44 -0
  306. package/types/iso-viewer/timeline-scope.d.ts +33 -0
  307. package/types/iso-viewer/timeline-search.d.ts +52 -0
  308. package/types/iso-viewer/timeline-time.d.ts +8 -0
  309. package/types/iso-viewer/view-css.d.ts +7 -0
  310. package/types/iso-viewer/viewport.d.ts +50 -0
@@ -0,0 +1,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);
@@ -0,0 +1,191 @@
1
+ // The commands every view uses to change a file: each is a label, the splice it makes (worked out against the text it
2
+ // will apply to), and how paths move. Renaming an object renames every reference to it in the same command; deleting
3
+ // one can take its references with it. What is an object, what references it and how, are the adapter's. Pure.
4
+
5
+ import { parseDocument } from 'yaml';
6
+ import { setValue, insertKey, deleteAt, insertItem, renameKey, moveKey, applyStep, scalarText, type Splice, type Step } from './splice.ts';
7
+ import { EditorDoc } from './doc.ts';
8
+ import { isPrefix, toPointer, type Path } from './path.ts';
9
+ import type { Command } from './model.ts';
10
+ import type { CommandsAdapter, Ref } from './adapter.ts';
11
+
12
+ const dataOf = (t: string) => parseDocument(t, { uniqueKeys: false }).toJS() as unknown;
13
+
14
+ /** Run several splices one after the other, each against the text the previous one left. */
15
+ export function chain(text: string, parts: ((t: string) => Splice)[]): Splice {
16
+ const steps: Step[] = [];
17
+ let t = text;
18
+ let fallback = false;
19
+ for (const f of parts) {
20
+ const s = f(t);
21
+ for (const st of s.steps) { steps.push(st); t = applyStep(t, st); }
22
+ fallback ||= !!s.fallback;
23
+ }
24
+ return { steps, fallback };
25
+ }
26
+
27
+ /** Several commands as one: each built against the text the one before left; one undo step. */
28
+ export function seqCmd(label: string, cmds: Command[]): Command {
29
+ return { label, touched: cmds.flatMap(c => c.touched ?? []), select: cmds.find(c => c.select)?.select, build: t => chain(t, cmds.map(c => (u: string) => c.build(u))) };
30
+ }
31
+ const hasKey = (t: string, p: Path) => { const d = dataOf(t); const parent = p.slice(0, -1).reduce<unknown>((x, k) => (x as Record<string, unknown>)?.[k as string], d); return !!parent && typeof parent === 'object' && String(p[p.length - 1]) in (parent as object); };
32
+ const parsePath = (ptr: string): Path => ptr.split('/').slice(1).map(s => { const u = s.replace(/~1/g, '/').replace(/~0/g, '~'); return /^\d+$/.test(u) ? Number(u) : u; });
33
+
34
+ /** The commands, for one domain. */
35
+ export function commandsFor(a: CommandsAdapter) {
36
+ const describe = (p: Path) => a.describe(p);
37
+ const order = a.topOrder;
38
+ /** every name an object has, across every kind (one namespace) */
39
+ const allNames = (data: unknown) => {
40
+ const all = new Set<string>();
41
+ for (const k of a.kinds) {
42
+ const m = k.section.reduce<unknown>((x, s) => (x as Record<string, unknown>)?.[s as string], data);
43
+ if (m && typeof m === 'object') for (const n of Object.keys(m)) all.add(n);
44
+ }
45
+ return all;
46
+ };
47
+
48
+ function setCmd(path: Path, value: unknown, label = `Set ${describe(path)}`): Command {
49
+ return {
50
+ label, touched: [path],
51
+ build: t => {
52
+ const d = new EditorDoc(t);
53
+ if (d.rangeOf(path) || d.nodeAt(path) !== undefined || hasKey(t, path)) return setValue(t, path, value);
54
+ return insertKey(t, path.slice(0, -1), String(path[path.length - 1]), value, { order });
55
+ },
56
+ };
57
+ }
58
+ /** Pins, one command: PINS.layout.NAME = { at: [x, y] } for each (a drag that keeps its neighbours in place). */
59
+ function pinsCmd(pins: [string, [number, number]][], label: string): Command {
60
+ const paths = pins.map(([n]) => [a.pins.key, 'layout', n] as Path);
61
+ return withPinsMoved({ label, touched: paths, build: t => chain(t, pins.map(([, at], i) => (u: string) => setCmd(paths[i], { at }).build(u))) });
62
+ }
63
+ /** A pin edit that first moves pins kept under the legacy key to the current one (renaming the key in place), in the
64
+ * same command: one undo step puts both back. */
65
+ function withPinsMoved(cmd: Command): Command {
66
+ return { ...cmd, build: t => (a.pins.legacyOnly(dataOf(t)) ? chain(t, [u => renameKey(u, [a.pins.legacyKey!], a.pins.key), u => cmd.build(u)]) : cmd.build(t)) };
67
+ }
68
+
69
+ function insertCmd(mapPath: Path, key: string, value: unknown, opts: { after?: string; before?: string; label?: string } = {}): Command {
70
+ return { label: opts.label ?? `Add ${describe([...mapPath, key])}`, touched: [[...mapPath, key]], select: [[...mapPath, key]], build: t => insertKey(t, mapPath, key, value, { ...opts, order }) };
71
+ }
72
+
73
+ function insertItemCmd(listPath: Path, value: unknown, index?: number, label = `Add to ${describe(listPath)}`): Command {
74
+ return { label, touched: [listPath], build: t => insertItem(t, listPath, value, index, order) };
75
+ }
76
+
77
+ function moveCmd(path: Path, before?: string): Command {
78
+ return { label: `Move ${describe(path)}`, touched: [path], build: t => moveKey(t, path, before, order) };
79
+ }
80
+
81
+ /** The references to an object, from the adapter's one table. */
82
+ function referencesTo(text: string, kind: string, name: string): Ref[] {
83
+ return a.refs(dataOf(text)).filter(r => (r.slot.key ? r.value === name : r.name === name) && r.slot.targets.includes(kind));
84
+ }
85
+
86
+ function deleteCmd(path: Path, opts: { withRefs?: boolean } = {}): Command {
87
+ const res = a.objectOf(toPointer(path));
88
+ const whole = res && res.path === toPointer(path);
89
+ return {
90
+ label: `Delete ${describe(path)}`, touched: [path],
91
+ remap: p => (isPrefix(path, p) ? null : p),
92
+ build: t => {
93
+ if (!whole || !opts.withRefs) return deleteAt(t, path);
94
+ // its references go too: list items (last first, so the indices stay right), and the keys that hold the others
95
+ const refs = referencesTo(t, res!.kind, res!.name);
96
+ // the adapter says what a reference's deletion takes (a reference, or the entry that holds it); a reference
97
+ // that is itself a list item goes as it is
98
+ const taken = refs.map(r => { const p = parsePath(r.path); return typeof p.at(-1) === 'number' ? p : a.refDeletePath(p); });
99
+ // once each (a link naming it at both ends is one entry), and every list entry last first, whether a reference
100
+ // was one or the adapter mapped it to one, so the indices still to go stay right (0.7.1)
101
+ const once = [...new Map(taken.map(p => [toPointer(p), p])).values()];
102
+ const items = once.filter(p => typeof p.at(-1) === 'number').sort((a, b) => (b.at(-1) as number) - (a.at(-1) as number));
103
+ const keys = once.filter(p => typeof p.at(-1) !== 'number');
104
+ const all = [...items, ...keys, path];
105
+ // a path inside another being deleted needs no step of its own
106
+ const kept = all.filter((p, i) => !all.some((q, j) => j !== i && q.length < p.length && isPrefix(q, p)));
107
+ return chain(t, kept.map(p => (x: string) => deleteAt(x, p)));
108
+ },
109
+ };
110
+ }
111
+
112
+ /** Rename an object and every reference to it, as one command. */
113
+ function renameCmd(path: Path, to: string): Command {
114
+ const res = a.objectOf(toPointer(path));
115
+ const from = String(path[path.length - 1]);
116
+ const base = path.slice(0, -1);
117
+ return {
118
+ label: `Rename ${describe(path)} to ${to}`, touched: [[...base, to]],
119
+ remap: p => (isPrefix(path, p) ? [...base, to, ...p.slice(path.length)] : p),
120
+ build: t => {
121
+ const key = renameKey(t, path, to);
122
+ if (!res || res.path !== toPointer(path)) return key;
123
+ const d = new EditorDoc(t);
124
+ const edits: Step = [...key.steps[0]];
125
+ for (const r of referencesTo(t, res.kind, from)) {
126
+ const p = parsePath(r.path);
127
+ const v = a.renameRef(r, to);
128
+ if (v === undefined) continue;
129
+ const range = d.rangeOf(p, r.slot.key ? 'key' : 'value');
130
+ if (!range) continue;
131
+ const now = t.slice(range[0], range[1]);
132
+ const quote = now[0] === '"' || now[0] === "'" ? now[0] : undefined;
133
+ edits.push({ start: range[0], end: range[1], text: quote === '"' ? JSON.stringify(v) : quote === "'" ? `'${v}'` : scalarText(v, { flow: true, indent: 0 }) });
134
+ }
135
+ return { steps: [edits] };
136
+ },
137
+ };
138
+ }
139
+
140
+ /** A copy of an object under a new name (name-2, name-3…), right after it. */
141
+ function duplicateCmd(path: Path): Command {
142
+ const name = String(path[path.length - 1]);
143
+ const base = path.slice(0, -1);
144
+ let made = '';
145
+ return {
146
+ label: `Duplicate ${describe(path)}`,
147
+ get select() { return made ? [[...base, made]] : undefined; },
148
+ build: t => {
149
+ const data = dataOf(t);
150
+ const all = allNames(data);
151
+ const stem = name.replace(/-\d+$/, '');
152
+ let n = 2;
153
+ while (all.has(`${stem}-${n}`)) n++;
154
+ made = `${stem}-${n}`;
155
+ const kind = a.objectOf(toPointer(path))?.kind ?? '';
156
+ const value = a.copyValue(kind, path.reduce<unknown>((x, k) => (x as Record<string, unknown>)?.[k as string], data));
157
+ return insertKey(t, base, made, value, { after: name, order });
158
+ },
159
+ } as Command;
160
+ }
161
+
162
+ /** Rename a key that isn't an object (an entry, a label): no references follow it. */
163
+ function renameKeyCmd(path: Path, to: string): Command {
164
+ const base = path.slice(0, -1);
165
+ return { label: `Rename ${describe(path)} to ${to}`, touched: [[...base, to]], remap: p => (isPrefix(path, p) ? [...base, to, ...p.slice(path.length)] : p), build: t => renameKey(t, path, to) };
166
+ }
167
+
168
+ /** Move a list item to another index (its value moves; a comment on its line stays behind). */
169
+ function moveItemCmd(listPath: Path, from: number, to: number): Command {
170
+ return {
171
+ label: `Move ${describe([...listPath, from])}`, touched: [listPath],
172
+ remap: p => (isPrefix(listPath, p) && p.length > listPath.length && p[listPath.length] === from ? [...listPath, to, ...p.slice(listPath.length + 1)] : p),
173
+ build: t => {
174
+ if (from === to) return { steps: [] };
175
+ const value = [...listPath, from].reduce<unknown>((x, k) => (x as Record<string, unknown>)?.[k as string], dataOf(t));
176
+ return chain(t, [x => deleteAt(x, [...listPath, from]), x => insertItem(x, listPath, value, to, order)]);
177
+ },
178
+ };
179
+ }
180
+
181
+ /** A name no object has yet: stem-1, stem-2… */
182
+ function freshName(text: string, stem: string): string {
183
+ const all = allNames(dataOf(text));
184
+ let n = 1;
185
+ while (all.has(`${stem}-${n}`)) n++;
186
+ return `${stem}-${n}`;
187
+ }
188
+
189
+ return { describe, setCmd, pinsCmd, withPinsMoved, insertCmd, insertItemCmd, moveCmd, referencesTo, deleteCmd, renameCmd, duplicateCmd, renameKeyCmd, moveItemCmd, freshName };
190
+ }
191
+ export type Commands = ReturnType<typeof commandsFor>;
@@ -0,0 +1,73 @@
1
+ // Completion: keys the schema allows where the caret is, values (enums, true/false), references (the names the file
2
+ // declares, by the adapter's table), and the adapter's snippets for a new object. Pure: a text pane's provider turns
3
+ // these into its items.
4
+
5
+ import { EditorDoc, completionContext } from './doc.ts';
6
+ import { SchemaNav } from './schema-nav.ts';
7
+ import { toPointer, type Path } from './path.ts';
8
+ import type { CompleteAdapter, ObjectKindInfo } from './adapter.ts';
9
+
10
+ export interface Item {
11
+ label: string;
12
+ /** text to insert (a Monaco snippet when `snippet`) */
13
+ insert: string;
14
+ kind: 'key' | 'value' | 'ref' | 'snippet';
15
+ detail?: string;
16
+ /** Markdown */
17
+ doc?: string;
18
+ snippet?: boolean;
19
+ /** sorts before the rest */
20
+ preferred?: boolean;
21
+ }
22
+ export interface Completion { items: Item[]; start: number; path: Path; context: 'key' | 'value' | 'item' }
23
+
24
+ type J = Record<string, unknown>;
25
+
26
+ const data = (d: EditorDoc): J => { const v = d.data; return v && typeof v === 'object' && !Array.isArray(v) ? v as J : {}; };
27
+ const get = (o: unknown, path: Path): unknown => path.reduce<unknown>((x, k) => (x && typeof x === 'object' ? (x as J)[k as string] : undefined), o);
28
+
29
+ /** the names declared in a kind's section */
30
+ export function namesIn(d: EditorDoc, k: ObjectKindInfo): string[] {
31
+ const m = get(data(d), k.section);
32
+ return m && typeof m === 'object' && !Array.isArray(m) ? Object.keys(m as J).filter(k => !k.startsWith('x-')) : [];
33
+ }
34
+
35
+ export function complete(d: EditorDoc, offset: number, nav: SchemaNav, a: CompleteAdapter): Completion {
36
+ const c = completionContext(d, offset);
37
+ const items: Item[] = [];
38
+ const root = data(d);
39
+
40
+ if (c.kind === 'key') {
41
+ const here = get(root, c.path);
42
+ const present = here && typeof here === 'object' && !Array.isArray(here) ? here as J : {};
43
+ if (nav.isNameMap(c.path)) {
44
+ const ptr = toPointer(c.path);
45
+ for (const [k, s] of Object.entries(a.snippets)) if (k.split('#')[0] === ptr) items.push({ label: s.label, insert: s.body, kind: 'snippet', snippet: true, doc: s.doc, preferred: true });
46
+ } else {
47
+ // a map with some keys written offers only what fits
48
+ const indent = ' '.repeat(Math.max(0, c.start - (d.text.lastIndexOf('\n', c.start - 1) + 1)));
49
+ for (const k of nav.keys(c.path, present)) {
50
+ if (k.name in present) continue;
51
+ const after = c.flow || k.shape === 'scalar' ? ': ' : k.shape === 'list' ? ':\n' + indent + ' - ' : ':\n' + indent + ' ';
52
+ const insert = k.enumValues.length > 1 && k.shape === 'scalar' ? `${k.name}: \${1|${k.enumValues.join(',')}|}` : k.name + after;
53
+ items.push({ label: k.name, insert, snippet: insert.includes('${'), kind: 'key', doc: k.doc, detail: k.enumValues.length ? k.enumValues.join(' | ') : k.shape === 'map' ? 'map' : k.shape === 'list' ? 'list' : undefined });
54
+ }
55
+ }
56
+ } else {
57
+ const valuePath = c.kind === 'item' ? [...c.path, 0] : c.path;
58
+ const ptr = toPointer(valuePath);
59
+ const slot = a.slotAt(ptr);
60
+ if (slot) {
61
+ for (const s of slot.targets) { const k = a.kinds.find(x => x.kind === s); if (k) for (const n of namesIn(d, k)) {
62
+ items.push({ label: slot.write ? slot.write(n) : n, insert: slot.write ? slot.write(n) : n, kind: 'ref', detail: `${k.singular} · declared`, preferred: true });
63
+ } }
64
+ for (const e of slot.extra ?? []) items.push({ label: e, insert: /[{*]/.test(e) ? JSON.stringify(e) : e, kind: 'value', detail: a.extraDetail?.(e, root) });
65
+ }
66
+ for (const v of nav.values(valuePath)) if (!items.some(i => i.label === v)) items.push({ label: v, insert: v, kind: 'value' });
67
+ if (!items.length) {
68
+ const k = nav.keys(c.path.slice(0, -1)).find(x => x.name === String(c.path[c.path.length - 1]));
69
+ for (const e of k?.examples ?? []) if (typeof e === 'string') items.push({ label: e, insert: e, kind: 'value', detail: 'example' });
70
+ }
71
+ }
72
+ return { items, start: c.start, path: c.path, context: c.kind };
73
+ }
@@ -0,0 +1,207 @@
1
+ // The editor's document: the text (the truth) and a yaml Document parsed from it, with the way between a caret offset
2
+ // and a path. E2 adds the command layer on top; here it is read-only. Pure (no DOM).
3
+
4
+ import { parseDocument, isMap, isSeq, isPair, isScalar, isCollection, LineCounter, type Document, type Node as YNode, type Pair } from 'yaml';
5
+ import type { Path } from './path.ts';
6
+
7
+ export type Where = 'key' | 'value' | 'inside';
8
+ export interface At { path: Path; where: Where; node?: YNode }
9
+
10
+ export class EditorDoc {
11
+ readonly text: string;
12
+ readonly doc: Document.Parsed;
13
+ readonly lines: LineCounter;
14
+ constructor(text: string) {
15
+ this.text = text;
16
+ this.lines = new LineCounter();
17
+ this.doc = parseDocument(text, { keepSourceTokens: true, lineCounter: this.lines, prettyErrors: false, uniqueKeys: false });
18
+ }
19
+ get ok() { return this.doc.errors.length === 0; }
20
+ get data(): unknown { try { return this.doc.toJS(); } catch { return undefined; } }
21
+
22
+ /** 1-based line and column of an offset */
23
+ pos(offset: number) { return this.lines.linePos(offset); }
24
+ /** offset of a 1-based line and column */
25
+ offset(line: number, col: number) { return (this.lines.lineStarts[line - 1] ?? this.text.length) + col - 1; }
26
+
27
+ /** The source range of the node (or its key, or the whole pair) at a path. */
28
+ rangeOf(path: Path, part: 'value' | 'key' | 'pair' = 'value'): [number, number] | undefined {
29
+ let node: unknown = this.doc.contents;
30
+ let pair: Pair | undefined;
31
+ for (const seg of path) {
32
+ pair = undefined;
33
+ if (isMap(node)) {
34
+ const p = node.items.find(x => isPair(x) && isScalar(x.key) && String(x.key.value) === String(seg));
35
+ if (!p) return undefined;
36
+ pair = p as Pair;
37
+ node = p.value;
38
+ } else if (isSeq(node) && typeof seg === 'number') node = node.items[seg];
39
+ else return undefined;
40
+ }
41
+ if (part === 'key' && pair && isScalar(pair.key) && pair.key.range) return [pair.key.range[0], pair.key.range[1]];
42
+ const v = (node as YNode | null)?.range;
43
+ if (part === 'pair' && pair && isScalar(pair.key) && pair.key.range) return [pair.key.range[0], v ? v[1] : pair.key.range[1]];
44
+ if (v) return [v[0], v[1]];
45
+ if (pair && isScalar(pair.key) && pair.key.range) return [pair.key.range[0], pair.key.range[1]];
46
+ return undefined;
47
+ }
48
+
49
+ /** What is at a caret: the innermost key, value or collection whose source contains the offset. */
50
+ at(offset: number): At {
51
+ const walk = (node: unknown, path: Path): At | undefined => {
52
+ if (isMap(node)) {
53
+ for (const p of node.items) {
54
+ const k = p.key as YNode | null;
55
+ if (k?.range && offset >= k.range[0] && offset <= k.range[1]) return { path: [...path, keyOf(p)], where: 'key', node: k };
56
+ const v = p.value as YNode | null;
57
+ if (v?.range && offset >= v.range[0] && (isScalar(v) ? offset <= v.range[1] : offset < v.range[1])) {
58
+ return walk(v, [...path, keyOf(p)]) ?? { path: [...path, keyOf(p)], where: 'value', node: v };
59
+ }
60
+ // an empty value: "key: |" on the key's line
61
+ if (k?.range && (!v || !v.range || isScalar(v) && v.value === null) && offset > k.range[1] && !this.text.slice(k.range[1], offset).includes('\n')) {
62
+ return { path: [...path, keyOf(p)], where: 'value', node: v ?? undefined };
63
+ }
64
+ }
65
+ return node.range && offset >= node.range[0] && offset <= node.range[1] ? { path, where: 'inside', node } : undefined;
66
+ }
67
+ if (isSeq(node)) {
68
+ for (const [i, it] of node.items.entries()) {
69
+ const r = (it as YNode | null)?.range;
70
+ if (r && offset >= r[0] && (isScalar(it) ? offset <= r[1] : offset < r[1])) return walk(it, [...path, i]) ?? { path: [...path, i], where: 'value', node: it as YNode };
71
+ }
72
+ return node.range && offset >= node.range[0] && offset <= node.range[1] ? { path, where: 'inside', node } : undefined;
73
+ }
74
+ if (isScalar(node) && node.range && offset >= node.range[0] && offset <= node.range[1]) return { path, where: 'value', node };
75
+ return undefined;
76
+ };
77
+ return walk(this.doc.contents, []) ?? { path: [], where: 'inside' };
78
+ }
79
+
80
+ /** The node at a path. */
81
+ nodeAt(path: Path): YNode | undefined {
82
+ let node: unknown = this.doc.contents;
83
+ for (const seg of path) {
84
+ if (isMap(node)) node = node.items.find(x => isScalar(x.key) && String(x.key.value) === String(seg))?.value;
85
+ else if (isSeq(node) && typeof seg === 'number') node = node.items[seg];
86
+ else return undefined;
87
+ }
88
+ return (node ?? undefined) as YNode | undefined;
89
+ }
90
+
91
+ /** Every path in the document, with its range: for tests (rangeOf ∘ at is the identity) and the tree (E3). */
92
+ paths(): { path: Path; range: [number, number] }[] {
93
+ const out: { path: Path; range: [number, number] }[] = [];
94
+ const walk = (node: unknown, path: Path) => {
95
+ const r = (node as YNode | null)?.range;
96
+ if (r && path.length) out.push({ path, range: [r[0], r[1]] });
97
+ if (isMap(node)) for (const p of node.items) walk(p.value, [...path, keyOf(p)]);
98
+ else if (isSeq(node)) node.items.forEach((x, i) => walk(x, [...path, i]));
99
+ };
100
+ walk(this.doc.contents, []);
101
+ return out;
102
+ }
103
+ }
104
+
105
+ function keyOf(p: Pair): string { return isScalar(p.key) ? String(p.key.value) : String(p.key); }
106
+
107
+ export interface CompletionContext {
108
+ /** the path of the map a key is being typed in, or of the value being typed */
109
+ path: Path;
110
+ kind: 'key' | 'value' | 'item';
111
+ /** the word typed so far, and where it starts */
112
+ prefix: string;
113
+ start: number;
114
+ /** a flow collection ({ … } or [ … ]): keys are written inline */
115
+ flow: boolean;
116
+ }
117
+
118
+ /**
119
+ * What the caret is completing. In a block map the parent is found by indentation (an empty line has no node);
120
+ * after "key: " it is that key's value; in a "- " item or a [ … ] list, an item of that list; inside { … } a key of
121
+ * that map.
122
+ */
123
+ export function completionContext(d: EditorDoc, offset: number): CompletionContext {
124
+ const text = d.text;
125
+ const lineStart = text.lastIndexOf('\n', offset - 1) + 1;
126
+ const before = text.slice(lineStart, offset);
127
+ const word = /[A-Za-z0-9_.:\/{}*~$-]*$/.exec(before)![0].replace(/^[{[,]/, '');
128
+ const start = offset - word.length;
129
+ // inside a flow collection: use the collection at the caret
130
+ const flowNode = enclosingFlow(d, start);
131
+ if (flowNode) {
132
+ const inner = text.slice(flowNode.range[0], start);
133
+ // after "key: " inside the flow map: a value
134
+ const m = /([A-Za-z0-9_-]+)\s*:\s*$/.exec(inner.slice(Math.max(inner.lastIndexOf(','), inner.lastIndexOf('{')) + 1));
135
+ if (flowNode.kind === 'map' && m) return { path: [...flowNode.path, m[1]], kind: 'value', prefix: word, start, flow: true };
136
+ return { path: flowNode.path, kind: flowNode.kind === 'map' ? 'key' : 'item', prefix: word, start, flow: true };
137
+ }
138
+ // "key: |": a value
139
+ const kv = /^(\s*)(?:- )?([^\s:#][^:#]*?)\s*:\s+$/.exec(before.slice(0, before.length - word.length));
140
+ if (kv) {
141
+ const keyOffset = lineStart + before.indexOf(kv[2], kv[1].length);
142
+ const a = d.at(keyOffset);
143
+ if (a.where === 'key') return { path: a.path, kind: 'value', prefix: word, start, flow: false };
144
+ // a key the parser couldn't place yet: its parent by indentation
145
+ return { path: [...parentByIndent(d, lineStart, kv[1].length), kv[2]], kind: 'value', prefix: word, start, flow: false };
146
+ }
147
+ // "- |": an item of the list above
148
+ const item = /^(\s*)- $/.exec(before.slice(0, before.length - word.length));
149
+ if (item) {
150
+ const owner = parentByIndent(d, lineStart, item[1].length, true);
151
+ return { path: owner, kind: 'item', prefix: word, start, flow: false };
152
+ }
153
+ // a key on its own line: the map is the parent by indentation
154
+ const indent = /^\s*/.exec(before)![0].length;
155
+ return { path: parentByIndent(d, lineStart, indent), kind: 'key', prefix: word, start, flow: false };
156
+ }
157
+
158
+ /** The path of the block map (or list) that a line indented by `indent` belongs to. */
159
+ function parentByIndent(d: EditorDoc, lineStart: number, indent: number, forList = false): Path {
160
+ const text = d.text;
161
+ let end = lineStart - 1;
162
+ while (end > 0) {
163
+ const s = text.lastIndexOf('\n', end - 1) + 1;
164
+ const line = text.slice(s, end);
165
+ end = s - 1;
166
+ if (!line.trim() || /^\s*#/.test(line)) continue;
167
+ const ind = /^\s*/.exec(line)![0].length;
168
+ // a sibling key at the same indent: its parent is ours (for a list item, a "- " at the same indent is a sibling)
169
+ if (ind === indent && !forList) {
170
+ const keyAt = s + ind + (line.slice(ind).startsWith('- ') ? 2 : 0);
171
+ const a = d.at(keyAt);
172
+ if (a.where === 'key') return a.path.slice(0, -1);
173
+ if (line.slice(ind).startsWith('- ')) return a.path.slice(0, -1);
174
+ }
175
+ if (ind < indent || (forList && ind <= indent && /:\s*$/.test(line))) {
176
+ const m = /^(\s*)(- )?([^\s:#][^:#]*?)\s*:/.exec(line);
177
+ if (m) {
178
+ const a = d.at(s + m[1].length + (m[2] ? 2 : 0));
179
+ if (a.where === 'key') return a.path;
180
+ }
181
+ if (/^\s*- /.test(line)) {
182
+ const a = d.at(s + ind + 2);
183
+ // the item that holds us: its index is the last number in the path to its first key
184
+ let i = a.path.length - 1;
185
+ while (i >= 0 && typeof a.path[i] !== 'number') i--;
186
+ return i >= 0 ? a.path.slice(0, i + 1) : a.path;
187
+ }
188
+ if (ind < indent) return [];
189
+ }
190
+ if (ind === 0 && indent === 0) return [];
191
+ }
192
+ return [];
193
+ }
194
+
195
+ function enclosingFlow(d: EditorDoc, offset: number): { path: Path; kind: 'map' | 'list'; range: [number, number] } | undefined {
196
+ let best: { path: Path; kind: 'map' | 'list'; range: [number, number] } | undefined;
197
+ const walk = (node: unknown, path: Path) => {
198
+ if (!isCollection(node)) return;
199
+ const r = node.range;
200
+ const flow = (node as { flow?: boolean }).flow;
201
+ if (flow && r && offset > r[0] && offset < r[1]) best = { path, kind: isMap(node) ? 'map' : 'list', range: [r[0], r[1]] };
202
+ if (isMap(node)) for (const p of node.items) walk(p.value, [...path, keyOf(p)]);
203
+ else if (isSeq(node)) node.items.forEach((x, i) => walk(x, [...path, i]));
204
+ };
205
+ walk(d.doc.contents, []);
206
+ return best;
207
+ }