@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,684 @@
1
+ // The editor as a component: mountEditor(el, options, setup) puts the whole editor (the text, the tree, the canvas,
2
+ // the properties, the problems, the menus) inside `el` and returns a handle. It does no I/O of its own:
3
+ // - the text comes in as options.text (and setText); saving goes out through options.onSave(text);
4
+ // - problems, and a host's deeper check shown beside them, come from the kit's check(text) (setup.kit);
5
+ // - preferences (panel sizes, the view) are kept only if options.storage is given.
6
+ // Everything it makes lives under one root element inside `el` (its class the setup's words name): its styles are
7
+ // scoped to that class, menus and dialogs open inside it, and keys are bound on it (none while the focus is elsewhere).
8
+ // dispose() removes the root, its listeners, timers, Monaco's editor and model, and any Worker it started. The domain gives the
9
+ // rest (EditorSetup): the kits, the shell's words, the features, its canvas options and its part.
10
+
11
+ import { problemRange } from '../providers.ts';
12
+ import { later, isTyping } from './later.ts';
13
+ import type { MonacoPane } from './text.ts';
14
+ import type { PaneOpts } from './pane.ts';
15
+ import type { Clip } from './clip.ts';
16
+ import { treeView, type TreeKit } from './tree.ts';
17
+ import { keySheet, keymapWith, type KeyGroup } from './keys.ts';
18
+ import { closeMenu } from './menu.ts';
19
+ import { setLayer } from './layer.ts';
20
+ import type { Path } from '../path.ts';
21
+ import { fromPointer, toPointer } from '../path.ts';
22
+ import { h } from './icons.ts';
23
+ import { EditorModel } from '../model.ts';
24
+ import type { Problem } from '../validate.ts';
25
+ import type { MountKit } from './mount-kit.ts';
26
+ import type { PartCtx, EditorPart } from './part.ts';
27
+ import { PREF } from '../storage-keys.ts';
28
+
29
+ export type Theme = 'light' | 'dark' | 'system';
30
+ export type SaveResult = { ok: true } | { conflict: true };
31
+ /** what a host adds to the shell */
32
+ export interface HostHooks {
33
+ titleStart?: HTMLElement[];
34
+ sideTabs?: { id: string; label: string; icon: string; panel: HTMLElement }[];
35
+ keys?(e: KeyboardEvent): boolean;
36
+ keymap?: [string, string][];
37
+ themeControls?: boolean;
38
+ onOpen?(rel: string): void;
39
+ onSaveAs?(): void;
40
+ onConflict?(): void;
41
+ /** the setup's brand mark in the title bar */
42
+ brand?: boolean;
43
+ }
44
+ export interface EditorOptions {
45
+ text?: string;
46
+ readOnly?: boolean;
47
+ theme?: Theme;
48
+ storage?: { get(k: string): string | null; set(k: string, v: string | null): void };
49
+ watch?: boolean;
50
+ onSave?(text: string): Promise<SaveResult>;
51
+ onDirtyChange?(dirty: boolean): void;
52
+ host?: HostHooks;
53
+ }
54
+ /** the shell's words (markup is the setup's constant, never the file's) */
55
+ export interface ShellWords {
56
+ rootClass: string;
57
+ /** the brand mark's markup */
58
+ brand: string;
59
+ sideLabel: string; canvasLabel: string; problemsLabel: string; bottomTabsLabel: string; extraTab: string;
60
+ /** more panels' slots under the work area (markup) */
61
+ slots: string;
62
+ }
63
+ /** the views' features, as the shell uses them (a feature not given is never loaded) */
64
+ export interface ShellFeatures {
65
+ text?: { textPane(el: HTMLElement, doc: EditorModel, o: Omit<PaneOpts, 'services'>): MonacoPane };
66
+ canvas?: { canvasView(host: HTMLElement, doc: EditorModel, o: never): ShellCanvas };
67
+ edit?: { propsPanel(body: HTMLElement, doc: EditorModel, o: never): { paint(): void; dispose(): void }; clipboard(doc: EditorModel, note: (t: string, tone?: 'info' | 'warn' | 'bad') => void): Clip };
68
+ /** the host's deeper check, as a panel beside Problems */
69
+ plan?: { planPanel(el: HTMLElement, o: { has(name: string): boolean; select(name: string): boolean }): { paint(extra: unknown, has: boolean): void } };
70
+ }
71
+ /** what the shell calls on a canvas */
72
+ export interface ShellCanvas { render(model: unknown, data: unknown): Promise<void>; setTheme(t: 'light' | 'dark'): void; fit(): void; focus(): void; dispose(): void }
73
+ /** what the domain gives the mounted editor */
74
+ export interface EditorSetup<R, X, A extends object> {
75
+ kit: MountKit<R, X>;
76
+ tree: TreeKit;
77
+ words: ShellWords;
78
+ features: ShellFeatures & Record<string, unknown>;
79
+ /** every feature's name, and those that can be added to a mounted editor */
80
+ names: readonly string[];
81
+ late: readonly string[];
82
+ load?: (names: readonly string[]) => Promise<{ name: string }[]>;
83
+ /** the host's deeper check is given (its panel paints "none" otherwise) */
84
+ hasExtra: boolean;
85
+ /** the domain's own canvas options (its layer's), given its part's calls */
86
+ canvasOpts?(part: () => A): Record<string, unknown>;
87
+ part?(ctx: PartCtx, deps: { canvas: () => ShellCanvas; objectPath(name: string): string | undefined }): EditorPart<A>;
88
+ /** what an absent canvas answers, beyond nothing */
89
+ noCanvas?: Record<string, unknown>;
90
+ /** more of the internal handle */
91
+ internal?: Record<string, unknown>;
92
+ /** the icons the views use (<svg> markup of <symbol id="se-i-NAME">s; the build makes it from the domain's icon names) */
93
+ sprite?: string;
94
+ }
95
+
96
+ const shellHtml = (W: ShellWords) => `
97
+ <header class="titlebar">
98
+ <button id="se-tree" class="btn sm quiet icon-only" type="button" aria-expanded="false" aria-controls="se-side" aria-label="Show the outline" title="The outline"><svg class="icon" aria-hidden="true"><use href="#se-i-list-tree"></use></svg></button>
99
+ <span class="brand" data-se="brand" hidden>${W.brand}</span>
100
+ <span data-se="title-start" class="title-start"></span>
101
+ <span class="pill ro" id="se-ro" hidden>Read-only</span>
102
+ <button id="se-save" class="btn sm primary" type="button" disabled title="Save (⌘S)">Save</button>
103
+ <div class="btn-group" role="group" aria-label="History">
104
+ <button id="se-undo" class="btn sm" type="button" disabled title="Nothing to undo"><svg class="icon" aria-hidden="true"><use href="#se-i-rotate-ccw"></use></svg>Undo</button>
105
+ <button id="se-redo" class="btn sm" type="button" disabled title="Nothing to redo"><svg class="icon flip" aria-hidden="true"><use href="#se-i-rotate-ccw"></use></svg>Redo</button>
106
+ </div>
107
+ <span class="spacer"></span>
108
+ <div id="se-views" class="segmented" role="group" aria-label="Show">
109
+ <button class="seg" type="button" data-v="canvas">Canvas</button>
110
+ <button class="seg" type="button" data-v="both">Both</button>
111
+ <button class="seg" type="button" data-v="text">Text</button>
112
+ </div>
113
+ <div id="se-theme" class="segmented" role="group" aria-label="Theme" hidden>
114
+ <button class="seg" type="button" data-v="system">System</button>
115
+ <button class="seg" type="button" data-v="light">Light</button>
116
+ <button class="seg" type="button" data-v="dark">Dark</button>
117
+ </div>
118
+ <button id="se-density" class="btn sm quiet" type="button" aria-pressed="false" title="Compact density" hidden>Compact</button>
119
+ <button id="se-keys" class="btn sm quiet" type="button" title="Keyboard (?)" aria-haspopup="dialog">Keys</button>
120
+ <button id="se-panel" class="btn sm quiet icon-only" type="button" aria-pressed="true" aria-label="Show the properties panel" title="The properties panel"><svg class="icon" aria-hidden="true"><use href="#se-i-panel-right"></use></svg></button>
121
+ </header>
122
+ <div class="body">
123
+ <div id="se-scrim" class="scrim" hidden></div>
124
+ <nav class="side" id="se-side" aria-label="${W.sideLabel}">
125
+ <div class="side-tabs segmented" role="tablist" aria-label="Sidebar" hidden>
126
+ <button class="seg" type="button" role="tab" id="se-tab-outline" aria-controls="se-outline" aria-selected="true"><svg class="icon" aria-hidden="true"><use href="#se-i-list-tree"></use></svg>Outline</button>
127
+ </div>
128
+ <div id="se-outline" role="tabpanel" aria-labelledby="se-tab-outline"></div>
129
+ </nav>
130
+ <div id="se-side-grip" class="vgrip" role="separator" aria-orientation="vertical" aria-label="Resize the sidebar" tabindex="0"></div>
131
+ <main class="center">
132
+ <div id="se-filebar" class="callout warn banner filebar" role="alert" hidden><svg class="icon" aria-hidden="true"><use href="#se-i-triangle-alert"></use></svg><div class="c-body"></div><div class="c-acts"></div></div>
133
+ <div class="work">
134
+ <div id="se-canvas" aria-label="${W.canvasLabel}"></div>
135
+ <div id="se-work-grip" class="vgrip" role="separator" aria-orientation="vertical" aria-label="Resize the canvas and the text" tabindex="0"></div>
136
+ <div id="se-code" aria-label="The file, as text"></div>
137
+ </div>
138
+ ${W.slots} <div id="se-grip" role="separator" aria-orientation="horizontal" aria-label="Resize the problems list" tabindex="0"></div>
139
+ <section id="se-problems" aria-label="${W.problemsLabel}">
140
+ <div id="se-problems-head" class="problems-head">
141
+ <button id="se-problems-toggle" type="button" class="problems-toggle" aria-expanded="false" aria-controls="se-problems-list"><svg class="icon" aria-hidden="true"><use href="#se-i-chevron-right"></use></svg><span id="se-problems-label">No problems</span></button>
142
+ <span class="spacer"></span>
143
+ <span id="se-plan-label" class="plan-label"></span>
144
+ <div class="segmented bottom-tabs" role="tablist" aria-label="${W.bottomTabsLabel}">
145
+ <button class="seg" type="button" role="tab" id="se-tab-problems" aria-selected="true" aria-controls="se-problems-list">Problems</button>
146
+ <button class="seg" type="button" role="tab" id="se-tab-plan" aria-selected="false" aria-controls="se-plan">${W.extraTab}</button>
147
+ </div>
148
+ </div>
149
+ <div id="se-problems-list" role="tabpanel" aria-labelledby="se-tab-problems"></div>
150
+ <div id="se-plan" class="plan" role="tabpanel" aria-labelledby="se-tab-plan" hidden></div>
151
+ </section>
152
+ <div id="se-note" class="callout compact" role="status" hidden><span class="c-body"></span></div>
153
+ </main>
154
+ <div id="se-right-grip" class="vgrip" role="separator" aria-orientation="vertical" aria-label="Resize the selection panel" tabindex="0"></div>
155
+ <aside id="se-right" class="right" aria-label="Properties">
156
+ <div class="side-head">Properties</div>
157
+ <div id="se-sel-body" class="sel-body"></div>
158
+ </aside>
159
+ </div>
160
+ <footer class="status">
161
+ <span id="se-st-problems" class="ok">0 ✕ 0 ⚠</span>
162
+ <span id="se-st-path" class="path"></span>
163
+ <span class="spacer"></span>
164
+ <span id="se-st-sel"></span>
165
+ <span id="se-st-hint" class="hint-mode" title="The canvas's navigation: change it in the canvas's toolbar"></span>
166
+ <span id="se-st-zoom" title="The canvas's zoom"></span>
167
+ <span id="se-st-pos"></span>
168
+ <span id="se-st-kind"></span>
169
+ <span id="se-announce" class="sr-only" aria-live="polite"></span>
170
+ </footer>`;
171
+
172
+ /** The editor's state, for the standalone page and the tests (not part of the component's API). */
173
+ export interface EditorState<R = unknown, X = unknown> {
174
+ problems: Problem[];
175
+ lifetimes: Map<string, string>;
176
+ read: R | undefined;
177
+ plan: X | undefined;
178
+ view: 'canvas' | 'both' | 'text';
179
+ theme: Theme;
180
+ density: 'comfortable' | 'compact';
181
+ readOnly: boolean;
182
+ problemsOpen: boolean;
183
+ problemsSeen: number;
184
+ checks: number;
185
+ }
186
+ export interface Editor {
187
+ getText(): string; setText(text: string): void; setReadOnly(ro: boolean): void; setTheme(t: Theme): void;
188
+ addFeatures(names: readonly string[]): Promise<void>; fit(): void; dispose(): void;
189
+ }
190
+
191
+ /** P3: the editor with the features given (the core alone: the shell, the model, the reader and the tree; read-only
192
+ * unless edit is given). */
193
+ export function mountEditor<R, X, A extends object = object>(el: HTMLElement, opts: EditorOptions, S: EditorSetup<R, X, A>): Editor & { internal: Record<string, unknown> } {
194
+ // v0.4.1: features can be added after mount (addFeatures): F grows, never shrinks
195
+ const F = S.features;
196
+ const K = S.kit, W = S.words, load = S.load;
197
+ // v0.4.1: watch: the canvas and Live, for this mount only (storage is read for the rest, but view and live aren't written)
198
+ const watch = !!opts.watch;
199
+ const hooks = opts.host ?? {};
200
+ const store = {
201
+ get: (k: string) => { try { return opts.storage?.get(k) ?? null; } catch { return null; } },
202
+ set: (k: string, v: string | null) => { try { opts.storage?.set(k, v); } catch { /* not kept */ } },
203
+ };
204
+ // ---------- the root: everything the editor makes is inside it ----------
205
+ const root = h('div', { class: W.rootClass, 'data-view': 'both' });
206
+ const sprite = document.createElement('template');
207
+ sprite.innerHTML = S.sprite ?? ''; // the setup's icon sprite: constant, no file data
208
+ const shell = document.createElement('template');
209
+ shell.innerHTML = shellHtml(W); // constant markup; every value goes in as text later
210
+ root.append(sprite.content, shell.content);
211
+ el.append(root);
212
+ setLayer(root);
213
+ const $ = <T extends HTMLElement>(id: string) => root.querySelector(`#se-${id}`) as T;
214
+ const cleanups: (() => void)[] = [];
215
+ const on = <K extends keyof HTMLElementEventMap>(t: HTMLElement | Window | MediaQueryList, ev: K | 'change', fn: (e: never) => void, o?: AddEventListenerOptions) => {
216
+ t.addEventListener(ev, fn as EventListener, o);
217
+ cleanups.push(() => t.removeEventListener(ev, fn as EventListener, o));
218
+ };
219
+ on(root, 'focusin', () => setLayer(root));
220
+ on(root, 'pointerdown', () => setLayer(root));
221
+
222
+ const state: EditorState<R, X> = {
223
+ problems: [], lifetimes: new Map(), read: undefined, plan: undefined,
224
+ view: watch ? 'canvas' : (store.get(PREF.view) ?? 'both') as EditorState['view'],
225
+ theme: opts.theme ?? (hooks.themeControls ? (store.get('theme') as Theme | null) ?? 'system' : 'system'),
226
+ density: hooks.themeControls ? ((store.get('density') ?? 'comfortable') as EditorState['density']) : 'comfortable',
227
+ readOnly: !!opts.readOnly || !F.edit, problemsOpen: false, problemsSeen: 0, checks: 0,
228
+ };
229
+ if (hooks.brand) (root.querySelector('[data-se="brand"]') as HTMLElement).hidden = false;
230
+ for (const x of hooks.titleStart ?? []) root.querySelector('[data-se="title-start"]')!.append(x);
231
+ $('save').hidden = !opts.onSave;
232
+ $('theme').hidden = $('density').hidden = !hooks.themeControls;
233
+
234
+ // ---------- the one model: the text, its Document, the selection and the undo stack ----------
235
+ const doc = new EditorModel();
236
+ // read-only: nothing changes the text (Monaco is read-only too); a view that tries says so
237
+ for (const m of ['apply', 'undo', 'redo'] as const) {
238
+ const f = (doc[m] as (...a: unknown[]) => boolean).bind(doc);
239
+ (doc as unknown as Record<string, unknown>)[m] = (...a: unknown[]) => { if (state.readOnly) { note('This file is read-only here', 'warn'); return false; } return f(...a); };
240
+ }
241
+
242
+ // ---------- the text: Monaco, bound to the one model ----------
243
+ const makePane = (): MonacoPane => (F.text ? F.text.textPane($('code'), doc, { onOpen: rel => hooks.onOpen?.(rel), onSave: () => { void save(); }, onSaveAs: () => hooks.onSaveAs?.() }) : noText());
244
+ let pane: MonacoPane = makePane();
245
+ const isTextTarget = (t: EventTarget | null) => !!(t as HTMLElement | null)?.closest?.('.monaco-editor, #se-code');
246
+
247
+ // ---------- the clipboard, the tree, the properties and the canvas ----------
248
+ const clip = F.edit ? F.edit.clipboard(doc, (t, tone) => note(t, tone)) : { items: () => [], attach: () => () => undefined };
249
+ const tree = treeView($('outline'), doc, {
250
+ kit: S.tree, clipItems: () => clip.items(), nav: () => K.nav(doc.text), problems: () => state.problems, role: () => K.role(doc.text),
251
+ lifetimes: () => state.lifetimes, showInText: path => showInText(path), note: (t, tone) => note(t, tone),
252
+ });
253
+ const props = !F.edit ? { paint: () => undefined, dispose: () => undefined } : F.edit.propsPanel($('sel-body'), doc, {
254
+ nav: () => K.nav(doc.text), problems: () => state.problems, read: () => state.read, note: (t: string, tone?: 'info' | 'warn' | 'bad') => note(t, tone), showInText: (p: Path) => showInText(p),
255
+ now: (ptr: string) => part?.now?.(ptr),
256
+ } as never);
257
+ const paintSelection = () => { $('st-sel').textContent = doc.selection.length > 1 ? `${doc.selection.length} selected` : ''; props.paint(); };
258
+ doc.onSelect(paintSelection);
259
+ const canvas: ShellCanvas = !F.canvas ? noCanvas(S.noCanvas) : F.canvas.canvasView($('canvas'), doc, {
260
+ problems: () => state.problems, note: (t: string, tone?: 'info' | 'warn' | 'bad') => note(t, tone), showInText: (p: Path) => showInText(p),
261
+ showInTree: (p: Path) => { $('tab-outline').click(); doc.select([p], 'menu'); tree.focus(); },
262
+ onZoom: (pct: number) => { $('st-zoom').textContent = `${pct}%`; }, onHint: (t: string) => { $('st-hint').textContent = t; },
263
+ clipItems: () => clip.items(), store,
264
+ ...S.canvasOpts?.(() => part!.api),
265
+ } as never);
266
+ cleanups.push(clip.attach(root, t => !!(t as HTMLElement | null)?.closest?.('#se-outline, .canvas, #se-sel-body')));
267
+ function showInText(path: Path) { if (state.view === 'canvas') setView('both', true); pane.goTo(path); }
268
+
269
+ // ---------- the sidebar's tabs (the standalone page adds Files) ----------
270
+ const tabs = root.querySelector('.side-tabs') as HTMLElement;
271
+ for (const t of hooks.sideTabs ?? []) {
272
+ const b = h('button', { class: 'seg', type: 'button', role: 'tab', id: `se-tab-${t.id}`, 'aria-controls': t.panel.id, 'aria-selected': 'false' });
273
+ const ic = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); ic.setAttribute('class', 'icon'); ic.setAttribute('aria-hidden', 'true');
274
+ const use = document.createElementNS('http://www.w3.org/2000/svg', 'use'); use.setAttribute('href', `#se-i-${t.icon}`); ic.append(use);
275
+ b.append(ic, t.label);
276
+ tabs.append(b);
277
+ t.panel.setAttribute('role', 'tabpanel'); t.panel.setAttribute('aria-labelledby', b.id); t.panel.hidden = true;
278
+ root.querySelector('nav.side')!.append(t.panel);
279
+ }
280
+ tabs.hidden = !(hooks.sideTabs ?? []).length;
281
+ for (const b of tabs.querySelectorAll<HTMLButtonElement>('[role="tab"]')) {
282
+ on(b, 'click', () => {
283
+ for (const x of tabs.querySelectorAll<HTMLButtonElement>('[role="tab"]')) {
284
+ const isOn = x === b;
285
+ x.setAttribute('aria-selected', String(isOn)); x.classList.toggle('active', isOn);
286
+ (root.querySelector(`#${x.getAttribute('aria-controls')}`) as HTMLElement).hidden = !isOn;
287
+ }
288
+ store.set('tab', b.id);
289
+ });
290
+ }
291
+ if (store.get('tab') && store.get('tab') !== 'se-tab-outline' && root.querySelector(`#${store.get('tab')}`)) (root.querySelector(`#${store.get('tab')}`) as HTMLElement).click();
292
+ else $('tab-outline').classList.add('active');
293
+
294
+ // ---------- canvas, text, or both ----------
295
+ // the view asked for (the viewer's, kept in storage as PREF.view), and the one shown: only the views whose features
296
+ // are here (P3). A view forced by a missing feature isn't kept, so adding the feature later shows the one asked for.
297
+ let wanted: EditorState['view'] = state.view;
298
+ function setView(v: EditorState['view'], chosen = false) {
299
+ if (chosen) { wanted = v; if (!watch) store.set(PREF.view, v); }
300
+ if (!F.text) v = 'canvas'; else if (!F.canvas) v = 'text';
301
+ state.view = v;
302
+ root.dataset.view = v;
303
+ for (const b of root.querySelectorAll<HTMLButtonElement>('#se-views .seg')) b.setAttribute('aria-pressed', String(b.dataset.v === v));
304
+ pane.editor.layout();
305
+ }
306
+ for (const b of root.querySelectorAll<HTMLButtonElement>('#se-views .seg')) on(b, 'click', () => setView(b.dataset.v as EditorState['view'], true));
307
+
308
+ // ---------- v0.4.1: narrow (the root ≤ 760 px wide): the outline is a drawer over the canvas, opened by its button ----------
309
+ const setTree = (open: boolean) => {
310
+ root.classList.toggle('side-open', open);
311
+ $('tree').setAttribute('aria-expanded', String(open));
312
+ $('tree').setAttribute('aria-label', open ? 'Hide the outline' : 'Show the outline');
313
+ $('scrim').hidden = !open;
314
+ };
315
+ on($('tree'), 'click', () => setTree(!root.classList.contains('side-open')));
316
+ on($('scrim'), 'click', () => setTree(false));
317
+ on(root, 'keydown', (e: KeyboardEvent) => { if (e.key === 'Escape' && root.classList.contains('side-open') && !(e.target as HTMLElement).closest?.('dialog, .menu')) { setTree(false); $('tree').focus(); } });
318
+ {
319
+ // the drawer is for narrow roots only: widening closes it
320
+ const ro = new ResizeObserver(() => { if (root.classList.contains('side-open') && root.clientWidth > 760) setTree(false); });
321
+ ro.observe(root); cleanups.push(() => ro.disconnect());
322
+ }
323
+
324
+ // ---------- panels: resizable sidebar, canvas and properties; the properties can be hidden ----------
325
+ function grip(id: string, varName: string, side: 'left' | 'right', min: number, max: number) {
326
+ const g = $(id);
327
+ const saved = store.get(varName);
328
+ if (saved) root.style.setProperty(varName, `${saved}px`);
329
+ const size = () => parseFloat(getComputedStyle(root).getPropertyValue(varName)) || (side === 'left' ? 260 : 280);
330
+ const set = (w: number) => { const v = Math.round(Math.min(max, Math.max(min, w))); root.style.setProperty(varName, `${v}px`); store.set(varName, String(v)); };
331
+ on(g, 'pointerdown', (e: PointerEvent) => {
332
+ g.setPointerCapture(e.pointerId);
333
+ const x0 = e.clientX, w0 = size();
334
+ const mv = (ev: PointerEvent) => set(side === 'left' ? w0 + ev.clientX - x0 : w0 - (ev.clientX - x0));
335
+ const up = () => { g.removeEventListener('pointermove', mv); g.removeEventListener('pointerup', up); };
336
+ g.addEventListener('pointermove', mv); g.addEventListener('pointerup', up);
337
+ });
338
+ on(g, 'keydown', (e: KeyboardEvent) => {
339
+ const d = e.key === 'ArrowLeft' ? -16 : e.key === 'ArrowRight' ? 16 : 0;
340
+ if (d) { set(size() + (side === 'left' ? d : -d)); e.preventDefault(); }
341
+ });
342
+ }
343
+ grip('side-grip', '--side-w', 'left', 180, 520);
344
+ grip('right-grip', '--right-w', 'right', 200, 520);
345
+ grip('work-grip', '--canvas-w', 'left', 240, 1600);
346
+ const setPanel = (isOn: boolean) => { root.classList.toggle('no-right', !isOn); $('panel').setAttribute('aria-pressed', String(isOn)); store.set('panel', isOn ? '1' : '0'); };
347
+ setPanel(store.get('panel') !== '0');
348
+ on($('panel'), 'click', () => setPanel(root.classList.contains('no-right')));
349
+
350
+ // ---------- theme: the host's tokens, on the light or dark side (color-scheme on the root) ----------
351
+ const media = matchMedia('(prefers-color-scheme: dark)');
352
+ const isDark = () => state.theme === 'dark' || (state.theme === 'system' && media.matches);
353
+ function applyTheme() {
354
+ root.style.colorScheme = state.theme === 'system' ? 'light dark' : state.theme;
355
+ if (state.theme === 'system') delete root.dataset.theme; else root.dataset.theme = state.theme;
356
+ if (state.density === 'compact') root.dataset.density = 'compact'; else delete root.dataset.density;
357
+ pane.setTheme(isDark());
358
+ canvas.setTheme(isDark() ? 'dark' : 'light');
359
+ for (const b of root.querySelectorAll<HTMLButtonElement>('#se-theme .seg')) b.setAttribute('aria-pressed', String(b.dataset.v === state.theme));
360
+ $('density').setAttribute('aria-pressed', String(state.density === 'compact'));
361
+ }
362
+ on(media, 'change', () => { if (state.theme === 'system') applyTheme(); });
363
+ const setTheme = (t: Theme) => { state.theme = t; if (hooks.themeControls) store.set('theme', t); applyTheme(); };
364
+ const setDensity = (d: EditorState['density']) => { state.density = d; store.set('density', d); applyTheme(); };
365
+ for (const b of root.querySelectorAll<HTMLButtonElement>('#se-theme .seg')) on(b, 'click', () => setTheme(b.dataset.v as Theme));
366
+ on($('density'), 'click', () => setDensity(state.density === 'compact' ? 'comfortable' : 'compact'));
367
+
368
+ // ---------- a note, and the banner (changed elsewhere; the standalone page's file bar) ----------
369
+ let noteTimer = 0;
370
+ function note(text: string, tone: 'info' | 'warn' | 'bad' = 'info') {
371
+ const n = $('note');
372
+ n.className = `callout compact ${tone === 'info' ? '' : tone}`;
373
+ n.querySelector('.c-body')!.textContent = text;
374
+ n.hidden = false;
375
+ clearTimeout(noteTimer);
376
+ noteTimer = window.setTimeout(() => { n.hidden = true; }, 6000);
377
+ }
378
+ function showBanner(body: Node[], actions: { label: string; primary?: boolean; run(): void }[]) {
379
+ const bar = $('filebar');
380
+ bar.querySelector('.c-body')!.replaceChildren(...body);
381
+ const acts = bar.querySelector('.c-acts')!;
382
+ acts.replaceChildren(...actions.map(a => { const b = h('button', { type: 'button', class: `btn sm${a.primary ? ' primary' : ''}` }, a.label); b.addEventListener('click', a.run); return b; }));
383
+ bar.hidden = false;
384
+ }
385
+ const hideBanner = () => { $('filebar').hidden = true; };
386
+
387
+ // ---------- saving: the host's onSave; a conflict is shown, never resolved here ----------
388
+ const dirty = () => doc.dirty;
389
+ let wasDirty = false;
390
+ function paintTitle() {
391
+ ($('save') as HTMLButtonElement).disabled = !dirty() || state.readOnly;
392
+ if (dirty() !== wasDirty) { wasDirty = dirty(); opts.onDirtyChange?.(wasDirty); }
393
+ }
394
+ async function save(): Promise<boolean> {
395
+ if (!opts.onSave || state.readOnly) return false;
396
+ if (!dirty()) return true;
397
+ const text = doc.text;
398
+ doc.seal();
399
+ let r: SaveResult;
400
+ try { r = await opts.onSave(text); } catch (e) { note(`Not saved: ${(e as Error).message ?? e}`, 'bad'); return false; }
401
+ if ('conflict' in r) {
402
+ if (hooks.onConflict) { hooks.onConflict(); return false; }
403
+ showBanner([h('span', { class: 'c-title' }, 'Changed elsewhere.'), h('span', null, ' This file changed outside the editor since it was loaded, so it wasn\'t saved.')],
404
+ [{ label: 'Dismiss', run: hideBanner }]);
405
+ return false;
406
+ }
407
+ if (doc.text === text) doc.markClean(); // an edit made while saving stays unsaved
408
+ hideBanner();
409
+ paintTitle();
410
+ return true;
411
+ }
412
+ on($('save'), 'click', () => { void save(); });
413
+
414
+ // ---------- the keys: bound on the root, so nothing answers while the focus is outside the editor ----------
415
+ const keymap: KeyGroup[] = hooks.keymap ? keymapWith(K.keymap, hooks.keymap) : K.keymap;
416
+ const sheet = () => keySheet(keymap);
417
+ on($('keys'), 'click', () => sheet());
418
+ on(root, 'keydown', (e: KeyboardEvent) => {
419
+ const t = e.target as HTMLElement;
420
+ if (e.key === '?' && !e.metaKey && !e.ctrlKey && !e.altKey) {
421
+ if (t.closest?.('input, textarea, select, .monaco-editor, #se-code, [contenteditable], dialog')) return;
422
+ e.preventDefault(); sheet(); return;
423
+ }
424
+ if (hooks.keys?.(e)) return;
425
+ if (!(e.metaKey || e.ctrlKey) || e.altKey || isTextTarget(e.target)) return; // the text has its own bindings
426
+ const k = e.key.toLowerCase();
427
+ if (k === 's' && !e.shiftKey) { e.preventDefault(); void save(); }
428
+ else if (k === 'z' && !e.shiftKey) { doc.undo(); e.preventDefault(); }
429
+ else if ((k === 'z' && e.shiftKey) || k === 'y') { doc.redo(); e.preventDefault(); }
430
+ });
431
+
432
+ // ---------- E10: the plan panel, beside Problems (the same plan, rendered) ----------
433
+ const resourcePath = (name: string) => K.objectPath(name, state.read);
434
+ const makePlan = () => (!F.plan ? { paint: () => undefined } : F.plan.planPanel($('plan'), {
435
+ has: name => !!resourcePath(name),
436
+ select: name => { const p = resourcePath(name); if (!p) return false; doc.select([fromPointer(p)], 'menu'); return true; },
437
+ }));
438
+ let planUI: { paint(extra: unknown, has: boolean): void } = makePlan();
439
+ let bottomTab: 'problems' | 'plan' = (store.get('bottom-tab') as 'problems' | 'plan' | null) ?? 'problems';
440
+ function setBottomTab(t: 'problems' | 'plan') {
441
+ bottomTab = t; store.set('bottom-tab', t);
442
+ for (const b of root.querySelectorAll<HTMLButtonElement>('.bottom-tabs [role="tab"]')) { const isOn = b.id === `se-tab-${t}`; b.setAttribute('aria-selected', String(isOn)); b.classList.toggle('active', isOn); }
443
+ $('problems-list').hidden = t !== 'problems';
444
+ $('plan').hidden = t !== 'plan';
445
+ $('problems-toggle').setAttribute('aria-controls', t === 'plan' ? 'se-plan' : 'se-problems-list');
446
+ }
447
+ for (const b of root.querySelectorAll<HTMLButtonElement>('.bottom-tabs [role="tab"]')) on(b, 'click', () => { setBottomTab(b.id === 'se-tab-plan' ? 'plan' : 'problems'); setProblemsOpen(true, false); });
448
+ function paintPlan() {
449
+ planUI.paint(state.plan, S.hasExtra);
450
+ const L = K.extraLabel(state.plan);
451
+ $('plan-label').textContent = L.text;
452
+ $('plan-label').className = `plan-label ${L.cls}`;
453
+ }
454
+
455
+ // ---------- problems and the plan: from the host's plan(text); the reader only draws ----------
456
+ let timer = 0;
457
+ let disposed = false;
458
+ async function check() {
459
+ clearTimeout(timer);
460
+ const text = doc.text, version = doc.version;
461
+ const r = await K.check(text, state.plan, note);
462
+ if (disposed || doc.version !== version) return;
463
+ state.plan = r.extra;
464
+ state.problems = r.problems;
465
+ state.read = r.read;
466
+ state.lifetimes = r.tags as EditorState['lifetimes'];
467
+ state.checks++;
468
+ pane.setProblems(state.problems.filter(p => !p.file));
469
+ paintProblems();
470
+ paintPlan();
471
+ tree.paint();
472
+ paintSelection();
473
+ void canvas.render(r.model, r.data);
474
+ }
475
+ cleanups.push(doc.on(() => { paintTitle(); paintHistory(); clearTimeout(timer); timer = window.setTimeout(() => { void check(); }, 150); }));
476
+
477
+ // ---------- undo and redo: one stack for every view ----------
478
+ function paintHistory() {
479
+ const u = $('undo') as HTMLButtonElement, r = $('redo') as HTMLButtonElement;
480
+ u.disabled = !doc.canUndo || state.readOnly; r.disabled = !doc.canRedo || state.readOnly;
481
+ u.title = doc.canUndo ? `Undo ${doc.undoLabel} (⌘Z)` : 'Nothing to undo';
482
+ r.title = doc.canRedo ? `Redo ${doc.redoLabel} (⇧⌘Z)` : 'Nothing to redo';
483
+ u.setAttribute('aria-label', u.title); r.setAttribute('aria-label', r.title);
484
+ }
485
+ on($('undo'), 'click', () => { doc.undo(); pane.focus(); });
486
+ on($('redo'), 'click', () => { doc.redo(); pane.focus(); });
487
+
488
+ function setProblemsOpen(open: boolean, byHand: boolean) {
489
+ if (byHand && !state.problems.length && !part?.attention?.()?.count && bottomTab === 'problems') open = false;
490
+ state.problemsOpen = open;
491
+ $('problems').classList.toggle('collapsed', !open);
492
+ $('problems-toggle').setAttribute('aria-expanded', String(open));
493
+ pane.editor.layout();
494
+ }
495
+ on($('problems-toggle'), 'click', () => setProblemsOpen(!state.problemsOpen, true));
496
+ /** the live part (Live, Simulation, the runs, what waits for a person): read by paintProblems, which can run before
497
+ * the part is set up */
498
+ let part: EditorPart<A> | undefined;
499
+ function paintProblems() {
500
+ const list = $('problems-list');
501
+ list.replaceChildren();
502
+ const errs = state.problems.filter(p => p.severity === 'error').length;
503
+ const warns = state.problems.length - errs;
504
+ $('problems-label').textContent = state.problems.length ? `Problems · ${errs} error${errs === 1 ? '' : 's'}, ${warns} warning${warns === 1 ? '' : 's'}` : 'No problems';
505
+ const had = state.problemsSeen;
506
+ const A = part?.attention?.();
507
+ state.problemsSeen = state.problems.length + (A?.count ?? 0);
508
+ // (in Simulation, made-up attention doesn't open or close the list: the layout keeps still while it plays or scrubs)
509
+ const attn = A?.opens ?? 0;
510
+ if (A?.still && !state.problems.length) setProblemsOpen(state.problemsOpen, false);
511
+ else if (!state.problems.length && !attn && bottomTab === 'problems') setProblemsOpen(false, false);
512
+ else if ((state.problems.length || attn) && !had) setProblemsOpen(true, false);
513
+ else setProblemsOpen(state.problemsOpen, false);
514
+ $('st-problems').textContent = `${errs} ✕ ${warns} ⚠`;
515
+ $('st-problems').className = errs ? 'bad' : warns ? 'warn' : 'ok';
516
+ // what waits for a person (the part's), under its own heading, before the file's problems
517
+ if (A?.rows.length) {
518
+ list.append(...A.rows);
519
+ if (state.problems.length) list.append(h('div', { class: 'prob-head' }, 'In the file'));
520
+ }
521
+ $('problems-label').textContent = (state.problems.length ? $('problems-label').textContent : A?.count ? '' : 'No problems') + (A?.count ? `${state.problems.length ? ' · ' : ''}${A.label}` : '');
522
+ for (const p of state.problems) {
523
+ const b = h('button', { type: 'button', class: `prob ${p.severity}${p.file ? ' other-file' : ''}` },
524
+ h('span', { class: 'where' }, p.file ? `${p.file} · line ${p.startLine}` : `${p.startLine}:${p.startCol}`), h('span', { class: 'msg' }, p.message),
525
+ p.hint ? h('span', { class: 'hint' }, p.hint) : null);
526
+ // a problem in another file (a defaults file) is named, not placed in this text
527
+ if (p.file) b.title = `In ${p.file}, line ${p.startLine}: not in this file`;
528
+ else b.addEventListener('click', () => pane.goToOffset(problemRange(doc.text, p)[0]));
529
+ list.append(b);
530
+ }
531
+ }
532
+
533
+ // ---------- the status bar ----------
534
+ let caretFrame = 0;
535
+ const paintCaret = () => {
536
+ if (caretFrame) return;
537
+ caretFrame = requestAnimationFrame(() => { caretFrame = 0; const p = pane.caret(); $('st-pos').textContent = p ? `Ln ${p.line}, Col ${p.col}` : ''; });
538
+ };
539
+ const paintPathLater = later(() => paintPath());
540
+ function paintPath() {
541
+ const path = pane.pathAtCaret();
542
+ $('st-path').textContent = path.length ? path.join(' › ') : '';
543
+ $('st-path').title = toPointer(path);
544
+ $('st-kind').textContent = K.kindLabel(doc.text);
545
+ }
546
+ const wireCaret = () => pane.onCaret(() => { paintCaret(); paintPathLater(); });
547
+ wireCaret();
548
+ cleanups.push(doc.on(c => { paintCaret(); if (isTyping(c)) paintPathLater(); else paintPathLater.now(); }));
549
+
550
+ // ---------- resizing the problems panel ----------
551
+ {
552
+ const g = $('grip');
553
+ const move = (dy: number) => {
554
+ const hh = Math.min(Math.max($('problems').getBoundingClientRect().height - dy, 48), innerHeight * 0.6);
555
+ root.style.setProperty('--problems-h', `${hh}px`);
556
+ store.set('problems-h', String(Math.round(hh)));
557
+ };
558
+ const saved = store.get('problems-h');
559
+ if (saved) root.style.setProperty('--problems-h', `${saved}px`);
560
+ on(g, 'pointerdown', (e: PointerEvent) => {
561
+ g.setPointerCapture(e.pointerId);
562
+ let y = e.clientY;
563
+ const mv = (ev: PointerEvent) => { move(ev.clientY - y); y = ev.clientY; };
564
+ const up = () => { g.removeEventListener('pointermove', mv); g.removeEventListener('pointerup', up); };
565
+ g.addEventListener('pointermove', mv); g.addEventListener('pointerup', up);
566
+ });
567
+ on(g, 'keydown', (e: KeyboardEvent) => { if (e.key === 'ArrowUp') { move(-16); e.preventDefault(); } if (e.key === 'ArrowDown') { move(16); e.preventDefault(); } });
568
+ }
569
+
570
+ // ---------- the domain's part (what it adds beside the views) ----------
571
+ part = S.part?.({
572
+ root, byId: $, doc, store, note, watch, on: (t, ev, fn) => on(t as HTMLElement, ev as 'change', fn), disposed: () => disposed,
573
+ paintProblems: () => paintProblems(), paintProps: () => props.paint(),
574
+ }, { canvas: () => canvas, objectPath: resourcePath });
575
+
576
+ // ---------- read-only ----------
577
+ function setReadOnly(ro: boolean) {
578
+ ro = ro || !F.edit; // without the edit feature, nothing edits
579
+ state.readOnly = ro;
580
+ root.classList.toggle('read-only', ro);
581
+ $('ro').hidden = !ro;
582
+ pane.setReadOnly(ro);
583
+ paintTitle(); paintHistory();
584
+ }
585
+
586
+ // ---------- start ----------
587
+ // P3: the controls of features not given are not shown
588
+ function paintFeatures() {
589
+ $('views').hidden = !(F.text && F.canvas);
590
+ $('right').hidden = $('right-grip').hidden = !F.edit;
591
+ ($('tab-plan') as HTMLElement).hidden = !F.plan;
592
+ root.dataset.features = Object.keys(F).sort().join(' ');
593
+ }
594
+ if (!F.plan && bottomTab === 'plan') bottomTab = 'problems';
595
+ setBottomTab(bottomTab);
596
+ paintFeatures();
597
+ setView(state.view);
598
+ applyTheme();
599
+ setReadOnly(state.readOnly);
600
+ doc.load(opts.text ?? '');
601
+ part?.start?.();
602
+ paintTitle(); paintHistory();
603
+
604
+ // ---------- v0.4.1: features added to the mounted editor: the file, its undo history and the selection are kept ----------
605
+ // text and plan attach here; the others are drawn into the canvas when it is made, so they come with a new mount.
606
+ const LATE = S.late;
607
+ let adding: Promise<void> = Promise.resolve();
608
+ async function addFeatures(names: readonly string[]): Promise<void> {
609
+ const bad = names.filter(n => !S.names.includes(n));
610
+ if (bad.length) throw new Error(`unknown feature ${bad.join(', ')}: the features are ${S.names.join(', ')}`);
611
+ const run = adding.then(async () => {
612
+ if (disposed) throw new Error('the editor was disposed');
613
+ const want = [...new Set(names)].filter(n => !F[n]);
614
+ if (!want.length) return;
615
+ const late = want.filter(n => !LATE.includes(n));
616
+ if (late.length) throw new Error(`${late.join(', ')} can't be added to a mounted editor (only ${LATE.join(' and ')} can): mount with ${late.length > 1 ? 'them' : 'it'}`);
617
+ if (!load) throw new Error(`this build has no loader for ${want.join(', ')}: mount with ${want.length > 1 ? 'them' : 'it'}`);
618
+ const got = await load(want);
619
+ if (disposed) throw new Error('the editor was disposed');
620
+ const sel = doc.selection.slice();
621
+ for (const f of got) (F as Record<string, unknown>)[f.name] = f;
622
+ if (want.includes('text')) {
623
+ pane.dispose();
624
+ pane = makePane(); // its model takes the file as it is now (doc.text)
625
+ wireCaret();
626
+ pane.setReadOnly(state.readOnly);
627
+ pane.setProblems(state.problems.filter(p => !p.file));
628
+ applyTheme();
629
+ if (sel.length) doc.select(sel, 'menu');
630
+ }
631
+ if (want.includes('plan')) { planUI = makePlan(); paintPlan(); }
632
+ paintFeatures();
633
+ setView(wanted);
634
+ paintPath();
635
+ });
636
+ adding = run.catch(() => undefined);
637
+ return run;
638
+ }
639
+
640
+ const internal: Record<string, unknown> = {
641
+ root, doc, get pane() { return pane; }, tree, canvas, props, clip, state, check, save, note, setView, showBanner, hideBanner,
642
+ keySheet: sheet, setTheme, setDensity, setBottomTab,
643
+ markers: () => {
644
+ const M = pane.monaco;
645
+ return M.editor.getModelMarkers({ resource: pane.model.uri }).map(m => ({ severity: m.severity, message: m.message, line: m.startLineNumber, col: m.startColumn, endCol: m.endColumn }));
646
+ },
647
+ };
648
+ // the domain's handles, and its part's calls (their getters stay getters)
649
+ if (S.internal) Object.defineProperties(internal, Object.getOwnPropertyDescriptors(S.internal));
650
+ if (part) Object.defineProperties(internal, Object.getOwnPropertyDescriptors(part.api));
651
+ return {
652
+ internal,
653
+ getText: () => doc.text,
654
+ setText(text: string) { hideBanner(); doc.load(text); doc.markClean(); paintTitle(); paintHistory(); },
655
+ setReadOnly,
656
+ setTheme,
657
+ addFeatures,
658
+ fit() { if (!disposed) canvas.fit(); },
659
+ dispose() {
660
+ if (disposed) return;
661
+ disposed = true;
662
+ clearTimeout(timer); clearTimeout(noteTimer); part?.dispose?.(); cancelAnimationFrame(caretFrame); paintPathLater.cancel();
663
+ closeMenu();
664
+ for (const c of cleanups.splice(0)) c();
665
+ tree.dispose(); props.dispose(); canvas.dispose();
666
+ pane.dispose();
667
+ root.remove();
668
+ setLayer(null);
669
+ },
670
+ };
671
+ }
672
+
673
+ /** P3: no text feature: a pane that shows nothing (the canvas is the view); no Monaco is loaded */
674
+ function noText(): MonacoPane {
675
+ const none = () => undefined;
676
+ return { setTheme: none, setReadOnly: none, setProblems: none, goTo: none, goToOffset: none, focus: none, dispose: none,
677
+ onCaret: none, caret: () => undefined, pathAtCaret: () => [], editor: { layout: none, focus: none }, model: undefined, monaco: undefined,
678
+ resyncs: () => 0 } as unknown as MonacoPane;
679
+ }
680
+ /** P3: no canvas feature: nothing drawn (the text and the tree are the views); every call answers nothing */
681
+ function noCanvas(more: Record<string, unknown> = {}): ShellCanvas {
682
+ const fixed: Record<string, unknown> = { palette: undefined, doc: undefined, stage: undefined, ...more };
683
+ return new Proxy({}, { get: (_t, k: string) => (k in fixed ? fixed[k] : () => undefined) }) as unknown as ShellCanvas;
684
+ }