@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.
- package/EDITOR-GUIDE.md +317 -0
- package/LICENSE +21 -0
- package/LICENSES/ajv.txt +22 -0
- package/LICENSES/lucide-static.txt +43 -0
- package/LICENSES/yaml.txt +13 -0
- package/README.md +62 -2
- package/assets/app.css +265 -0
- package/assets/default-theme.yaml +99 -0
- package/assets/icons.svg +1 -0
- package/assets/marks.css +35 -0
- package/assets/skin.css +181 -0
- package/iso-editor.d.ts +4 -0
- package/iso-editor.js +550 -0
- package/iso-render.d.ts +3 -0
- package/iso-render.js +388 -0
- package/iso-systems.d.ts +4 -0
- package/iso-systems.js +389 -0
- package/js/iso-core/compile-schema.js +22 -0
- package/js/iso-core/depth.js +55 -0
- package/js/iso-core/errors.js +65 -0
- package/js/iso-core/glyphs.js +100 -0
- package/js/iso-core/index.js +55 -0
- package/js/iso-core/kernel.js +158 -0
- package/js/iso-core/metrics.json +1 -0
- package/js/iso-core/package.json +6 -0
- package/js/iso-core/parse.js +79 -0
- package/js/iso-core/schema-errors.js +170 -0
- package/js/iso-core/shims/crypto.js +125 -0
- package/js/iso-core/shims/path.js +49 -0
- package/js/iso-core/svg-dom.js +144 -0
- package/js/iso-core/theme.js +48 -0
- package/js/iso-core/vdom.js +48 -0
- package/js/iso-editor/adapter.js +0 -0
- package/js/iso-editor/clipboard.js +152 -0
- package/js/iso-editor/commands.js +173 -0
- package/js/iso-editor/complete.js +55 -0
- package/js/iso-editor/doc.js +182 -0
- package/js/iso-editor/index.js +105 -0
- package/js/iso-editor/model.js +210 -0
- package/js/iso-editor/outline.js +111 -0
- package/js/iso-editor/package.json +6 -0
- package/js/iso-editor/path.js +19 -0
- package/js/iso-editor/providers.js +96 -0
- package/js/iso-editor/schema-nav.js +117 -0
- package/js/iso-editor/splice.js +441 -0
- package/js/iso-editor/storage-keys.js +6 -0
- package/js/iso-editor/ui/actions.js +116 -0
- package/js/iso-editor/ui/canvas-layer.js +0 -0
- package/js/iso-editor/ui/canvas.js +1205 -0
- package/js/iso-editor/ui/clip.js +133 -0
- package/js/iso-editor/ui/dialog.js +26 -0
- package/js/iso-editor/ui/flat-canvas.js +54 -0
- package/js/iso-editor/ui/icons.js +15 -0
- package/js/iso-editor/ui/keys.js +26 -0
- package/js/iso-editor/ui/later.js +28 -0
- package/js/iso-editor/ui/layer.js +11 -0
- package/js/iso-editor/ui/menu.js +105 -0
- package/js/iso-editor/ui/monaco-entry.js +2 -0
- package/js/iso-editor/ui/mount-kit.js +0 -0
- package/js/iso-editor/ui/mount.js +767 -0
- package/js/iso-editor/ui/pane.js +0 -0
- package/js/iso-editor/ui/part.js +0 -0
- package/js/iso-editor/ui/plain-icons.js +34 -0
- package/js/iso-editor/ui/props.js +314 -0
- package/js/iso-editor/ui/scope-css.js +81 -0
- package/js/iso-editor/ui/setup.js +145 -0
- package/js/iso-editor/ui/text.js +323 -0
- package/js/iso-editor/ui/tree.js +728 -0
- package/js/iso-editor/validate.js +33 -0
- package/js/iso-editor/window/protocol.js +8 -0
- package/js/iso-objects/assemble.js +43 -0
- package/js/iso-objects/assets.js +88 -0
- package/js/iso-objects/board.js +162 -0
- package/js/iso-objects/compile.js +60 -0
- package/js/iso-objects/css.js +154 -0
- package/js/iso-objects/flat.js +696 -0
- package/js/iso-objects/focus.js +16 -0
- package/js/iso-objects/geometry.js +76 -0
- package/js/iso-objects/index.js +93 -0
- package/js/iso-objects/kinds.js +12 -0
- package/js/iso-objects/labels.js +325 -0
- package/js/iso-objects/package.json +6 -0
- package/js/iso-objects/place.js +347 -0
- package/js/iso-objects/route.js +461 -0
- package/js/iso-objects/scene.js +350 -0
- package/js/iso-objects/steps.js +246 -0
- package/js/iso-objects/types.js +0 -0
- package/js/iso-systems/catalog.js +42 -0
- package/js/iso-systems/compile.js +34 -0
- package/js/iso-systems/css.js +8 -0
- package/js/iso-systems/index.js +16 -0
- package/js/iso-systems/nodes.js +124 -0
- package/js/iso-systems/package.json +6 -0
- package/js/iso-systems/schema.json +311 -0
- package/js/iso-systems/validate.js +35 -0
- package/js/iso-viewer/bundle.js +20 -0
- package/js/iso-viewer/card-motion.js +228 -0
- package/js/iso-viewer/dom.js +14 -0
- package/js/iso-viewer/dual-view.js +212 -0
- package/js/iso-viewer/flat-view.js +124 -0
- package/js/iso-viewer/history.js +990 -0
- package/js/iso-viewer/index.js +98 -0
- package/js/iso-viewer/morph.js +192 -0
- package/js/iso-viewer/overlay.js +199 -0
- package/js/iso-viewer/package.json +6 -0
- package/js/iso-viewer/page.js +138 -0
- package/js/iso-viewer/player.js +409 -0
- package/js/iso-viewer/still.js +81 -0
- package/js/iso-viewer/timeline-contract.js +14 -0
- package/js/iso-viewer/timeline-engine.js +475 -0
- package/js/iso-viewer/timeline-export.js +36 -0
- package/js/iso-viewer/timeline-scale.js +116 -0
- package/js/iso-viewer/timeline-scope.js +58 -0
- package/js/iso-viewer/timeline-search.js +216 -0
- package/js/iso-viewer/timeline-time.js +55 -0
- package/js/iso-viewer/view-css.js +68 -0
- package/js/iso-viewer/viewport.js +177 -0
- package/package.json +502 -4
- package/src/iso-core/compile-schema.ts +23 -0
- package/src/iso-core/depth.ts +56 -0
- package/src/iso-core/errors.ts +73 -0
- package/src/iso-core/glyphs.ts +108 -0
- package/src/iso-core/index.ts +27 -0
- package/src/iso-core/kernel.ts +163 -0
- package/src/iso-core/metrics.json +1 -0
- package/src/iso-core/package.json +6 -0
- package/src/iso-core/parse.ts +91 -0
- package/src/iso-core/schema-errors.ts +163 -0
- package/src/iso-core/shims/crypto.ts +37 -0
- package/src/iso-core/shims/path.ts +24 -0
- package/src/iso-core/svg-dom.ts +103 -0
- package/src/iso-core/theme.ts +64 -0
- package/src/iso-core/vdom.ts +41 -0
- package/src/iso-editor/adapter.ts +128 -0
- package/src/iso-editor/clipboard.ts +163 -0
- package/src/iso-editor/commands.ts +191 -0
- package/src/iso-editor/complete.ts +73 -0
- package/src/iso-editor/doc.ts +207 -0
- package/src/iso-editor/index.ts +67 -0
- package/src/iso-editor/model.ts +234 -0
- package/src/iso-editor/outline.ts +126 -0
- package/src/iso-editor/package.json +6 -0
- package/src/iso-editor/path.ts +18 -0
- package/src/iso-editor/providers.ts +113 -0
- package/src/iso-editor/schema-nav.ts +129 -0
- package/src/iso-editor/splice.ts +472 -0
- package/src/iso-editor/storage-keys.ts +6 -0
- package/src/iso-editor/ui/actions.ts +119 -0
- package/src/iso-editor/ui/app.css +230 -0
- package/src/iso-editor/ui/canvas-layer.ts +56 -0
- package/src/iso-editor/ui/canvas.ts +1071 -0
- package/src/iso-editor/ui/clip.ts +97 -0
- package/src/iso-editor/ui/dialog.ts +25 -0
- package/src/iso-editor/ui/flat-canvas.ts +51 -0
- package/src/iso-editor/ui/icons.ts +21 -0
- package/src/iso-editor/ui/keys.ts +30 -0
- package/src/iso-editor/ui/later.ts +22 -0
- package/src/iso-editor/ui/layer.ts +7 -0
- package/src/iso-editor/ui/marks.css +35 -0
- package/src/iso-editor/ui/menu.ts +67 -0
- package/src/iso-editor/ui/monaco-entry.ts +6 -0
- package/src/iso-editor/ui/mount-kit.ts +35 -0
- package/src/iso-editor/ui/mount.ts +684 -0
- package/src/iso-editor/ui/pane.ts +45 -0
- package/src/iso-editor/ui/part.ts +45 -0
- package/src/iso-editor/ui/plain-icons.ts +83 -0
- package/src/iso-editor/ui/props.ts +347 -0
- package/src/iso-editor/ui/scope-css.ts +65 -0
- package/src/iso-editor/ui/setup.ts +144 -0
- package/src/iso-editor/ui/skin.css +181 -0
- package/src/iso-editor/ui/text.ts +262 -0
- package/src/iso-editor/ui/tree.ts +657 -0
- package/src/iso-editor/validate.ts +62 -0
- package/src/iso-editor/window/protocol.ts +33 -0
- package/src/iso-objects/assemble.ts +57 -0
- package/src/iso-objects/assets.ts +122 -0
- package/src/iso-objects/board.ts +169 -0
- package/src/iso-objects/compile.ts +76 -0
- package/src/iso-objects/css.ts +163 -0
- package/src/iso-objects/flat.ts +653 -0
- package/src/iso-objects/focus.ts +14 -0
- package/src/iso-objects/geometry.ts +86 -0
- package/src/iso-objects/index.ts +33 -0
- package/src/iso-objects/kinds.ts +56 -0
- package/src/iso-objects/labels.ts +310 -0
- package/src/iso-objects/package.json +6 -0
- package/src/iso-objects/place.ts +318 -0
- package/src/iso-objects/route.ts +444 -0
- package/src/iso-objects/scene.ts +376 -0
- package/src/iso-objects/steps.ts +234 -0
- package/src/iso-objects/types.ts +68 -0
- package/src/iso-systems/catalog.ts +31 -0
- package/src/iso-systems/compile.ts +39 -0
- package/src/iso-systems/css.ts +9 -0
- package/src/iso-systems/index.ts +12 -0
- package/src/iso-systems/nodes.ts +126 -0
- package/src/iso-systems/package.json +6 -0
- package/src/iso-systems/schema.json +311 -0
- package/src/iso-systems/validate.ts +34 -0
- package/src/iso-viewer/bundle.ts +15 -0
- package/src/iso-viewer/card-motion.ts +237 -0
- package/src/iso-viewer/dom.ts +13 -0
- package/src/iso-viewer/dual-view.ts +212 -0
- package/src/iso-viewer/flat-view.ts +127 -0
- package/src/iso-viewer/history.ts +781 -0
- package/src/iso-viewer/index.ts +40 -0
- package/src/iso-viewer/morph.ts +191 -0
- package/src/iso-viewer/overlay.ts +212 -0
- package/src/iso-viewer/package.json +6 -0
- package/src/iso-viewer/page.ts +150 -0
- package/src/iso-viewer/player.ts +321 -0
- package/src/iso-viewer/still.ts +74 -0
- package/src/iso-viewer/timeline-contract.ts +342 -0
- package/src/iso-viewer/timeline-engine.ts +420 -0
- package/src/iso-viewer/timeline-export.ts +31 -0
- package/src/iso-viewer/timeline-scale.ts +129 -0
- package/src/iso-viewer/timeline-scope.ts +56 -0
- package/src/iso-viewer/timeline-search.ts +198 -0
- package/src/iso-viewer/timeline-time.ts +54 -0
- package/src/iso-viewer/view-css.ts +59 -0
- package/src/iso-viewer/viewport.ts +142 -0
- package/types/iso-core/compile-schema.d.ts +11 -0
- package/types/iso-core/depth.d.ts +6 -0
- package/types/iso-core/errors.d.ts +24 -0
- package/types/iso-core/glyphs.d.ts +19 -0
- package/types/iso-core/index.d.ts +17 -0
- package/types/iso-core/kernel.d.ts +130 -0
- package/types/iso-core/metrics.json +1 -0
- package/types/iso-core/parse.d.ts +18 -0
- package/types/iso-core/schema-errors.d.ts +14 -0
- package/types/iso-core/shims/crypto.d.ts +9 -0
- package/types/iso-core/svg-dom.d.ts +15 -0
- package/types/iso-core/theme.d.ts +38 -0
- package/types/iso-core/vdom.d.ts +26 -0
- package/types/iso-editor/adapter.d.ts +145 -0
- package/types/iso-editor/clipboard.d.ts +23 -0
- package/types/iso-editor/commands.d.ts +32 -0
- package/types/iso-editor/complete.d.ts +25 -0
- package/types/iso-editor/doc.d.ts +50 -0
- package/types/iso-editor/index.d.ts +57 -0
- package/types/iso-editor/model.d.ts +96 -0
- package/types/iso-editor/outline.d.ts +28 -0
- package/types/iso-editor/path.d.ts +7 -0
- package/types/iso-editor/providers.d.ts +43 -0
- package/types/iso-editor/schema-nav.d.ts +34 -0
- package/types/iso-editor/splice.d.ts +53 -0
- package/types/iso-editor/storage-keys.d.ts +5 -0
- package/types/iso-editor/ui/actions.d.ts +23 -0
- package/types/iso-editor/ui/canvas-layer.d.ts +65 -0
- package/types/iso-editor/ui/canvas.d.ts +279 -0
- package/types/iso-editor/ui/clip.d.ts +14 -0
- package/types/iso-editor/ui/dialog.d.ts +7 -0
- package/types/iso-editor/ui/flat-canvas.d.ts +2 -0
- package/types/iso-editor/ui/icons.d.ts +5 -0
- package/types/iso-editor/ui/keys.d.ts +7 -0
- package/types/iso-editor/ui/later.d.ts +12 -0
- package/types/iso-editor/ui/layer.d.ts +2 -0
- package/types/iso-editor/ui/menu.d.ts +21 -0
- package/types/iso-editor/ui/mount-kit.d.ts +31 -0
- package/types/iso-editor/ui/mount.d.ts +146 -0
- package/types/iso-editor/ui/pane.d.ts +60 -0
- package/types/iso-editor/ui/part.d.ts +40 -0
- package/types/iso-editor/ui/plain-icons.d.ts +10 -0
- package/types/iso-editor/ui/props.d.ts +57 -0
- package/types/iso-editor/ui/scope-css.d.ts +5 -0
- package/types/iso-editor/ui/setup.d.ts +40 -0
- package/types/iso-editor/ui/text.d.ts +19 -0
- package/types/iso-editor/ui/tree.d.ts +100 -0
- package/types/iso-editor/validate.d.ts +36 -0
- package/types/iso-editor/window/protocol.d.ts +60 -0
- package/types/iso-objects/assemble.d.ts +35 -0
- package/types/iso-objects/assets.d.ts +49 -0
- package/types/iso-objects/board.d.ts +36 -0
- package/types/iso-objects/compile.d.ts +35 -0
- package/types/iso-objects/css.d.ts +16 -0
- package/types/iso-objects/flat.d.ts +130 -0
- package/types/iso-objects/focus.d.ts +1 -0
- package/types/iso-objects/geometry.d.ts +59 -0
- package/types/iso-objects/index.d.ts +26 -0
- package/types/iso-objects/kinds.d.ts +53 -0
- package/types/iso-objects/labels.d.ts +92 -0
- package/types/iso-objects/place.d.ts +25 -0
- package/types/iso-objects/route.d.ts +67 -0
- package/types/iso-objects/scene.d.ts +63 -0
- package/types/iso-objects/steps.d.ts +90 -0
- package/types/iso-objects/types.d.ts +140 -0
- package/types/iso-systems/catalog.d.ts +4 -0
- package/types/iso-systems/compile.d.ts +6 -0
- package/types/iso-systems/css.d.ts +3 -0
- package/types/iso-systems/index.d.ts +5 -0
- package/types/iso-systems/nodes.d.ts +3 -0
- package/types/iso-viewer/card-motion.d.ts +56 -0
- package/types/iso-viewer/dom.d.ts +1 -0
- package/types/iso-viewer/dual-view.d.ts +44 -0
- package/types/iso-viewer/flat-view.d.ts +25 -0
- package/types/iso-viewer/history.d.ts +91 -0
- package/types/iso-viewer/index.d.ts +31 -0
- package/types/iso-viewer/morph.d.ts +28 -0
- package/types/iso-viewer/overlay.d.ts +135 -0
- package/types/iso-viewer/page.d.ts +13 -0
- package/types/iso-viewer/still.d.ts +26 -0
- package/types/iso-viewer/timeline-contract.d.ts +345 -0
- package/types/iso-viewer/timeline-engine.d.ts +20 -0
- package/types/iso-viewer/timeline-export.d.ts +5 -0
- package/types/iso-viewer/timeline-scale.d.ts +44 -0
- package/types/iso-viewer/timeline-scope.d.ts +33 -0
- package/types/iso-viewer/timeline-search.d.ts +52 -0
- package/types/iso-viewer/timeline-time.d.ts +8 -0
- package/types/iso-viewer/view-css.d.ts +7 -0
- package/types/iso-viewer/viewport.d.ts +50 -0
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
// Structural edits as text splices. Each operation reads the parsed Document's source ranges and returns the few
|
|
2
|
+
// TextEdits that make the change, so every byte outside them stays as the user wrote it (comments, key order,
|
|
3
|
+
// quoting, blank lines). When a layout is too irregular to splice (a key that isn't first on its line inside a block
|
|
4
|
+
// map, say), the smallest enclosing collection is re-serialised instead; that result is marked `fallback` so tests
|
|
5
|
+
// can flag it. Pure.
|
|
6
|
+
|
|
7
|
+
import { parseDocument, stringify, isMap, isSeq, isScalar, isPair, Scalar, Document, type Node as YNode, type Pair, type YAMLMap, type YAMLSeq } from 'yaml';
|
|
8
|
+
import type { Path, Seg } from './path.ts';
|
|
9
|
+
|
|
10
|
+
export interface TextEdit { start: number; end: number; text: string }
|
|
11
|
+
/** one step: non-overlapping edits against the same text */
|
|
12
|
+
export type Step = TextEdit[];
|
|
13
|
+
export interface Splice { steps: Step[]; fallback?: boolean }
|
|
14
|
+
|
|
15
|
+
export class SpliceError extends Error {}
|
|
16
|
+
|
|
17
|
+
/** Apply one step's edits (non-overlapping) to a text. */
|
|
18
|
+
export function applyStep(text: string, step: Step): string {
|
|
19
|
+
let out = text;
|
|
20
|
+
for (const e of [...step].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.text + out.slice(e.end);
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
/** The step that undoes `step` on the text it produced. */
|
|
24
|
+
export function invertStep(text: string, step: Step): Step {
|
|
25
|
+
const sorted = [...step].sort((a, b) => a.start - b.start);
|
|
26
|
+
let delta = 0;
|
|
27
|
+
return sorted.map(e => {
|
|
28
|
+
const start = e.start + delta;
|
|
29
|
+
delta += e.text.length - (e.end - e.start);
|
|
30
|
+
return { start, end: start + e.text.length, text: text.slice(e.start, e.end) };
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ---------- reading the document ----------
|
|
35
|
+
|
|
36
|
+
interface Ctx { text: string; doc: Document.Parsed }
|
|
37
|
+
const parse = (text: string): Ctx => ({ text, doc: parseDocument(text, { keepSourceTokens: true, uniqueKeys: false }) });
|
|
38
|
+
|
|
39
|
+
function keyOf(p: Pair): string { return isScalar(p.key) ? String(p.key.value) : String(p.key); }
|
|
40
|
+
|
|
41
|
+
/** The node at a path, the pair holding it (for map entries), and the collections on the way (for flow detection). */
|
|
42
|
+
function find(c: Ctx, path: Path): { node: YNode | null | undefined; pair?: Pair; parent?: YAMLMap | YAMLSeq; chain: unknown[] } {
|
|
43
|
+
let node: unknown = c.doc.contents;
|
|
44
|
+
let pair: Pair | undefined;
|
|
45
|
+
let parent: YAMLMap | YAMLSeq | undefined;
|
|
46
|
+
const chain: unknown[] = [node];
|
|
47
|
+
for (const seg of path) {
|
|
48
|
+
pair = undefined;
|
|
49
|
+
if (isMap(node)) {
|
|
50
|
+
parent = node;
|
|
51
|
+
const p = node.items.find(x => isPair(x) && keyOf(x) === String(seg));
|
|
52
|
+
if (!p) return { node: undefined, parent, chain };
|
|
53
|
+
pair = p as Pair;
|
|
54
|
+
node = p.value;
|
|
55
|
+
} else if (isSeq(node) && typeof seg === 'number') {
|
|
56
|
+
parent = node;
|
|
57
|
+
node = node.items[seg];
|
|
58
|
+
if (node === undefined) return { node: undefined, parent, chain };
|
|
59
|
+
} else return { node: undefined, chain };
|
|
60
|
+
chain.push(node);
|
|
61
|
+
}
|
|
62
|
+
return { node: node as YNode | null, pair, parent, chain };
|
|
63
|
+
}
|
|
64
|
+
const inFlow = (chain: unknown[]) => chain.some(n => (isMap(n) || isSeq(n)) && (n as { flow?: boolean }).flow);
|
|
65
|
+
|
|
66
|
+
const lineStart = (t: string, off: number) => t.lastIndexOf('\n', off - 1) + 1;
|
|
67
|
+
const lineEnd = (t: string, off: number) => { const i = t.indexOf('\n', off); return i < 0 ? t.length : i; };
|
|
68
|
+
/** the start of the line after the one holding `off` (or the end of the text) */
|
|
69
|
+
const nextLine = (t: string, off: number) => { const i = t.indexOf('\n', off); return i < 0 ? t.length : i + 1; };
|
|
70
|
+
const colOf = (t: string, off: number) => off - lineStart(t, off);
|
|
71
|
+
|
|
72
|
+
/** Where a pair's text ends: the start of the line after its last line (its value's end, with any comment after it). */
|
|
73
|
+
function pairEnd(c: Ctx, p: Pair): number {
|
|
74
|
+
const k = p.key as YNode;
|
|
75
|
+
const v = p.value as YNode | null;
|
|
76
|
+
const end = v?.range ? Math.max(v.range[1], k.range![1]) : k.range![1];
|
|
77
|
+
// a block value's range ends at the start of the line after it; anything else ends inside its last line
|
|
78
|
+
const last = end > 0 && c.text[end - 1] === '\n' ? end - 1 : end;
|
|
79
|
+
return nextLine(c.text, last);
|
|
80
|
+
}
|
|
81
|
+
/** The first line of a pair, with its own comment lines directly above it at the same indent. */
|
|
82
|
+
function pairStart(c: Ctx, p: Pair): number {
|
|
83
|
+
const k = (p.key as YNode).range![0];
|
|
84
|
+
let s = lineStart(c.text, k);
|
|
85
|
+
const ind = k - s;
|
|
86
|
+
if (onDash(c.text, k)) return k;
|
|
87
|
+
for (;;) {
|
|
88
|
+
if (s === 0) break;
|
|
89
|
+
const ps = lineStart(c.text, s - 1);
|
|
90
|
+
const line = c.text.slice(ps, s - 1);
|
|
91
|
+
if (/^\s*#/.test(line) && line.length - line.trimStart().length === ind) s = ps; else break;
|
|
92
|
+
}
|
|
93
|
+
return s;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Is a key the first thing on its line (after any "- " of the list items holding its map)? */
|
|
97
|
+
const firstOnLine = (t: string, k: number) => /^\s*(-\s+)*$/.test(t.slice(lineStart(t, k), k));
|
|
98
|
+
const onDash = (t: string, k: number) => /-\s+$/.test(t.slice(lineStart(t, k), k));
|
|
99
|
+
|
|
100
|
+
// ---------- writing values ----------
|
|
101
|
+
|
|
102
|
+
type Style = string | undefined;
|
|
103
|
+
const SAFE_FLOW = /[,[\]{}]/;
|
|
104
|
+
|
|
105
|
+
/** A scalar as YAML text. Keeps a quoting style when one is given; multi-line text becomes a block literal. */
|
|
106
|
+
export function scalarText(v: unknown, opts: { flow: boolean; indent: number; style?: Style }): string {
|
|
107
|
+
if (v === null || v === undefined) return 'null';
|
|
108
|
+
if (typeof v !== 'string') return String(v);
|
|
109
|
+
if (opts.style === Scalar.QUOTE_DOUBLE) return JSON.stringify(v);
|
|
110
|
+
if (opts.style === Scalar.QUOTE_SINGLE && !v.includes('\n')) return `'${v.replace(/'/g, "''")}'`;
|
|
111
|
+
if (v.includes('\n')) {
|
|
112
|
+
if (opts.flow) return JSON.stringify(v);
|
|
113
|
+
const body = v.endsWith('\n') ? v.slice(0, -1) : v;
|
|
114
|
+
if (/(^|\n)\s/.test(body.split('\n')[0] ?? '') || /^\s/.test(body)) return JSON.stringify(v);
|
|
115
|
+
return (v.endsWith('\n') ? '|' : '|-') + '\n' + body.split('\n').map(l => (l ? ' '.repeat(opts.indent) + l : '')).join('\n');
|
|
116
|
+
}
|
|
117
|
+
const plain = stringify(v, { lineWidth: 0 }).replace(/\n$/, '');
|
|
118
|
+
if (opts.flow && SAFE_FLOW.test(plain) && !/^["']/.test(plain)) return JSON.stringify(v);
|
|
119
|
+
return plain;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A value inline, in flow style: { a: 1, b: [x, y] } */
|
|
123
|
+
export function flowText(v: unknown): string {
|
|
124
|
+
if (Array.isArray(v)) return v.length ? `[${v.map(flowText).join(', ')}]` : '[]';
|
|
125
|
+
if (v && typeof v === 'object') {
|
|
126
|
+
const e = Object.entries(v as Record<string, unknown>);
|
|
127
|
+
return e.length ? `{ ${e.map(([k, x]) => `${keyText(k)}: ${flowText(x)}`).join(', ')} }` : '{}';
|
|
128
|
+
}
|
|
129
|
+
return scalarText(v, { flow: true, indent: 0 });
|
|
130
|
+
}
|
|
131
|
+
const keyText = (k: string) => scalarText(k, { flow: true, indent: 0 });
|
|
132
|
+
const isObj = (v: unknown) => !!v && typeof v === 'object';
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Small values are written the way the files are written by hand: a list of scalars as [a, b], a map of at most two
|
|
136
|
+
* short entries as { key: value } (a pin: { at: [3, 12] }). Anything bigger stays in block style.
|
|
137
|
+
*/
|
|
138
|
+
const flowFits = (v: unknown): boolean => {
|
|
139
|
+
if (Array.isArray(v)) return v.every(x => !isObj(x) && !(typeof x === 'string' && x.includes('\n'))) && flowText(v).length <= 60;
|
|
140
|
+
if (isObj(v)) { const e = Object.entries(v as Record<string, unknown>); return e.length > 0 && e.length <= 2 && e.every(([, x]) => !isObj(x) && !(typeof x === 'string' && x.includes('\n')) || (Array.isArray(x) && flowFits(x))) && flowText(v).length <= 40; }
|
|
141
|
+
return false;
|
|
142
|
+
};
|
|
143
|
+
/** A value in block style at indent 0, its small parts in flow style (see flowFits). */
|
|
144
|
+
function yamlText(v: unknown, ind = 0): string {
|
|
145
|
+
const pad = ' '.repeat(ind);
|
|
146
|
+
const inline = (x: unknown): string | undefined => {
|
|
147
|
+
if (!isObj(x)) return scalarText(x, { flow: false, indent: ind + 2 });
|
|
148
|
+
if (Array.isArray(x) ? !x.length : !Object.keys(x as object).length) return Array.isArray(x) ? '[]' : '{}';
|
|
149
|
+
return flowFits(x) ? flowText(x) : undefined;
|
|
150
|
+
};
|
|
151
|
+
if (Array.isArray(v)) {
|
|
152
|
+
return v.map(x => {
|
|
153
|
+
const one = inline(x);
|
|
154
|
+
if (one !== undefined) return `${pad}- ${one}`;
|
|
155
|
+
const inner = yamlText(x, ind + 2);
|
|
156
|
+
return Array.isArray(x) ? `${pad}-\n${inner}` : `${pad}- ${inner.slice(ind + 2)}`;
|
|
157
|
+
}).join('\n');
|
|
158
|
+
}
|
|
159
|
+
return Object.entries(v as Record<string, unknown>).map(([k, x]) => {
|
|
160
|
+
const one = inline(x);
|
|
161
|
+
return one !== undefined ? `${pad}${keyText(k)}: ${one}` : `${pad}${keyText(k)}:\n${yamlText(x, ind + 2)}`;
|
|
162
|
+
}).join('\n');
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The text after "key:" for a value in block style, the key being at `indent`. */
|
|
166
|
+
function blockValue(v: unknown, indent: number): string {
|
|
167
|
+
if (!isObj(v)) return ' ' + scalarText(v, { flow: false, indent: indent + 2 });
|
|
168
|
+
if (Array.isArray(v) ? !v.length : !Object.keys(v as object).length) return Array.isArray(v) ? ' []' : ' {}';
|
|
169
|
+
if (flowFits(v)) return ' ' + flowText(v);
|
|
170
|
+
return '\n' + reindent(yamlText(v), indent + 2);
|
|
171
|
+
}
|
|
172
|
+
const reindent = (t: string, n: number) => t.split('\n').map(l => (l ? ' '.repeat(n) + l : l)).join('\n');
|
|
173
|
+
|
|
174
|
+
// ---------- the operations ----------
|
|
175
|
+
|
|
176
|
+
/** Set the value at a path (which must exist: use insertKey for a new key). */
|
|
177
|
+
export function setValue(text: string, path: Path, value: unknown): Splice {
|
|
178
|
+
const c = parse(text);
|
|
179
|
+
const f = find(c, path);
|
|
180
|
+
if (f.node === undefined) throw new SpliceError(`no value at ${path.join('.')}`);
|
|
181
|
+
const flow = inFlow(f.chain.slice(0, -1));
|
|
182
|
+
const n = f.node;
|
|
183
|
+
const pairKey = f.pair?.key as YNode | undefined;
|
|
184
|
+
const indent = pairKey?.range ? colOf(text, pairKey.range[0]) : n?.range ? colOf(text, n.range[0]) : 0;
|
|
185
|
+
// a scalar replaced by a scalar: its own range, its own style
|
|
186
|
+
if (isScalar(n) && n.range && !isObj(value) && n.range[1] > n.range[0]) {
|
|
187
|
+
const style = n.type === Scalar.BLOCK_LITERAL || n.type === Scalar.BLOCK_FOLDED ? undefined : n.type;
|
|
188
|
+
let t = scalarText(value, { flow, indent: indent + 2, style });
|
|
189
|
+
let end = n.range[1];
|
|
190
|
+
// a block scalar's range runs to the start of the next line; keep that line break
|
|
191
|
+
if (text[end - 1] === '\n' && !t.endsWith('\n')) { end -= 1; while (end > n.range[0] && text[end - 1] === '\n') end -= 1; }
|
|
192
|
+
if (t.startsWith('|') && !text.slice(n.range[0], end).includes('\n')) {
|
|
193
|
+
// a one-line value becoming a block literal: a comment after it moves onto the "|" line
|
|
194
|
+
const lineE = lineEnd(text, end);
|
|
195
|
+
const trail = text.slice(end, lineE);
|
|
196
|
+
if (/^\s*#/.test(trail)) { t = t.replace(/^(\|-?)/, `$1${trail}`); end = lineE; }
|
|
197
|
+
}
|
|
198
|
+
return { steps: [[{ start: n.range[0], end, text: t }]] };
|
|
199
|
+
}
|
|
200
|
+
if (flow || (isObj(n) && (n as { flow?: boolean }).flow) || !f.pair) {
|
|
201
|
+
// inline: replace the node's text (an empty value: write after the colon)
|
|
202
|
+
if (n?.range && n.range[1] > n.range[0]) {
|
|
203
|
+
const t = flow || !isObj(value) || !f.pair ? (isObj(value) ? flowText(value) : scalarText(value, { flow, indent: indent + 2 })) : null;
|
|
204
|
+
if (t !== null) {
|
|
205
|
+
// a block node's range runs to the start of the next line: keep that line break
|
|
206
|
+
let end = n.range[1];
|
|
207
|
+
while (end > n.range[0] && text[end - 1] === '\n') end -= 1;
|
|
208
|
+
return { steps: [[{ start: n.range[0], end, text: t }]] };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (!f.pair || !pairKey?.range) return fallback(text, path.slice(0, -1), d => d.setIn(path, value));
|
|
213
|
+
// block: rewrite everything after "key:" up to the value's end
|
|
214
|
+
const colon = text.indexOf(':', pairKey.range[1]);
|
|
215
|
+
const vEnd = n?.range ? n.range[1] : colon + 1;
|
|
216
|
+
const end = text[vEnd - 1] === '\n' ? vEnd - 1 : vEnd;
|
|
217
|
+
// keep a comment on the key's line when the old value started on the next line
|
|
218
|
+
const lineE = lineEnd(text, colon);
|
|
219
|
+
const comment = n?.range && n.range[0] > lineE ? text.slice(colon + 1, lineE) : '';
|
|
220
|
+
const after = /^\s*#/.test(comment) ? comment : '';
|
|
221
|
+
let t = blockValue(value, indent);
|
|
222
|
+
let stop = end;
|
|
223
|
+
if (after && t.startsWith('\n')) t = after + t;
|
|
224
|
+
else if (after) t = t + after;
|
|
225
|
+
else if (t.startsWith('\n') && end <= lineE) {
|
|
226
|
+
// the old value was on the key's line with a comment after it: the comment stays on the key's line
|
|
227
|
+
const trail = text.slice(end, lineE);
|
|
228
|
+
if (/^\s*#/.test(trail)) { t = trail + t; stop = lineE; }
|
|
229
|
+
}
|
|
230
|
+
return { steps: [[{ start: colon + 1, end: stop, text: t }]] };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Add `key: value` to the map at a path (creating the map, and its parents, when missing). order: the format's
|
|
234
|
+
* top-level key order, for where a new top-level key goes (the adapter's topOrder). */
|
|
235
|
+
export function insertKey(text: string, mapPath: Path, key: string, value: unknown, opts: { after?: string; before?: string; order?: readonly string[] } = {}): Splice {
|
|
236
|
+
const TOP_ORDER = opts.order ?? [];
|
|
237
|
+
const c = parse(text);
|
|
238
|
+
const f = find(c, mapPath);
|
|
239
|
+
if (f.node === undefined || f.node === null || (isScalar(f.node) && f.node.value === null)) {
|
|
240
|
+
// the map isn't there: write it with this one key
|
|
241
|
+
if (!mapPath.length) {
|
|
242
|
+
const t = `${keyText(key)}:${blockValue(value, 0)}\n`;
|
|
243
|
+
return { steps: [[{ start: text.length, end: text.length, text: (text && !text.endsWith('\n') ? '\n' : '') + t }]] };
|
|
244
|
+
}
|
|
245
|
+
if (f.node === undefined) return insertKey(text, mapPath.slice(0, -1), String(mapPath[mapPath.length - 1]), { [key]: value }, { order: opts.order });
|
|
246
|
+
return setValue(text, mapPath, { [key]: value });
|
|
247
|
+
}
|
|
248
|
+
const map = f.node;
|
|
249
|
+
if (!isMap(map)) throw new SpliceError(`${mapPath.join('.') || 'the file'} is not a map`);
|
|
250
|
+
if (map.items.some(p => keyOf(p) === key)) throw new SpliceError(`"${key}" is already in ${mapPath.join('.') || 'the file'}`);
|
|
251
|
+
const flow = (map as { flow?: boolean }).flow || inFlow(f.chain.slice(0, -1));
|
|
252
|
+
const items = map.items as Pair[];
|
|
253
|
+
// where it goes: after a named key, before a named key, in the spec's order at the top, else at the end
|
|
254
|
+
let at = items.length;
|
|
255
|
+
if (opts.after !== undefined) at = items.findIndex(p => keyOf(p) === opts.after) + 1 || items.length;
|
|
256
|
+
else if (opts.before !== undefined) { const i = items.findIndex(p => keyOf(p) === opts.before); if (i >= 0) at = i; }
|
|
257
|
+
else if (!mapPath.length && TOP_ORDER.includes(key)) {
|
|
258
|
+
const rank = TOP_ORDER.indexOf(key);
|
|
259
|
+
const i = items.findIndex(p => { const r = TOP_ORDER.indexOf(keyOf(p)); return r > rank || keyOf(p).startsWith('x-'); });
|
|
260
|
+
if (i >= 0) at = i;
|
|
261
|
+
}
|
|
262
|
+
if (flow && map.range && text[map.range[0]] !== '{') {
|
|
263
|
+
// an implicit one-pair map inside a flow list ([terminal: 3]): it becomes { terminal: 3, key: v }
|
|
264
|
+
const now = (c.doc.getIn(mapPath, true) as { toJSON(): Record<string, unknown> }).toJSON();
|
|
265
|
+
return { steps: [[{ start: map.range[0], end: map.range[1], text: flowText({ ...now, [key]: value }) }]] };
|
|
266
|
+
}
|
|
267
|
+
if (flow) {
|
|
268
|
+
const t = `${keyText(key)}: ${flowText(value)}`;
|
|
269
|
+
if (!items.length) { const r = map.range!; return { steps: [[{ start: r[0], end: text.lastIndexOf('}', r[1]) + 1, text: `{ ${t} }` }]] }; }
|
|
270
|
+
if (at < items.length) { const k = (items[at].key as YNode).range![0]; return { steps: [[{ start: k, end: k, text: `${t}, ` }]] }; }
|
|
271
|
+
const last = items[items.length - 1];
|
|
272
|
+
const e = (last.value as YNode | null)?.range?.[1] ?? (last.key as YNode).range![1];
|
|
273
|
+
return { steps: [[{ start: e, end: e, text: `, ${t}` }]] };
|
|
274
|
+
}
|
|
275
|
+
// block
|
|
276
|
+
const first = items[0]?.key as YNode | undefined;
|
|
277
|
+
if (!first?.range) return fallback(text, mapPath, d => d.setIn([...mapPath, key], value), true);
|
|
278
|
+
const indent = colOf(text, first.range[0]);
|
|
279
|
+
if (items.some(p => !firstOnLine(text, (p.key as YNode).range![0]))) {
|
|
280
|
+
// a key that shares its line with something else: re-serialise the map
|
|
281
|
+
return fallback(text, mapPath, d => d.setIn([...mapPath, key], value), true);
|
|
282
|
+
}
|
|
283
|
+
const body = `${' '.repeat(indent)}${keyText(key)}:${blockValue(value, indent)}\n`;
|
|
284
|
+
// a new section at the top gets a blank line before it, like the others
|
|
285
|
+
const blank = !mapPath.length && isObj(value) ? '\n' : '';
|
|
286
|
+
if (at === 0 && items.length && onDash(text, first.range[0])) {
|
|
287
|
+
// before the key on a list item's "- " line: the new key takes that place, the old one moves down
|
|
288
|
+
const k = first.range[0];
|
|
289
|
+
return { steps: [[{ start: k, end: k, text: body.slice(indent) + ' '.repeat(indent) }]] };
|
|
290
|
+
}
|
|
291
|
+
if (at < items.length) {
|
|
292
|
+
const s = pairStart(c, items[at]);
|
|
293
|
+
return { steps: [[{ start: s, end: s, text: blank && at > 0 ? body + '\n' : body }]] };
|
|
294
|
+
}
|
|
295
|
+
const end = pairEnd(c, items[items.length - 1]);
|
|
296
|
+
const pre = end === text.length && text.length && !text.endsWith('\n') ? '\n' : '';
|
|
297
|
+
return { steps: [[{ start: end, end, text: pre + blank + body }]] };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Remove the entry at a path: a key and its value (with its own comment lines), or a list item. */
|
|
301
|
+
export function deleteAt(text: string, path: Path): Splice {
|
|
302
|
+
if (!path.length) throw new SpliceError('can\'t delete the whole file');
|
|
303
|
+
const c = parse(text);
|
|
304
|
+
const parentPath = path.slice(0, -1);
|
|
305
|
+
const pf = find(c, parentPath);
|
|
306
|
+
const coll = pf.node;
|
|
307
|
+
const seg = path[path.length - 1];
|
|
308
|
+
if (!isMap(coll) && !isSeq(coll)) throw new SpliceError(`no entry at ${path.join('.')}`);
|
|
309
|
+
const items = coll.items as unknown[];
|
|
310
|
+
const i = isMap(coll) ? (items as Pair[]).findIndex(p => keyOf(p) === String(seg)) : Number(seg);
|
|
311
|
+
if (i < 0 || i >= items.length) throw new SpliceError(`no entry at ${path.join('.')}`);
|
|
312
|
+
const flow = (coll as { flow?: boolean }).flow;
|
|
313
|
+
const startOf = (x: unknown) => (isPair(x) ? (x.key as YNode).range![0] : (x as YNode).range![0]);
|
|
314
|
+
const endOf = (x: unknown) => (isPair(x) ? ((x.value as YNode | null)?.range?.[1] ?? (x.key as YNode).range![1]) : (x as YNode).range![1]);
|
|
315
|
+
if (items.length === 1) {
|
|
316
|
+
// the last entry: the collection becomes empty ({} or []), on its parent's line
|
|
317
|
+
// the file's last key: its lines go; comments elsewhere stay (an empty document reads as nothing)
|
|
318
|
+
if (!parentPath.length && isMap(coll) && !(coll as { flow?: boolean }).flow) return { steps: [[{ start: pairStart(c, items[0] as Pair), end: pairEnd(c, items[0] as Pair), text: '' }]] };
|
|
319
|
+
if (!parentPath.length) return { steps: [[{ start: 0, end: text.length, text: '' }]] };
|
|
320
|
+
return setValue(text, parentPath, isMap(coll) ? {} : []);
|
|
321
|
+
}
|
|
322
|
+
if (flow) {
|
|
323
|
+
if (i < items.length - 1) return { steps: [[{ start: startOf(items[i]), end: startOf(items[i + 1]), text: '' }]] };
|
|
324
|
+
return { steps: [[{ start: endOf(items[i - 1]), end: endOf(items[i]), text: '' }]] };
|
|
325
|
+
}
|
|
326
|
+
if (isMap(coll)) {
|
|
327
|
+
const p = items[i] as Pair;
|
|
328
|
+
const k = (p.key as YNode).range![0];
|
|
329
|
+
if (!firstOnLine(text, k)) return fallback(text, parentPath, d => d.deleteIn(path), true);
|
|
330
|
+
// the key on a list item's "- " line: the next key moves up into its place
|
|
331
|
+
if (onDash(text, k)) return { steps: [[{ start: k, end: (items[i + 1] as Pair | undefined) ? ((items[i + 1] as Pair).key as YNode).range![0] : pairEnd(c, p), text: '' }]] };
|
|
332
|
+
return { steps: [[{ start: pairStart(c, p), end: pairEnd(c, p), text: '' }]] };
|
|
333
|
+
}
|
|
334
|
+
// a block list item: its "- " line(s)
|
|
335
|
+
const it = items[i] as YNode;
|
|
336
|
+
const s = lineStart(text, it.range![0]);
|
|
337
|
+
if (!/^\s*-/.test(text.slice(s, it.range![0]))) return fallback(text, parentPath, d => d.deleteIn(path), true);
|
|
338
|
+
const e = it.range![1];
|
|
339
|
+
const end = nextLine(text, text[e - 1] === '\n' ? e - 1 : e);
|
|
340
|
+
return { steps: [[{ start: s, end, text: '' }]] };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Add an item to the list at a path, at an index (default: the end). */
|
|
344
|
+
export function insertItem(text: string, listPath: Path, value: unknown, index?: number, order?: readonly string[]): Splice {
|
|
345
|
+
const c = parse(text);
|
|
346
|
+
const f = find(c, listPath);
|
|
347
|
+
if (f.node === undefined || f.node === null || (isScalar(f.node) && f.node.value === null)) {
|
|
348
|
+
if (f.node === undefined) return insertKey(text, listPath.slice(0, -1), String(listPath[listPath.length - 1]), [value], { order });
|
|
349
|
+
return setValue(text, listPath, [value]);
|
|
350
|
+
}
|
|
351
|
+
const list = f.node;
|
|
352
|
+
if (!isSeq(list)) throw new SpliceError(`${listPath.join('.')} is not a list`);
|
|
353
|
+
const items = list.items as YNode[];
|
|
354
|
+
const at = index === undefined ? items.length : Math.max(0, Math.min(index, items.length));
|
|
355
|
+
if ((list as { flow?: boolean }).flow || inFlow(f.chain.slice(0, -1))) {
|
|
356
|
+
const t = flowText(value);
|
|
357
|
+
if (!items.length) { const r = list.range!; const close = text.lastIndexOf(']', r[1]); return { steps: [[{ start: r[0], end: close + 1, text: `[${t}]` }]] }; }
|
|
358
|
+
if (at < items.length) { const s = items[at].range![0]; return { steps: [[{ start: s, end: s, text: `${t}, ` }]] }; }
|
|
359
|
+
const e = items[items.length - 1].range![1];
|
|
360
|
+
return { steps: [[{ start: e, end: e, text: `, ${t}` }]] };
|
|
361
|
+
}
|
|
362
|
+
const first = items[0];
|
|
363
|
+
const dash = lineStart(text, first.range![0]);
|
|
364
|
+
const prefix = text.slice(dash, first.range![0]);
|
|
365
|
+
if (!/^\s*- $/.test(prefix)) return fallback(text, listPath, d => { const s = d.getIn(listPath) as YAMLSeq; s.items.splice(at, 0, d.createNode(value) as never); }, true);
|
|
366
|
+
const indent = prefix.indexOf('-');
|
|
367
|
+
const body = ' '.repeat(indent) + '- ' + (isObj(value) && Object.keys(value as object).length
|
|
368
|
+
? reindent(yamlText(value), indent + 2).slice(indent + 2)
|
|
369
|
+
: scalarText(value, { flow: false, indent: indent + 2 })) + '\n';
|
|
370
|
+
if (at < items.length) { const s = lineStart(text, items[at].range![0]); return { steps: [[{ start: s, end: s, text: body }]] }; }
|
|
371
|
+
const e = items[items.length - 1].range![1];
|
|
372
|
+
const end = nextLine(text, text[e - 1] === '\n' ? e - 1 : e);
|
|
373
|
+
const pre = end === text.length && !text.endsWith('\n') ? '\n' : '';
|
|
374
|
+
return { steps: [[{ start: end, end, text: pre + body }]] };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Rename a key in place. */
|
|
378
|
+
export function renameKey(text: string, path: Path, to: string): Splice {
|
|
379
|
+
const c = parse(text);
|
|
380
|
+
const f = find(c, path);
|
|
381
|
+
if (!f.pair) throw new SpliceError(`no key at ${path.join('.')}`);
|
|
382
|
+
if ((f.parent as YAMLMap).items.some(p => keyOf(p as Pair) === to)) throw new SpliceError(`"${to}" is already there`);
|
|
383
|
+
const k = f.pair.key as YNode;
|
|
384
|
+
return { steps: [[{ start: k.range![0], end: k.range![1], text: keyText(to) }]] };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Move a block map's entry (with its comment lines) to before another key, or to the end. */
|
|
388
|
+
export function moveKey(text: string, path: Path, before?: string, order?: readonly string[]): Splice {
|
|
389
|
+
const c = parse(text);
|
|
390
|
+
const f = find(c, path);
|
|
391
|
+
if (!f.pair || !isMap(f.parent)) throw new SpliceError(`no key at ${path.join('.')}`);
|
|
392
|
+
const map = f.parent;
|
|
393
|
+
const dashy = onDash(text, (f.pair.key as YNode).range![0]) || (map.items as Pair[]).some(p => onDash(text, (p.key as YNode).range![0]));
|
|
394
|
+
if ((map as { flow?: boolean }).flow || dashy) {
|
|
395
|
+
// a flow map, or a list item's map whose first key is on its "- " line: delete, then insert
|
|
396
|
+
const v = (f.pair.value as YNode | null);
|
|
397
|
+
const value = v ? (c.doc.getIn(path) as { toJSON?: () => unknown })?.toJSON?.() ?? c.doc.getIn(path) : null;
|
|
398
|
+
const del = deleteAt(text, path);
|
|
399
|
+
const mid = applyStep(text, del.steps[0]);
|
|
400
|
+
const ins = insertKey(mid, path.slice(0, -1), String(path[path.length - 1]), value, before ? { before, order } : { order });
|
|
401
|
+
return { steps: [...del.steps, ...ins.steps] };
|
|
402
|
+
}
|
|
403
|
+
const s = pairStart(c, f.pair), e = pairEnd(c, f.pair);
|
|
404
|
+
const chunk = text.slice(s, e);
|
|
405
|
+
const target = before ? (map.items as Pair[]).find(p => keyOf(p) === before) : undefined;
|
|
406
|
+
if (target === f.pair) return { steps: [] };
|
|
407
|
+
const at = target ? pairStart(c, target) : pairEnd(c, map.items[map.items.length - 1] as Pair);
|
|
408
|
+
const body = chunk.endsWith('\n') ? chunk : chunk + '\n';
|
|
409
|
+
// one step, in the old text's coordinates: remove here, insert there
|
|
410
|
+
return { steps: [[{ start: s, end: e, text: '' }, { start: at, end: at, text: at === text.length && !text.endsWith('\n') ? '\n' + body : body }]] };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Re-serialise the smallest collection holding the change: the last resort, marked as such. */
|
|
414
|
+
function fallback(text: string, collPath: Path, mutate: (d: Document.Parsed) => void, _structural = false): Splice {
|
|
415
|
+
const c = parse(text);
|
|
416
|
+
const f = find(c, collPath);
|
|
417
|
+
const node = f.node as YNode | undefined;
|
|
418
|
+
mutate(c.doc);
|
|
419
|
+
if (!collPath.length || !node?.range) return { steps: [[{ start: 0, end: text.length, text: c.doc.toString({ lineWidth: 0 }) }]], fallback: true };
|
|
420
|
+
const after = c.doc.getIn(collPath, true) as YNode;
|
|
421
|
+
const flow = (node as { flow?: boolean }).flow;
|
|
422
|
+
const one = new Document();
|
|
423
|
+
one.contents = after as never;
|
|
424
|
+
let t = one.toString({ lineWidth: 0, indent: 2 }).replace(/\n$/, '');
|
|
425
|
+
const r = node.range;
|
|
426
|
+
if (flow) return { steps: [[{ start: r[0], end: r[1], text: t.replace(/\n\s*/g, ' ') }]], fallback: true };
|
|
427
|
+
const s = lineStart(text, r[0]);
|
|
428
|
+
const ind = r[0] - s;
|
|
429
|
+
const e = r[1] > 0 && text[r[1] - 1] === '\n' ? r[1] - 1 : lineEnd(text, r[1]);
|
|
430
|
+
t = reindent(t, ind).slice(text.slice(s, r[0]).trim() ? ind : 0);
|
|
431
|
+
return { steps: [[{ start: text.slice(s, r[0]).trim() ? r[0] : s, end: e, text: t }]], fallback: true };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export type { Seg };
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Add a pair given as source text ("key: value", with its own comments, at indent 0) to the map at a path, re-indented
|
|
438
|
+
* to the map's; the text, comments and all, is kept. A flow map (or one the splices can't place a line in) takes the
|
|
439
|
+
* value's data instead. The map must exist (insertKey makes a missing one).
|
|
440
|
+
*/
|
|
441
|
+
export function insertRawPair(text: string, mapPath: Path, key: string, pairText: string, order?: readonly string[]): Splice {
|
|
442
|
+
const c = parse(text);
|
|
443
|
+
const f = find(c, mapPath);
|
|
444
|
+
const map = f.node;
|
|
445
|
+
const value = (parseDocument(pairText).toJS() as Record<string, unknown> | null)?.[key];
|
|
446
|
+
if (!isMap(map) || (map as { flow?: boolean }).flow || inFlow(f.chain.slice(0, -1)) || !map.items.length) return insertKey(text, mapPath, key, value, { order });
|
|
447
|
+
const items = map.items as Pair[];
|
|
448
|
+
const first = items[0].key as YNode;
|
|
449
|
+
if (!first.range || items.some(p => !firstOnLine(text, (p.key as YNode).range![0]) || onDash(text, (p.key as YNode).range![0]))) return insertKey(text, mapPath, key, value, { order });
|
|
450
|
+
if (items.some(p => keyOf(p) === key)) throw new SpliceError(`"${key}" is already in ${mapPath.join('.') || 'the file'}`);
|
|
451
|
+
const indent = colOf(text, first.range[0]);
|
|
452
|
+
const body = reindent(pairText.replace(/\n+$/, ''), indent) + '\n';
|
|
453
|
+
const end = pairEnd(c, items[items.length - 1]);
|
|
454
|
+
const pre = end === text.length && text.length && !text.endsWith('\n') ? '\n' : '';
|
|
455
|
+
return { steps: [[{ start: end, end, text: pre + body }]] };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** A pair's source text (its own comment lines, the key and its value, a comment after it), at indent 0. */
|
|
459
|
+
export function pairText(text: string, path: Path): string | undefined {
|
|
460
|
+
const c = parse(text);
|
|
461
|
+
const f = find(c, path);
|
|
462
|
+
if (!f.pair || !isMap(f.parent)) return undefined;
|
|
463
|
+
const k = (f.pair.key as YNode).range![0];
|
|
464
|
+
if ((f.parent as { flow?: boolean }).flow || inFlow(f.chain.slice(0, -1)) || !firstOnLine(text, k) || onDash(text, k)) {
|
|
465
|
+
const v = c.doc.getIn(path, true) as { toJSON?: () => unknown } | null;
|
|
466
|
+
const value = v && typeof v === 'object' && v.toJSON ? v.toJSON() : c.doc.getIn(path);
|
|
467
|
+
return `${keyText(String(path[path.length - 1]))}:${blockValue(value, 0)}\n`;
|
|
468
|
+
}
|
|
469
|
+
const s = pairStart(c, f.pair), e = pairEnd(c, f.pair);
|
|
470
|
+
const ind = colOf(text, k);
|
|
471
|
+
return text.slice(s, e).split('\n').map(l => (l.slice(0, ind).trim() === '' ? l.slice(ind) : l.trimStart())).join('\n').replace(/\n*$/, '\n');
|
|
472
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// v0.4.1: the editor's storage keys that hosts rely on (a stable contract; docs/editor/INTEGRATION.md, "Storage").
|
|
2
|
+
// A host's watch view reads and writes them. Renaming one is a breaking change: test/storage-keys.test.ts pins them.
|
|
3
|
+
// view 'text' | 'both' | 'canvas': the view the viewer chose (written when they choose one)
|
|
4
|
+
// live '1' while Live is on; removed when it goes off
|
|
5
|
+
export const PREF = { view: 'view', live: 'live' } as const;
|
|
6
|
+
export const VIEWS = ['text', 'both', 'canvas'] as const;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Actions the canvas and the properties panel share (the tree has its own inline forms of the same commands): delete
|
|
2
|
+
// with a references dialog, rename in a dialog, duplicate, select connected. What an object is and how it is named
|
|
3
|
+
// are the kit's (the domain's commands, objectOf, kinds and name rule); what each kind offers in its own menu is the
|
|
4
|
+
// domain's too.
|
|
5
|
+
|
|
6
|
+
import { h } from './icons.ts';
|
|
7
|
+
import { ask } from './dialog.ts';
|
|
8
|
+
import type { EditorModel, Command } from '../model.ts';
|
|
9
|
+
import type { Commands } from '../commands.ts';
|
|
10
|
+
import type { ObjectKindInfo, ObjectRef } from '../adapter.ts';
|
|
11
|
+
import { applyStep } from '../splice.ts';
|
|
12
|
+
import { fromPointer, isPrefix, toPointer, type Path } from '../path.ts';
|
|
13
|
+
|
|
14
|
+
type Raw = Record<string, unknown>;
|
|
15
|
+
const getIn = (o: unknown, p: Path) => p.reduce<unknown>((x, k) => (x && typeof x === 'object' ? (x as Raw)[k as string] : undefined), o);
|
|
16
|
+
|
|
17
|
+
/** what the shared actions are given of the domain */
|
|
18
|
+
export interface ActionsKit {
|
|
19
|
+
commands: Pick<Commands, 'deleteCmd' | 'renameCmd' | 'renameKeyCmd' | 'referencesTo' | 'describe' | 'duplicateCmd'>;
|
|
20
|
+
objectOf(ptr: string): ObjectRef | undefined;
|
|
21
|
+
kinds: ObjectKindInfo[];
|
|
22
|
+
nameRule: RegExp;
|
|
23
|
+
nameHint: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function run(doc: EditorModel, c: Command, origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void): boolean {
|
|
27
|
+
try { return doc.apply(c, origin); } catch (e) { note?.(String((e as Error).message), 'bad'); return false; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Several commands as one undo step. */
|
|
31
|
+
export function composite(label: string, cmds: Command[]): Command {
|
|
32
|
+
return {
|
|
33
|
+
label,
|
|
34
|
+
remap: p => cmds.reduce<Path | null>((x, c) => (x && c.remap ? c.remap(x) : x), p),
|
|
35
|
+
build: t => {
|
|
36
|
+
const steps = [];
|
|
37
|
+
let fallback = false;
|
|
38
|
+
for (const c of cmds) { const s = c.build(t); for (const st of s.steps) { steps.push(st); t = applyStep(t, st); } fallback ||= !!s.fallback; }
|
|
39
|
+
return { steps, fallback };
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The shared actions, for one domain. */
|
|
45
|
+
export function actionsFor(kit: ActionsKit) {
|
|
46
|
+
const { deleteCmd, renameCmd, renameKeyCmd, referencesTo, describe, duplicateCmd } = kit.commands;
|
|
47
|
+
const isRes = (p: Path) => { const r = kit.objectOf(toPointer(p)); return !!r && r.path === toPointer(p); };
|
|
48
|
+
|
|
49
|
+
/** Delete paths; when something refers to an object being deleted, ask whether its references go too. */
|
|
50
|
+
async function deletePaths(doc: EditorModel, paths: Path[], origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void): Promise<boolean> {
|
|
51
|
+
const top = paths.filter(p => p.length && !paths.some(o => o !== p && o.length < p.length && isPrefix(o, p)));
|
|
52
|
+
if (!top.length) return false;
|
|
53
|
+
const refs = top.filter(isRes).flatMap(p => { const r = kit.objectOf(toPointer(p))!; return referencesTo(doc.text, r.kind, r.name).filter(x => !top.some(o => isPrefix(o, fromPointer(x.path)))).map(x => ({ p, x })); });
|
|
54
|
+
let withRefs = false;
|
|
55
|
+
if (refs.length) {
|
|
56
|
+
const choice = await ask(`Delete ${top.length === 1 ? describe(top[0]) : `${top.length} items`}?`, [
|
|
57
|
+
h('p', { class: 'sub' }, `${refs.length === 1 ? 'One place refers' : `${refs.length} places refer`} to ${top.length === 1 ? 'it' : 'them'}:`),
|
|
58
|
+
h('ul', { class: 'ref-list' }, ...refs.map(({ x }) => h('li', null, h('code', null, x.path.slice(1).replace(/\//g, '.')), ` — ${x.slot.what}`))),
|
|
59
|
+
h('p', { class: 'sub' }, 'Delete the references too, or leave them (the problems list will show them). Either way, Undo brings everything back.'),
|
|
60
|
+
], [{ label: 'Cancel', value: 'cancel' }, { label: 'Delete only', value: 'only', danger: true }, { label: 'Delete with references', value: 'with', danger: true, primary: true }]);
|
|
61
|
+
if (!choice) return false;
|
|
62
|
+
withRefs = choice === 'with';
|
|
63
|
+
}
|
|
64
|
+
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));
|
|
65
|
+
const cmds = order.map(p => deleteCmd(p, { withRefs: withRefs && isRes(p) }));
|
|
66
|
+
const ok = run(doc, cmds.length === 1 ? cmds[0] : composite(`Delete ${top.length} items`, cmds), origin, note);
|
|
67
|
+
if (ok) doc.select([], origin);
|
|
68
|
+
return ok;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Rename in a dialog (the canvas has no inline field). */
|
|
72
|
+
async function renameDialog(doc: EditorModel, path: Path, origin: 'canvas' | 'props' | 'menu', note?: (t: string, tone?: 'bad') => void): Promise<boolean> {
|
|
73
|
+
const now = String(path[path.length - 1]);
|
|
74
|
+
const input = h('input', { type: 'text', value: now, 'aria-label': 'New name', spellcheck: 'false', autocomplete: 'off', class: 'mono-input' });
|
|
75
|
+
input.value = now;
|
|
76
|
+
const why = h('p', { class: 'dlg-error', role: 'alert' });
|
|
77
|
+
const used = () => kit.kinds.flatMap(k => Object.keys((getIn(doc.goodDoc.data, k.section) ?? {}) as Raw));
|
|
78
|
+
const check = () => {
|
|
79
|
+
const v = input.value.trim();
|
|
80
|
+
const bad = !kit.nameRule.test(v) && isRes(path) ? kit.nameHint : v !== now && used().includes(v) ? `"${v}" is already used` : '';
|
|
81
|
+
why.textContent = bad;
|
|
82
|
+
return bad ? undefined : v;
|
|
83
|
+
};
|
|
84
|
+
input.addEventListener('input', check);
|
|
85
|
+
const go = ask(`Rename ${describe(path)}`, [h('label', { class: 'field' }, h('span', null, 'Name'), input), why, isRes(path) ? h('p', { class: 'sub' }, 'Every reference to it is renamed too.') : ''], [{ label: 'Cancel', value: 'cancel' }, { label: 'Rename', value: 'ok', primary: true }]);
|
|
86
|
+
setTimeout(() => { input.focus(); input.select(); }, 0);
|
|
87
|
+
if (await go !== 'ok') return false;
|
|
88
|
+
const v = check();
|
|
89
|
+
if (!v || v === now) return false;
|
|
90
|
+
return run(doc, isRes(path) ? renameCmd(path, v) : renameKeyCmd(path, v), origin, note);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const duplicate = (doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void) => {
|
|
94
|
+
const c = duplicateCmd(path);
|
|
95
|
+
if (run(doc, c, origin, note) && c.select) doc.select(c.select, origin);
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
/** Paths linked to these by references, both ways (select connected). */
|
|
99
|
+
function connected(doc: EditorModel, paths: Path[]): Path[] {
|
|
100
|
+
const out = new Map<string, Path>();
|
|
101
|
+
for (const p of paths) {
|
|
102
|
+
const r = kit.objectOf(toPointer(p));
|
|
103
|
+
if (!r) continue;
|
|
104
|
+
out.set(r.path, fromPointer(r.path));
|
|
105
|
+
// what refers to it
|
|
106
|
+
for (const x of referencesTo(doc.text, r.kind, r.name)) { const q = kit.objectOf(x.path); out.set(q ? q.path : x.path, fromPointer(q ? q.path : x.path)); }
|
|
107
|
+
// what it refers to
|
|
108
|
+
const v = getIn(doc.goodDoc.data, fromPointer(r.path)) as Raw | undefined;
|
|
109
|
+
const names: string[] = JSON.stringify(v ?? {}).match(/[a-z][a-z0-9-]*/g) ?? [];
|
|
110
|
+
for (const k of kit.kinds) for (const n of Object.keys((getIn(doc.goodDoc.data, k.section) ?? {}) as Raw)) {
|
|
111
|
+
if (names.includes(n) && n !== r.name) { const q = toPointer([...k.section, n]); out.set(q, fromPointer(q)); }
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return [...out.values()];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return { deletePaths, renameDialog, duplicate, connected };
|
|
118
|
+
}
|
|
119
|
+
export type Actions = ReturnType<typeof actionsFor>;
|