@johnoscott/isometric-engine 0.0.0-stage → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EDITOR-GUIDE.md +355 -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 +269 -0
- package/assets/default-theme.yaml +99 -0
- package/assets/icons.svg +1 -0
- package/assets/marks.css +39 -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 +443 -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 +1403 -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 +149 -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 +511 -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 +147 -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 +477 -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 +1227 -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 +39 -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 +153 -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 +178 -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 +307 -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 +49 -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,1227 @@
|
|
|
1
|
+
// The canvas: the file drawn by the drawing engine (the kit's draw()), editable.
|
|
2
|
+
// - Selection: click, ⇧-click or ⌘-click to add or remove, a marquee drag on empty canvas (⌥: touching is enough),
|
|
3
|
+
// ⌘↑ the parent, rings in the skin's accent. Shared with the tree and the text through the model.
|
|
4
|
+
// - Pan and zoom: the wheel pans, a pinch or ⌘/Ctrl-wheel zooms around the pointer, space-drag or middle-drag pans;
|
|
5
|
+
// + − zoom, 0 fits, 1 is 100%, ⇧2 zooms to the selection; 10%–800%.
|
|
6
|
+
// - Pins: drag a selected thing to pin it to the grid; the pin is x-editor.layout.NAME.at in the file.
|
|
7
|
+
// - Right-click: the menu of what is under the pointer (or of the canvas).
|
|
8
|
+
// The drawing is in the page itself (E9): an <svg> built with DOM calls from the renderer's output (svg-dom.ts, never
|
|
9
|
+
// innerHTML), styled by the host's canvas CSS, which scopes the diagram's CSS under the kit's root class and names its
|
|
10
|
+
// tokens --iso-*, so it never meets the page's. No frame: the pointer's coordinates are the page's.
|
|
11
|
+
// - The kit (CanvasKit) is the domain: how a file is drawn, its objects and kinds, its commands and pins, what
|
|
12
|
+
// the palette offers and what a drop into a container makes, and the words.
|
|
13
|
+
|
|
14
|
+
import { h, icon, type IconName } from './icons.ts';
|
|
15
|
+
import { openMenu, type MenuItem } from './menu.ts';
|
|
16
|
+
import { run, type Actions } from './actions.ts';
|
|
17
|
+
import { screenToGrid, localAt, boxSilhouette, floorOf, snapMove, overlaps, paddingOf, type Move } from '../../iso-objects/geometry.ts';
|
|
18
|
+
import { regionKind, type KindCatalog } from '../../iso-objects/kinds.ts';
|
|
19
|
+
import type { CompiledScene } from '../../iso-objects/compile.ts';
|
|
20
|
+
import { iso, C, S } from '../../iso-core/kernel.ts';
|
|
21
|
+
import type { EditorModel, Command } from '../model.ts';
|
|
22
|
+
import type { Problem } from '../validate.ts';
|
|
23
|
+
import { applyStep } from '../splice.ts';
|
|
24
|
+
import { seqCmd, type Commands } from '../commands.ts';
|
|
25
|
+
import type { ObjectKindInfo, ObjectRef, ConnectPlan, GroupPlan } from '../adapter.ts';
|
|
26
|
+
import { fromPointer, toPointer, type Path } from '../path.ts';
|
|
27
|
+
import { buildSvg } from '../../iso-core/svg-dom.ts';
|
|
28
|
+
import { viewport, type View } from '../../iso-viewer/viewport.ts';
|
|
29
|
+
import type { CanvasCtx, CanvasLayer } from './canvas-layer.ts';
|
|
30
|
+
import type { FlatStyle } from '../../iso-viewer/flat-view.ts';
|
|
31
|
+
import type { FlatOptions } from '../../iso-objects/flat.ts';
|
|
32
|
+
import type { SvgMorph } from '../../iso-viewer/morph.ts';
|
|
33
|
+
|
|
34
|
+
/** what the canvas draws: the domain's drawn document */
|
|
35
|
+
export interface CanvasDrawing {
|
|
36
|
+
scene: CompiledScene;
|
|
37
|
+
/** the frame: the scene's SVG */
|
|
38
|
+
svg: string;
|
|
39
|
+
/** data-id → the JSON pointer in the file it shows */
|
|
40
|
+
pathOf: Map<string, string>;
|
|
41
|
+
/** object name → the id of the element a pin moves */
|
|
42
|
+
pinId: Map<string, string>;
|
|
43
|
+
/** pins that couldn't apply, with why */
|
|
44
|
+
pinNotes: string[];
|
|
45
|
+
diags: string[];
|
|
46
|
+
}
|
|
47
|
+
/** a scene drawn in 2D, as the canvas uses it (flat-canvas.ts makes it) */
|
|
48
|
+
export interface FlatDrawn {
|
|
49
|
+
svg: string;
|
|
50
|
+
/** its viewBox */
|
|
51
|
+
full: [number, number, number, number];
|
|
52
|
+
/** the layout (for tests) */
|
|
53
|
+
layout: unknown;
|
|
54
|
+
/** the outlines of these drawn ids: a card's or a panel's rect, a link's path */
|
|
55
|
+
outlines(ids: Set<string>, svg: SVGSVGElement): ({ kind: 'poly'; id: string; points: [number, number][] } | { kind: 'route'; d: string })[];
|
|
56
|
+
/** the ids of the cards and panels in a rectangle (or touching it) */
|
|
57
|
+
hits(r: { l: number; t: number; r: number; b: number }, touch: boolean): string[];
|
|
58
|
+
/** the panels under a point, innermost first */
|
|
59
|
+
panelsAt(x: number, y: number): string[];
|
|
60
|
+
}
|
|
61
|
+
/** the 2D view's implementation, handed to the canvas by its host */
|
|
62
|
+
export interface FlatCanvas {
|
|
63
|
+
draw(scene: CompiledScene, stage: Element, o: { styles?: Record<string, FlatStyle>; title?: string; options?: Partial<FlatOptions> }): FlatDrawn;
|
|
64
|
+
/** (0.7.5) the switch's morph, from the view on the stage to the other, both laid out in `root`: undefined when it
|
|
65
|
+
* shouldn't animate (the motion option, reduced motion); the canvas shows and hides the two drawings itself */
|
|
66
|
+
morph?(root: HTMLElement, scene: CompiledScene, from: { svg: SVGSVGElement; mode: '3d' | '2d' }, to: SVGSVGElement,
|
|
67
|
+
o: { duration?: number; motion?: 'auto' | 'always' | 'never' }): SvgMorph | undefined;
|
|
68
|
+
}
|
|
69
|
+
/** a drop into a container: what the new object is made as, and the words for it */
|
|
70
|
+
export interface DropInto { container: string; value(container: string): unknown; label(container: string): string }
|
|
71
|
+
/** the canvas's words and names */
|
|
72
|
+
export interface CanvasUi {
|
|
73
|
+
/** the stage's class (the host's canvas CSS is scoped under it), and the drawing's class while the space key is down */
|
|
74
|
+
rootClass: string; panKeyClass: string;
|
|
75
|
+
/** the kinds the canvas's menu offers, in order */
|
|
76
|
+
newOrder: string[];
|
|
77
|
+
/** the palette's entries: a kind, and (0.10.0) a preset: what a new one starts as (default: the kind's template) and
|
|
78
|
+
* the base of its fresh name (default: the kind's singular) */
|
|
79
|
+
palette: PaletteItem[];
|
|
80
|
+
text: {
|
|
81
|
+
stage: string; dragGroup: string; dragSelectTip: string; unreadable: string; palette: string;
|
|
82
|
+
/** the end of a pin drag's hint */
|
|
83
|
+
pinHint: string; renameWhy: string; duplicateWhy: string;
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export interface PaletteItem { kind: string; icon: IconName; label: string; value?(): unknown; name?: string }
|
|
87
|
+
/** what the canvas is given of the domain (M: the domain's reading of the file; D: its drawing) */
|
|
88
|
+
export interface CanvasKit<M, D extends CanvasDrawing> {
|
|
89
|
+
draw(model: M, data: unknown, theme: string): D;
|
|
90
|
+
/** the drawing a text would be (a trial: where a drop lands), or undefined */
|
|
91
|
+
trial(text: string, theme: string): D | undefined;
|
|
92
|
+
catalog: KindCatalog;
|
|
93
|
+
objectOf(ptr: string): ObjectRef | undefined;
|
|
94
|
+
kinds: ObjectKindInfo[];
|
|
95
|
+
commands: Pick<Commands, 'setCmd' | 'deleteCmd' | 'insertCmd' | 'insertItemCmd' | 'pinsCmd' | 'withPinsMoved' | 'describe' | 'freshName'>;
|
|
96
|
+
/** (0.10.0) a connection drawn from one object to another (the adapter's connect): the canvas offers the gesture (a
|
|
97
|
+
* handle on a selected object, and "Connect to…") only when it is given */
|
|
98
|
+
connect?(from: ObjectRef, to: ObjectRef, data: unknown): ConnectPlan | undefined;
|
|
99
|
+
/** (0.10.1) a palette drop onto an object (the adapter's dropInto): the new thing inside it, asked innermost first */
|
|
100
|
+
dropOnto?(target: ObjectRef, value: unknown, kind: string, data: unknown): { value: unknown; label?: string } | undefined;
|
|
101
|
+
/** (0.10.0) the selection made into a new container (the adapter's group): Group, ⌘G, one undo step */
|
|
102
|
+
group?(members: ObjectRef[], data: unknown): GroupPlan | undefined;
|
|
103
|
+
actions: Actions;
|
|
104
|
+
/** what an object's own menu offers, beyond rename, duplicate and delete */
|
|
105
|
+
objectItems(doc: EditorModel, path: Path, origin: 'canvas' | 'menu', note?: (t: string, tone?: 'bad') => void): MenuItem[];
|
|
106
|
+
pins: { key: string; legacyKey?: string; of(data: unknown): Record<string, unknown> | undefined; keyOf(data: unknown): string; legacyOnly(data: unknown): boolean };
|
|
107
|
+
/** the 2D view (0.6.4): offered as a 3D | 2D switch when given. `load` hands over its implementation (flat-canvas.ts;
|
|
108
|
+
* the canvas never names it, so a host without a 2D view bundles none of it). In 2D, selecting, the menu, renaming,
|
|
109
|
+
* deleting, adding from the palette (into a panel, or placed by the layout) and undo work as in 3D; pins (moving)
|
|
110
|
+
* are 3D only. The host's canvas CSS has the 2D view's (flatCss), scoped as the drawing's is. */
|
|
111
|
+
flat?: { load(): Promise<FlatCanvas>; styles?: Record<string, FlatStyle>; title?: string; options?: Partial<FlatOptions>;
|
|
112
|
+
/** (0.7.5) the switch morphs, as dualView does: 'auto' (the default) honours prefers-reduced-motion, 'always' morphs
|
|
113
|
+
* regardless, 'never' swaps at once; `duration` in ms (600) */
|
|
114
|
+
motion?: 'auto' | 'always' | 'never'; duration?: number };
|
|
115
|
+
/** a drop of this kind onto a container's floor (none: it is pinned where it drops) */
|
|
116
|
+
dropInto?(kind: string): DropInto | undefined;
|
|
117
|
+
ui: CanvasUi;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface CanvasOpts<M, D extends CanvasDrawing, A extends object = object> {
|
|
121
|
+
kit: CanvasKit<M, D>;
|
|
122
|
+
theme: string;
|
|
123
|
+
problems(): Problem[];
|
|
124
|
+
note(t: string, tone?: 'info' | 'warn' | 'bad'): void;
|
|
125
|
+
showInText(p: Path): void;
|
|
126
|
+
showInTree(p: Path): void;
|
|
127
|
+
onZoom(pct: number): void;
|
|
128
|
+
/** the navigation modes, for the status bar */
|
|
129
|
+
onHint?(text: string): void;
|
|
130
|
+
/** Copy, Cut and Paste for the menu */
|
|
131
|
+
clipItems?(): MenuItem[];
|
|
132
|
+
/** where the navigation modes are kept between visits (the host's storage); none: for this mount only */
|
|
133
|
+
store?: { get(k: string): string | null; set(k: string, v: string | null): void };
|
|
134
|
+
/** a layer over the drawing (none: the drawing and its marks only) */
|
|
135
|
+
layer?: (ctx: CanvasCtx<D>) => CanvasLayer<A>;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const SVGNS = 'http://www.w3.org/2000/svg';
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
export function canvasView<M, D extends CanvasDrawing, A extends object = object>(host: HTMLElement, doc: EditorModel, opts: CanvasOpts<M, D, A>) {
|
|
142
|
+
const K = opts.kit, ui = K.ui, T = ui.text;
|
|
143
|
+
const { setCmd, deleteCmd, insertCmd, insertItemCmd, pinsCmd, withPinsMoved, freshName, describe } = K.commands;
|
|
144
|
+
const { deletePaths, renameDialog, duplicate, connected } = K.actions;
|
|
145
|
+
const resourceOf = (ptr: string) => K.objectOf(ptr);
|
|
146
|
+
const kindOf = (k: string) => K.kinds.find(x => x.kind === k)!;
|
|
147
|
+
const PINS_KEY = K.pins.key;
|
|
148
|
+
/** (0.10.0) a connection being drawn: from what, the pointer (in the drawing's coordinates), what it is over; `pick`:
|
|
149
|
+
* started from the menu, so the next click ends it */
|
|
150
|
+
let linking: { from: ObjectRef; x?: number; y?: number; over?: string; pick?: boolean } | undefined;
|
|
151
|
+
host.classList.add('canvas');
|
|
152
|
+
// the stage holds the drawing, and takes the focus, the keys and the pointer
|
|
153
|
+
const stage = h('div', { class: `${ui.rootClass} canvas-stage`, tabindex: '0', role: 'application', 'aria-label': T.stage });
|
|
154
|
+
const tools = h('div', { class: 'canvas-tools', role: 'toolbar', 'aria-label': 'Canvas' });
|
|
155
|
+
const zoomOut = h('button', { type: 'button', class: 'btn sm quiet icon-only', 'aria-label': 'Zoom out (−)', title: 'Zoom out (−)' }, '−');
|
|
156
|
+
const zoomLabel = h('button', { type: 'button', class: 'btn sm quiet zoom-label', title: 'Fit (0) · 100% (1)' }, '100%');
|
|
157
|
+
const zoomIn = h('button', { type: 'button', class: 'btn sm quiet icon-only', 'aria-label': 'Zoom in (+)', title: 'Zoom in (+)' }, '+');
|
|
158
|
+
const fitBtn = h('button', { type: 'button', class: 'btn sm quiet', title: 'Fit (0)' }, 'Fit');
|
|
159
|
+
// navigation: what the wheel does, and what a drag on nothing does (remembered by this browser)
|
|
160
|
+
const seg = (label: string, key: string, values: [string, string, string][]) => {
|
|
161
|
+
const g = h('div', { class: 'segmented', role: 'group', 'aria-label': label, title: label });
|
|
162
|
+
for (const [v, text, tip] of values) {
|
|
163
|
+
const b = h('button', { type: 'button', class: 'seg', 'data-v': v, title: tip }, text);
|
|
164
|
+
b.addEventListener('click', () => { nav[key as 'wheel' | 'drag'] = v as never; saveNav(); paintNav(); });
|
|
165
|
+
g.append(b);
|
|
166
|
+
}
|
|
167
|
+
return g;
|
|
168
|
+
};
|
|
169
|
+
const wheelSeg = seg('The wheel', 'wheel', [['zoom', 'Zoom', 'The wheel zooms around the pointer; ⇧-wheel pans sideways'], ['scroll', 'Scroll', 'The wheel pans; ⇧-wheel pans sideways; a pinch zooms']]);
|
|
170
|
+
const dragSeg = seg(T.dragGroup, 'drag', [['pan', 'Pan', 'Drag pans; ⇧- or ⌘-drag draws a selection'], ['select', 'Select', T.dragSelectTip]]);
|
|
171
|
+
// the view: 3D (the drawing, pins and all) or 2D (its flat layout); offered when the kit has a 2D view
|
|
172
|
+
let mode: '3d' | '2d' = '3d';
|
|
173
|
+
let flat: FlatDrawn | undefined, flatImpl: FlatCanvas | undefined;
|
|
174
|
+
/** the 2D view's implementation, once (the host's to hand over) */
|
|
175
|
+
const loadFlat = async () => (flatImpl ??= await K.flat!.load());
|
|
176
|
+
const viewSeg = h('div', { class: 'segmented view-seg', role: 'group', 'aria-label': 'The view' });
|
|
177
|
+
for (const [v, text, tip] of [['3d', '3D', '3D: the drawing; drag a selected thing to move it'], ['2d', '2D', '2D: select, rename, delete, add from the palette and edit here; moving is in 3D']] as const) {
|
|
178
|
+
const b = h('button', { type: 'button', class: 'seg', 'data-v': v, title: tip }, text);
|
|
179
|
+
b.addEventListener('click', () => setMode(v));
|
|
180
|
+
viewSeg.append(b);
|
|
181
|
+
}
|
|
182
|
+
// what a layer is given (its calls run later, once the drawing and the view are made)
|
|
183
|
+
const ctx: CanvasCtx<D> = {
|
|
184
|
+
host, doc, cd: () => cd, svg: () => svg, elementsFor: p => elementsFor(p), boxOf: e => boxOf(e), union: bs => union(bs), outlinesFor: p => outlinesFor(p),
|
|
185
|
+
scale: () => scale(), full: () => V.full, toSvg: (x, y) => toSvg(x, y), autoFit: () => autoFit(), paint: () => paintOverlay(), reveal: p => zoomIfOutside(p), note: (m, tone) => opts.note(m, tone),
|
|
186
|
+
};
|
|
187
|
+
// the layer's controls first, then the canvas's own
|
|
188
|
+
const layer = opts.layer?.(ctx);
|
|
189
|
+
tools.append(...(layer?.tools ?? []), ...(K.flat ? [viewSeg] : []), wheelSeg, dragSeg, zoomOut, zoomLabel, zoomIn, fitBtn);
|
|
190
|
+
const empty = h('div', { class: 'canvas-empty', hidden: true });
|
|
191
|
+
host.append(stage, tools, empty, ...(layer?.marks ?? []));
|
|
192
|
+
const nav = { wheel: 'zoom' as 'zoom' | 'scroll', drag: 'pan' as 'pan' | 'select' };
|
|
193
|
+
try { Object.assign(nav, JSON.parse(opts.store?.get('canvas-nav') ?? '{}')); } catch { /* defaults */ }
|
|
194
|
+
if (K.flat && opts.store?.get('canvas-view') === '2d') mode = '2d';
|
|
195
|
+
/** switch the view: the drawing again in the other one, fitted (a 2D layout and a 3D one share no coordinates) */
|
|
196
|
+
function setMode(m: '3d' | '2d') {
|
|
197
|
+
if (!K.flat || m === mode) return;
|
|
198
|
+
endMorph();
|
|
199
|
+
const was = mode;
|
|
200
|
+
mode = m;
|
|
201
|
+
opts.store?.set('canvas-view', m);
|
|
202
|
+
paintNav();
|
|
203
|
+
// the drawing on the stage stays there, under the new one, to morph from (0.7.5)
|
|
204
|
+
if (svg && cd && svg.parentNode === stage) morphFrom = { svg, mode: was };
|
|
205
|
+
if (lastS3 !== undefined) { V.view = undefined; lastKey = ''; void render(lastS3, lastData); }
|
|
206
|
+
}
|
|
207
|
+
const saveNav = () => opts.store?.set('canvas-nav', JSON.stringify(nav));
|
|
208
|
+
/** the toolbar, the cursor and the status bar's hint show the current modes */
|
|
209
|
+
function paintNav() {
|
|
210
|
+
for (const [g, v] of [[wheelSeg, nav.wheel], [dragSeg, nav.drag], [viewSeg, mode]] as const) for (const b of g.querySelectorAll<HTMLButtonElement>('.seg')) b.setAttribute('aria-pressed', String(b.dataset.v === v));
|
|
211
|
+
svg?.classList.toggle('mode-pan', nav.drag === 'pan');
|
|
212
|
+
svg?.classList.toggle('mode-select', nav.drag === 'select');
|
|
213
|
+
if (drag?.kind === 'pin' && drag.moved) { svg?.classList.add('dragging'); svg?.classList.toggle('drag-bad', !!drag.invalid); return; } // the drag's own hint stays
|
|
214
|
+
opts.onHint?.(`${nav.drag === 'pan' ? 'Drag: pan · ⇧-drag: select' : 'Drag: select · space-drag: pan'} · Wheel: ${nav.wheel === 'zoom' ? 'zoom' : 'scroll'}`);
|
|
215
|
+
}
|
|
216
|
+
let cd: D | undefined;
|
|
217
|
+
let svg: SVGSVGElement | undefined;
|
|
218
|
+
let overlay: SVGGElement | undefined;
|
|
219
|
+
let lastKey = '';
|
|
220
|
+
let hoverId: string | undefined;
|
|
221
|
+
const fdoc = () => document;
|
|
222
|
+
|
|
223
|
+
/** Draw the file (after each change the reader accepted). */
|
|
224
|
+
let disposed = false;
|
|
225
|
+
async function render(s3: M | undefined, data: unknown) {
|
|
226
|
+
if (disposed) return;
|
|
227
|
+
if (!s3) { showEmpty(T.unreadable); return; }
|
|
228
|
+
const key = JSON.stringify(data);
|
|
229
|
+
// nothing new to draw: repaint the marks, unless a drag is showing its grid (it repaints when it ends)
|
|
230
|
+
if (key === lastKey && svg) { if (!pinDrag()) paintOverlay(); return; }
|
|
231
|
+
if (mode === '2d' && !flatImpl) {
|
|
232
|
+
try { await loadFlat(); } catch (e) { mode = '3d'; paintNav(); opts.note(`The 2D view couldn't load: ${(e as Error).message}`, 'warn'); }
|
|
233
|
+
}
|
|
234
|
+
let next: D;
|
|
235
|
+
try { next = K.draw(s3, data, opts.theme); } catch (e) { showEmpty(`The canvas couldn't draw this: ${(e as Error).message}`); return; }
|
|
236
|
+
if (next.diags.length) { showEmpty(`The canvas couldn't draw this: ${next.diags[0]}`); return; }
|
|
237
|
+
lastKey = key;
|
|
238
|
+
lastS3 = s3; lastData = data;
|
|
239
|
+
if (pinDrag()) { pendingAfterDrag = true; return; } // a model change mid-drag: drawn when the drag ends
|
|
240
|
+
await draw(next);
|
|
241
|
+
if (cd!.pinNotes.length) opts.note(`Pins: ${cd!.pinNotes.join('; ')}`, 'warn');
|
|
242
|
+
}
|
|
243
|
+
let lastS3: M | undefined, lastData: unknown, pendingAfterDrag = false;
|
|
244
|
+
// ---------- the switch's morph (0.7.5): the 2D view's implementation runs it, over the stage ----------
|
|
245
|
+
let morphFrom: { svg: SVGSVGElement; mode: '3d' | '2d' } | undefined;
|
|
246
|
+
let morphing: { m: SvgMorph; from: SVGSVGElement; to: SVGSVGElement } | undefined;
|
|
247
|
+
/** end a morph now: the layer and the old drawing gone, the new one shown */
|
|
248
|
+
function endMorph() {
|
|
249
|
+
if (!morphing) return;
|
|
250
|
+
const r = morphing; morphing = undefined;
|
|
251
|
+
r.m.finish();
|
|
252
|
+
r.from.remove();
|
|
253
|
+
r.to.style.visibility = '';
|
|
254
|
+
}
|
|
255
|
+
/** after a switch draws the new view: the morph from the old one, both on the stage (the old under the new) */
|
|
256
|
+
function startMorph(from: { svg: SVGSVGElement; mode: '3d' | '2d' }, to: SVGSVGElement) {
|
|
257
|
+
const m = flatImpl?.morph?.(stage, cd!.scene, from, to, { motion: K.flat?.motion, duration: K.flat?.duration });
|
|
258
|
+
if (!m) { from.svg.remove(); return; }
|
|
259
|
+
from.svg.style.visibility = 'hidden'; to.style.visibility = 'hidden';
|
|
260
|
+
const me = { m, from: from.svg, to };
|
|
261
|
+
morphing = me;
|
|
262
|
+
stage.classList.add('morphing');
|
|
263
|
+
void m.done.then(() => { if (morphing === me) endMorph(); stage.classList.remove('morphing'); });
|
|
264
|
+
}
|
|
265
|
+
/** put a drawing on the stage (the file's, or a drag's trial layout): built with DOM calls, never from markup */
|
|
266
|
+
async function draw(next: D) {
|
|
267
|
+
endMorph();
|
|
268
|
+
let s: SVGSVGElement;
|
|
269
|
+
let full = next.scene.rendered.viewBox as unknown as number[];
|
|
270
|
+
try {
|
|
271
|
+
if (mode === '2d' && flatImpl) {
|
|
272
|
+
// the 2D view: the host's implementation draws the drawing's board, laid out flat
|
|
273
|
+
flat = flatImpl.draw(next.scene, stage, { styles: K.flat?.styles, title: K.flat?.title, options: K.flat?.options });
|
|
274
|
+
full = flat.full;
|
|
275
|
+
s = buildSvg(flat.svg);
|
|
276
|
+
// the stage takes the keys: the cards aren't stops of their own here
|
|
277
|
+
for (const e of s.querySelectorAll('[tabindex]')) { e.removeAttribute('tabindex'); e.removeAttribute('role'); }
|
|
278
|
+
} else { flat = undefined; s = buildSvg(next.svg); }
|
|
279
|
+
} catch (e) { showEmpty(`The canvas couldn't draw this: ${(e as Error).message}`); return; }
|
|
280
|
+
cd = next;
|
|
281
|
+
s.classList.add('scene');
|
|
282
|
+
s.removeAttribute('width'); s.removeAttribute('height');
|
|
283
|
+
s.setAttribute('preserveAspectRatio', 'xMidYMid meet');
|
|
284
|
+
s.setAttribute('aria-hidden', 'true'); // the stage says it in words; the tree and text say the rest
|
|
285
|
+
overlay = document.createElementNS(SVGNS, 'g') as SVGGElement;
|
|
286
|
+
overlay.setAttribute('class', 'overlay');
|
|
287
|
+
// 0.7.4: safe without any stylesheet: the marks inherit no fill, a thin accent-less stroke, and never take the pointer
|
|
288
|
+
// (a hover mark over its thing would take it, and the hover would flicker); a host's CSS (assets/marks.css) styles them
|
|
289
|
+
overlay.setAttribute('fill', 'none'); overlay.setAttribute('stroke', 'currentColor'); overlay.setAttribute('pointer-events', 'none');
|
|
290
|
+
s.append(overlay, ...(layer?.groups?.() ?? []));
|
|
291
|
+
const from = morphFrom; morphFrom = undefined;
|
|
292
|
+
if (from && svg === from.svg && svg.parentNode === stage) {
|
|
293
|
+
// a switch: the old view stays under the new one until the morph has read both
|
|
294
|
+
from.svg.querySelector('.overlay')?.replaceChildren();
|
|
295
|
+
from.svg.style.position = 'absolute'; from.svg.style.inset = '0';
|
|
296
|
+
stage.append(s);
|
|
297
|
+
} else if (svg?.parentNode === stage) svg.replaceWith(s); else stage.append(s);
|
|
298
|
+
svg = s;
|
|
299
|
+
const [x, y, w, hh] = full;
|
|
300
|
+
V.full = { x, y, w, h: hh };
|
|
301
|
+
if (!V.view) { V.view = { ...V.full }; autoFit(); } else quietly(applyView);
|
|
302
|
+
empty.hidden = true;
|
|
303
|
+
layer?.drawn?.();
|
|
304
|
+
if (pendingReveal && reveal(pendingReveal)) pendingReveal = undefined;
|
|
305
|
+
paintNav();
|
|
306
|
+
paintOverlay();
|
|
307
|
+
if (from && from.svg !== s) {
|
|
308
|
+
if (getComputedStyle(stage).position === 'static') stage.style.position = 'relative';
|
|
309
|
+
startMorph(from, s);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
function showEmpty(t: string) {
|
|
313
|
+
morphFrom = undefined;
|
|
314
|
+
empty.textContent = t;
|
|
315
|
+
empty.hidden = false;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// light and dark: the canvas CSS maps the drawing's tokens onto the skin's, which follow the page's colour scheme
|
|
319
|
+
function setTheme(_t: 'light' | 'dark') { paintOverlay(); }
|
|
320
|
+
|
|
321
|
+
// ---------- view: pan and zoom (the viewport, src/iso-viewer/viewport.ts) ----------
|
|
322
|
+
function itemsBox() {
|
|
323
|
+
if (!cd || !svg) return undefined;
|
|
324
|
+
const ptrs = [...new Set([...cd.pathOf.values()].filter(p => { const r = resourceOf(p); return r && r.path === p; }))];
|
|
325
|
+
// what a layer draws is fitted too
|
|
326
|
+
const live = layer?.extent?.() ?? [];
|
|
327
|
+
return union([...ptrs.flatMap(p => elementsFor(p)).filter(e => e.getBBox().width || e.getBBox().height).map(boxOf), ...live]);
|
|
328
|
+
}
|
|
329
|
+
const V = viewport(host, {
|
|
330
|
+
svg: () => svg,
|
|
331
|
+
onApply: k => {
|
|
332
|
+
svg!.classList.toggle('zoom-near', k >= 1); // a layer's detail shows from 100% up
|
|
333
|
+
const pct = Math.round(k * 100);
|
|
334
|
+
zoomLabel.textContent = `${pct}%`;
|
|
335
|
+
opts.onZoom(pct);
|
|
336
|
+
},
|
|
337
|
+
onRezoom: () => paintOverlay(),
|
|
338
|
+
itemsBox: () => itemsBox(),
|
|
339
|
+
marksShowing: () => !!layer?.showing?.(),
|
|
340
|
+
});
|
|
341
|
+
const { size, scale, quietly, applyView, toSvg, zoomAt, fit, fitItems, autoFit, actual, settled } = V;
|
|
342
|
+
function zoomToSelection() { const b = unionBox(doc.selection); if (b) fit({ x: b.x - 20, y: b.y - 20, w: b.w + 40, h: b.h + 40 }); }
|
|
343
|
+
zoomIn.addEventListener('click', () => zoomAt(1.25));
|
|
344
|
+
zoomOut.addEventListener('click', () => zoomAt(0.8));
|
|
345
|
+
zoomLabel.addEventListener('click', () => fitItems());
|
|
346
|
+
fitBtn.addEventListener('click', () => fitItems());
|
|
347
|
+
|
|
348
|
+
// ---------- what is where ----------
|
|
349
|
+
const elementsFor = (ptr: string): SVGGraphicsElement[] => {
|
|
350
|
+
if (!svg || !cd) return [];
|
|
351
|
+
const ids = [...cd.pathOf.entries()].filter(([, p]) => p === ptr || (ptr && p.startsWith(ptr + '/') && false)).map(([id]) => id);
|
|
352
|
+
return ids.flatMap(id => [...svg!.querySelectorAll<SVGGraphicsElement>(`[data-id="${CSS.escape(id)}"]`)]).filter(e => !e.closest('.pre') && !e.classList.contains('pre'));
|
|
353
|
+
};
|
|
354
|
+
/** an element's box in the scene's (root) coordinates */
|
|
355
|
+
const boxOf = (e: SVGGraphicsElement) => {
|
|
356
|
+
const b = e.getBBox();
|
|
357
|
+
const m = e.getCTM(), root = svg!.getCTM();
|
|
358
|
+
if (!m || !root) return { x: b.x, y: b.y, w: b.width, h: b.height };
|
|
359
|
+
const t = root.inverse().multiply(m);
|
|
360
|
+
const pts = [[b.x, b.y], [b.x + b.width, b.y], [b.x, b.y + b.height], [b.x + b.width, b.y + b.height]].map(([x, y]) => ({ x: t.a * x + t.c * y + t.e, y: t.b * x + t.d * y + t.f }));
|
|
361
|
+
const xs = pts.map(p => p.x), ys = pts.map(p => p.y);
|
|
362
|
+
return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
|
|
363
|
+
};
|
|
364
|
+
const union = (bs: { x: number; y: number; w: number; h: number }[]) => {
|
|
365
|
+
if (!bs.length) return undefined;
|
|
366
|
+
const x0 = Math.min(...bs.map(b => b.x)), y0 = Math.min(...bs.map(b => b.y)), x1 = Math.max(...bs.map(b => b.x + b.w)), y1 = Math.max(...bs.map(b => b.y + b.h));
|
|
367
|
+
return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
|
368
|
+
};
|
|
369
|
+
/** a path's drawn box: its own elements, else its resource's */
|
|
370
|
+
const boxFor = (p: Path) => {
|
|
371
|
+
// the path's own drawing, else (a key inside a resource) its resource's; never the whole file for something else
|
|
372
|
+
const own = toPointer(p);
|
|
373
|
+
let els = elementsFor(own);
|
|
374
|
+
const r = resourceOf(own);
|
|
375
|
+
if (!els.length && r && r.path !== own) els = elementsFor(r.path);
|
|
376
|
+
return els.length ? union(els.filter(e => e.getBBox().width || e.getBBox().height).map(boxOf)) : undefined;
|
|
377
|
+
};
|
|
378
|
+
const unionBox = (ps: Path[]) => union(ps.map(boxFor).filter((b): b is NonNullable<typeof b> => !!b));
|
|
379
|
+
const pathAtEvent = (target: EventTarget | null): string | undefined => {
|
|
380
|
+
const el = (target as Element | null)?.closest?.('[data-id]') as Element | null;
|
|
381
|
+
if (!el || !cd) return undefined;
|
|
382
|
+
// the innermost element that maps
|
|
383
|
+
let e: Element | null = el;
|
|
384
|
+
while (e) { const id = e.getAttribute('data-id'); if (id && cd.pathOf.has(id)) return cd.pathOf.get(id); e = e.parentElement?.closest('[data-id]') ?? null; }
|
|
385
|
+
return undefined;
|
|
386
|
+
};
|
|
387
|
+
|
|
388
|
+
// ---------- the overlay: selection rings, hover, problem badges ----------
|
|
389
|
+
/**
|
|
390
|
+
* A resource's drawn shapes, isometric: a node (or a slab, a VM, a platform) is the silhouette of its box (the hexagon
|
|
391
|
+
* its eight projected corners make); any other region is its floor parallelogram; a route is its own path.
|
|
392
|
+
*/
|
|
393
|
+
function outlinesFor(ptr: string): ({ kind: 'poly'; id: string; points: [number, number][] } | { kind: 'route'; d: string })[] {
|
|
394
|
+
if (!cd) return [];
|
|
395
|
+
const out: ({ kind: 'poly'; id: string; points: [number, number][] } | { kind: 'route'; d: string })[] = [];
|
|
396
|
+
const mine = new Set([...cd.pathOf].filter(([, p]) => p === ptr).map(([id]) => id));
|
|
397
|
+
// 2D: a card's or a panel's rect; a link's own path
|
|
398
|
+
if (flat && svg) return flat.outlines(mine, svg);
|
|
399
|
+
for (const [id, p] of cd.pathOf) {
|
|
400
|
+
if (p !== ptr) continue;
|
|
401
|
+
const item = cd.scene.layout.byId.get(id);
|
|
402
|
+
// a thing drawn inside another drawing of the same resource (a VM's /workspace and disk) has no outline of its own
|
|
403
|
+
let up = item?.parent;
|
|
404
|
+
while (up && !mine.has(up.id)) up = up.parent;
|
|
405
|
+
if (up) continue;
|
|
406
|
+
if (item) {
|
|
407
|
+
if (svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) continue;
|
|
408
|
+
const shape = regionKind(K.catalog, item.region?.kind)?.shape;
|
|
409
|
+
const solid = item.type === 'node' || shape === 'slab' || shape === 'block';
|
|
410
|
+
out.push({ kind: 'poly', id, points: solid ? boxSilhouette(item.box) : floorOf(item.box) });
|
|
411
|
+
} else if (cd.scene.rendered.paths[id] && !svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) {
|
|
412
|
+
out.push({ kind: 'route', d: cd.scene.rendered.paths[id] });
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return out;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function paintOverlay() {
|
|
419
|
+
V.painted(V.view ? scale() : 0);
|
|
420
|
+
if (!overlay || !svg) return;
|
|
421
|
+
const d = fdoc();
|
|
422
|
+
overlay.replaceChildren();
|
|
423
|
+
const ring = (b: { x: number; y: number; w: number; h: number }, cls: string, pad = 4) => {
|
|
424
|
+
const r = d.createElementNS(SVGNS, 'rect');
|
|
425
|
+
r.setAttribute('class', cls);
|
|
426
|
+
r.setAttribute('x', String(b.x - pad)); r.setAttribute('y', String(b.y - pad));
|
|
427
|
+
r.setAttribute('width', String(b.w + pad * 2)); r.setAttribute('height', String(b.h + pad * 2));
|
|
428
|
+
r.setAttribute('rx', '6');
|
|
429
|
+
overlay!.append(r);
|
|
430
|
+
};
|
|
431
|
+
const draw = (ptr: string, cls: 'ring' | 'hover') => {
|
|
432
|
+
// a key inside a resource is shown by its resource's outline
|
|
433
|
+
const r = resourceOf(ptr);
|
|
434
|
+
let shapes = outlinesFor(ptr);
|
|
435
|
+
if (!shapes.length && r && r.path !== ptr) shapes = outlinesFor(r.path);
|
|
436
|
+
if (!shapes.length) { const b = boxFor(fromPointer(ptr)); if (b) ring(b, cls, cls === 'hover' ? 3 : 4); return; }
|
|
437
|
+
for (const sh of shapes) {
|
|
438
|
+
if (sh.kind === 'route') {
|
|
439
|
+
const r = d.createElementNS(SVGNS, 'path');
|
|
440
|
+
r.setAttribute('class', cls === 'ring' ? 'route-ring' : 'route-hover');
|
|
441
|
+
r.setAttribute('d', sh.d);
|
|
442
|
+
overlay!.append(r);
|
|
443
|
+
} else {
|
|
444
|
+
const r = d.createElementNS(SVGNS, 'polygon');
|
|
445
|
+
r.setAttribute('class', cls);
|
|
446
|
+
r.setAttribute('points', sh.points.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' '));
|
|
447
|
+
r.setAttribute('data-for', sh.id);
|
|
448
|
+
overlay!.append(r);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
if (hoverId !== undefined && !doc.selection.some(p => toPointer(p) === hoverId)) draw(hoverId, 'hover');
|
|
453
|
+
for (const p of doc.selection) draw(toPointer(p), 'ring');
|
|
454
|
+
// (0.10.0) connecting: a handle on the one selected object, and while a connection is drawn, its line and its target
|
|
455
|
+
const one = connectable();
|
|
456
|
+
const from = linking?.from ?? one;
|
|
457
|
+
const fb = from ? boxFor(fromPointer(from.path)) : undefined;
|
|
458
|
+
if (fb && K.connect) {
|
|
459
|
+
const k = scale(), hx = fb.x + fb.w + 10 / k, hy = fb.y + fb.h / 2;
|
|
460
|
+
if (linking && linking.x !== undefined && linking.y !== undefined) {
|
|
461
|
+
if (linking.over) draw(linking.over, 'hover');
|
|
462
|
+
const l = d.createElementNS(SVGNS, 'line');
|
|
463
|
+
l.setAttribute('class', `connect-line${linking.over ? ' ok' : ''}`);
|
|
464
|
+
l.setAttribute('x1', String(hx)); l.setAttribute('y1', String(hy)); l.setAttribute('x2', String(linking.x)); l.setAttribute('y2', String(linking.y));
|
|
465
|
+
overlay.append(l);
|
|
466
|
+
}
|
|
467
|
+
if (!linking) {
|
|
468
|
+
const c = d.createElementNS(SVGNS, 'circle');
|
|
469
|
+
c.setAttribute('class', 'connect-handle');
|
|
470
|
+
c.setAttribute('cx', String(hx)); c.setAttribute('cy', String(hy)); c.setAttribute('r', String(7 / k));
|
|
471
|
+
// the one mark that takes the pointer (through the CSSOM: a host's marks CSS may say none for the overlay)
|
|
472
|
+
c.style.pointerEvents = 'all'; c.style.cursor = 'crosshair';
|
|
473
|
+
const t = d.createElementNS(SVGNS, 'title');
|
|
474
|
+
t.textContent = `Drag to what ${from!.name} connects to`;
|
|
475
|
+
c.append(t);
|
|
476
|
+
overlay.append(c);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
// a badge on each drawn resource with problems
|
|
480
|
+
const counts = new Map<string, { e: number; w: number }>();
|
|
481
|
+
for (const pr of opts.problems()) {
|
|
482
|
+
if (pr.file) continue;
|
|
483
|
+
const r = resourceOf(pr.path);
|
|
484
|
+
if (!r) continue;
|
|
485
|
+
const c = counts.get(r.path) ?? { e: 0, w: 0 };
|
|
486
|
+
if (pr.severity === 'error') c.e++; else c.w++;
|
|
487
|
+
counts.set(r.path, c);
|
|
488
|
+
}
|
|
489
|
+
for (const [ptr, c] of counts) {
|
|
490
|
+
// on the thing itself (its nodes and regions), not on the routes that reach out from it
|
|
491
|
+
const els = elementsFor(ptr).filter(e => cd!.scene.layout.byId.has(e.getAttribute('data-id') ?? ''));
|
|
492
|
+
const b = union(els.map(boxOf));
|
|
493
|
+
if (!b) continue;
|
|
494
|
+
const g = d.createElementNS(SVGNS, 'g');
|
|
495
|
+
g.setAttribute('class', `badge${c.e ? '' : ' warn'}`);
|
|
496
|
+
const k = scale();
|
|
497
|
+
const cx = b.x + b.w, cy = b.y, rr = 9 / k;
|
|
498
|
+
const circle = d.createElementNS(SVGNS, 'circle');
|
|
499
|
+
circle.setAttribute('cx', String(cx)); circle.setAttribute('cy', String(cy)); circle.setAttribute('r', String(rr));
|
|
500
|
+
const t = d.createElementNS(SVGNS, 'text');
|
|
501
|
+
t.setAttribute('x', String(cx)); t.setAttribute('y', String(cy));
|
|
502
|
+
t.style.fontSize = `${(11 / k).toFixed(2)}px`; // through the CSSOM (it must beat the drawing's badge rule)
|
|
503
|
+
t.textContent = String(c.e || c.w);
|
|
504
|
+
g.append(circle, t);
|
|
505
|
+
overlay.append(g);
|
|
506
|
+
}
|
|
507
|
+
layer?.paint?.(d);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// ---------- pointer: select, marquee, pan, pin ----------
|
|
511
|
+
let drag: {
|
|
512
|
+
kind: 'pan' | 'marquee' | 'pin' | 'click'; x0: number; y0: number; v0?: View; emptyClick?: boolean;
|
|
513
|
+
// a pin drag: where it started and what it is shown at, its size and floor, its parent and siblings, the move so far
|
|
514
|
+
start?: [number, number]; shown?: [number, number]; z0?: number; size?: [number, number];
|
|
515
|
+
parent?: { w: number; d: number; pad: number; box: { x0: number; y0: number; x1: number; y1: number }; label: string };
|
|
516
|
+
siblings?: { x0: number; y0: number; x1: number; y1: number }[]; move?: Move; invalid?: boolean; step?: number; origCd?: D; gridShown?: boolean;
|
|
517
|
+
/** siblings that flow after the dragged item, pinned where they stand so the drag doesn't push them */
|
|
518
|
+
keep?: [string, [number, number]][]; sel0?: Path[]; add?: boolean; touch?: boolean; name?: string; id?: string; box?: { x: number; y: number; w: number; h: number }; moved?: boolean; ptr?: string; narrow?: string } | undefined;
|
|
519
|
+
let spaceKeyDown = false;
|
|
520
|
+
const ifEvents = () => {
|
|
521
|
+
stage.addEventListener('pointerdown', down);
|
|
522
|
+
stage.addEventListener('pointermove', move);
|
|
523
|
+
stage.addEventListener('pointerup', up);
|
|
524
|
+
stage.addEventListener('pointercancel', up);
|
|
525
|
+
stage.addEventListener('wheel', wheel, { passive: false });
|
|
526
|
+
stage.addEventListener('contextmenu', context);
|
|
527
|
+
stage.addEventListener('dblclick', e => { const p = pathAtEvent(e.target); if (p !== undefined) opts.showInText(fromPointer(p)); });
|
|
528
|
+
};
|
|
529
|
+
// in the page, a pointer's coordinates are already the page's
|
|
530
|
+
const pageXY = (e: PointerEvent | MouseEvent) => ({ x: e.clientX, y: e.clientY });
|
|
531
|
+
/** a drag keeps its pointer's events when the pointer leaves the stage (a synthetic pointer can't be captured) */
|
|
532
|
+
const capture = (e: PointerEvent) => { try { stage.setPointerCapture(e.pointerId); } catch { /* not a real pointer */ } };
|
|
533
|
+
|
|
534
|
+
function down(e: PointerEvent) {
|
|
535
|
+
stage.focus({ preventScroll: true });
|
|
536
|
+
if (layer?.down?.(e)) return;
|
|
537
|
+
const { x, y } = pageXY(e);
|
|
538
|
+
// (0.10.0) a press on the connect handle starts a connection; a click while one is picked ends it
|
|
539
|
+
if (e.button === 0 && linking?.pick) { e.preventDefault(); endConnect(pathAtEvent(e.target)); return; }
|
|
540
|
+
if (e.button === 0 && (e.target as Element | null)?.closest?.('.connect-handle')) {
|
|
541
|
+
const one = connectable();
|
|
542
|
+
if (one) { capture(e); e.preventDefault(); const p = toSvg(x, y); linking = { from: one, x: p.x, y: p.y }; paintOverlay(); return; }
|
|
543
|
+
}
|
|
544
|
+
if (e.button === 0 || e.button === 1) capture(e);
|
|
545
|
+
const pan = () => { drag = { kind: 'pan', x0: x, y0: y, v0: { ...V.view! } }; svg?.classList.add('panning'); e.preventDefault(); };
|
|
546
|
+
if (e.button === 1 || spaceKeyDown) { pan(); return; }
|
|
547
|
+
if (e.button !== 0) return;
|
|
548
|
+
const ptr = pathAtEvent(e.target);
|
|
549
|
+
if (ptr === undefined) {
|
|
550
|
+
// nothing under the pointer: Pan mode pans (⇧ or ⌘ draws a selection instead); Select mode draws a selection (the space key pans)
|
|
551
|
+
const mod = e.shiftKey || e.metaKey || e.ctrlKey;
|
|
552
|
+
if (nav.drag === 'pan' && !mod) { drag = { kind: 'pan', x0: x, y0: y, v0: { ...V.view! }, emptyClick: true }; svg?.classList.add('panning'); return; }
|
|
553
|
+
const add = nav.drag === 'select' && mod;
|
|
554
|
+
drag = { kind: 'marquee', x0: x, y0: y, sel0: add ? doc.selection : [], add, touch: e.altKey };
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
const p = fromPointer(ptr);
|
|
558
|
+
const sel = doc.selection.map(toPointer);
|
|
559
|
+
if (e.shiftKey || e.metaKey || e.ctrlKey) {
|
|
560
|
+
doc.select(sel.includes(ptr) ? doc.selection.filter(q => toPointer(q) !== ptr) : [...doc.selection, p], 'canvas');
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
if (!sel.includes(ptr)) doc.select([p], 'canvas');
|
|
564
|
+
// a plain click on one of several selected things selects just it, once the button comes up without a drag
|
|
565
|
+
const narrow = sel.includes(ptr) && sel.length > 1 ? ptr : undefined;
|
|
566
|
+
drag = { kind: 'click', x0: x, y0: y, ptr: narrow };
|
|
567
|
+
// a press on a resource that can be pinned: a drag pins it
|
|
568
|
+
const r = resourceOf(ptr);
|
|
569
|
+
const name = r && r.path === ptr ? r.name : undefined;
|
|
570
|
+
const id = name && mode === '3d' ? cd?.pinId.get(name) : undefined;
|
|
571
|
+
if (id && cd) {
|
|
572
|
+
const item = cd.scene.layout.byId.get(id);
|
|
573
|
+
const start = localAt(cd.scene, id);
|
|
574
|
+
if (item && start) {
|
|
575
|
+
const b = item.box, par = item.parent;
|
|
576
|
+
const siblings = (par ? par.children : cd.scene.layout.items.filter(i => !i.parent)).filter(i => i !== item).map(i => ({ x0: i.box.x0, y0: i.box.y0, x1: i.box.x1, y1: i.box.y1 }));
|
|
577
|
+
drag = {
|
|
578
|
+
kind: 'pin', x0: x, y0: y, name, id, ptr, narrow, start, shown: start, z0: b.z0, size: [b.x1 - b.x0, b.y1 - b.y0], siblings,
|
|
579
|
+
parent: par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region), box: par.box, label: par.region?.label ?? par.id } : undefined,
|
|
580
|
+
origCd: cd,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
function move(e: PointerEvent) {
|
|
586
|
+
const { x, y } = pageXY(e);
|
|
587
|
+
if (linking) {
|
|
588
|
+
const p = toSvg(x, y), under = pathAtEvent(document.elementFromPoint(x, y));
|
|
589
|
+
const r = under === undefined ? undefined : resourceOf(under);
|
|
590
|
+
linking = { ...linking, x: p.x, y: p.y, over: r && r.path !== linking.from.path ? r.path : undefined };
|
|
591
|
+
paintOverlay();
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
if (!drag) {
|
|
595
|
+
const p = pathAtEvent(e.target);
|
|
596
|
+
if (p !== hoverId) { hoverId = p; paintOverlay(); }
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
const k = scale();
|
|
600
|
+
if (drag.kind === 'click' && mode === '2d' && !drag.moved && Math.hypot(x - drag.x0, y - drag.y0) > 4) {
|
|
601
|
+
drag.moved = true;
|
|
602
|
+
opts.onHint?.('Moving is in 3D: switch to 3D to drag it where it goes');
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
if (drag.kind === 'pan') {
|
|
606
|
+
if (Math.hypot(x - drag.x0, y - drag.y0) > 3) drag.emptyClick = false;
|
|
607
|
+
V.view = { ...drag.v0!, x: drag.v0!.x - (x - drag.x0) / k, y: drag.v0!.y - (y - drag.y0) / k };
|
|
608
|
+
applyView();
|
|
609
|
+
} else if (drag.kind === 'marquee') {
|
|
610
|
+
// the marquee is a rectangle on the floor (grid units), drawn as the parallelogram it projects to
|
|
611
|
+
if (Math.hypot(x - drag.x0, y - drag.y0) < 3) return;
|
|
612
|
+
drag.moved = true;
|
|
613
|
+
const a = toSvg(drag.x0, drag.y0), b = toSvg(x, y);
|
|
614
|
+
if (flat) { marquee2d(a, b); return; }
|
|
615
|
+
const [ax, ay] = screenToGrid(a.x, a.y), [bx, by] = screenToGrid(b.x, b.y);
|
|
616
|
+
const g = { x0: Math.min(ax, bx), y0: Math.min(ay, by), x1: Math.max(ax, bx), y1: Math.max(ay, by) };
|
|
617
|
+
const hits = new Map<string, Path>();
|
|
618
|
+
for (const [ptr, foot] of footprints()) {
|
|
619
|
+
// a thing at height z shows where a thing on the floor at (x − z, y − z) would: compare it there
|
|
620
|
+
const f = foot;
|
|
621
|
+
const inside = f.x0 >= g.x0 && f.y0 >= g.y0 && f.x1 <= g.x1 && f.y1 <= g.y1;
|
|
622
|
+
const touches = f.x0 < g.x1 && f.x1 > g.x0 && f.y0 < g.y1 && f.y1 > g.y0;
|
|
623
|
+
if (drag.touch ? touches : inside) hits.set(ptr, fromPointer(ptr));
|
|
624
|
+
}
|
|
625
|
+
const base = new Map((drag.sel0 ?? []).map(p => [toPointer(p), p]));
|
|
626
|
+
for (const [k2, p] of hits) base.set(k2, p);
|
|
627
|
+
doc.select([...base.values()], 'canvas');
|
|
628
|
+
paintOverlay();
|
|
629
|
+
const poly = fdoc().createElementNS(SVGNS, 'polygon');
|
|
630
|
+
poly.setAttribute('class', 'marquee');
|
|
631
|
+
poly.setAttribute('points', [[g.x0, g.y0], [g.x1, g.y0], [g.x1, g.y1], [g.x0, g.y1]].map(([gx, gy]) => iso(gx, gy, 0).map(v => v.toFixed(1)).join(',')).join(' '));
|
|
632
|
+
overlay!.append(poly);
|
|
633
|
+
lastMarquee = g;
|
|
634
|
+
} else if (drag.kind === 'pin') {
|
|
635
|
+
if (!drag.moved && Math.hypot(x - drag.x0, y - drag.y0) < 4) return;
|
|
636
|
+
drag.moved = true;
|
|
637
|
+
lastPin = { x, y, alt: e.altKey };
|
|
638
|
+
// throttled to animation frames (with a timer for a page that draws none)
|
|
639
|
+
if (!pinFrame) { pinFrame = true; const go = () => { if (pinFrame) { pinFrame = false; pinStep(); } }; requestAnimationFrame(go); setTimeout(go, 32); }
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
/** the marquee in 2D: a rectangle, what lies in it (or touches it, with ⌥) */
|
|
643
|
+
function marquee2d(a: { x: number; y: number }, b: { x: number; y: number }) {
|
|
644
|
+
if (!drag || !flat || !cd) return;
|
|
645
|
+
const g = { l: Math.min(a.x, b.x), t: Math.min(a.y, b.y), r: Math.max(a.x, b.x), b: Math.max(a.y, b.y) };
|
|
646
|
+
const hits = new Map<string, Path>();
|
|
647
|
+
for (const id of flat.hits(g, !!drag.touch)) {
|
|
648
|
+
const ptr = cd.pathOf.get(id);
|
|
649
|
+
if (ptr !== undefined && resourceOf(ptr)?.path === ptr) hits.set(ptr, fromPointer(ptr));
|
|
650
|
+
}
|
|
651
|
+
const base = new Map((drag.sel0 ?? []).map(p => [toPointer(p), p]));
|
|
652
|
+
for (const [k2, p] of hits) base.set(k2, p);
|
|
653
|
+
doc.select([...base.values()], 'canvas');
|
|
654
|
+
paintOverlay();
|
|
655
|
+
const r = fdoc().createElementNS(SVGNS, 'rect');
|
|
656
|
+
r.setAttribute('class', 'marquee');
|
|
657
|
+
r.setAttribute('x', String(g.l)); r.setAttribute('y', String(g.t)); r.setAttribute('width', String(g.r - g.l)); r.setAttribute('height', String(g.b - g.t));
|
|
658
|
+
overlay!.append(r);
|
|
659
|
+
}
|
|
660
|
+
let pinFrame = false, lastPin: { x: number; y: number; alt: boolean } | undefined, relayout = 0;
|
|
661
|
+
const pinDrag = () => (drag?.kind === 'pin' && drag.moved ? drag : undefined);
|
|
662
|
+
/** one step of a pin drag: snap, clamp, check, move the drawing, and lay it out again when the cell changes */
|
|
663
|
+
function pinStep() {
|
|
664
|
+
const g = pinDrag();
|
|
665
|
+
if (!g || !lastPin || !cd) return;
|
|
666
|
+
const k = scale();
|
|
667
|
+
const step = lastPin.alt ? 0.5 : 1;
|
|
668
|
+
g.step = step;
|
|
669
|
+
const m = snapMove(g.start!, screenToGrid((lastPin.x - g.x0) / k, (lastPin.y - g.y0) / k), step, g.size!, g.parent);
|
|
670
|
+
const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
|
|
671
|
+
const foot = { x0: ox + m.at[0], y0: oy + m.at[1], x1: ox + m.at[0] + g.size![0], y1: oy + m.at[1] + g.size![1] };
|
|
672
|
+
const changed = !g.move || g.move.at[0] !== m.at[0] || g.move.at[1] !== m.at[1];
|
|
673
|
+
g.move = m;
|
|
674
|
+
g.invalid = overlaps(foot, g.siblings!);
|
|
675
|
+
svg?.classList.add('dragging');
|
|
676
|
+
svg?.classList.toggle('drag-bad', g.invalid);
|
|
677
|
+
// at once: the drawn item (and what stands on it) moved by transform, from where the drawing has it
|
|
678
|
+
shiftDragged(g.id!, [m.at[0] - g.shown![0], m.at[1] - g.shown![1]]);
|
|
679
|
+
paintDrag(foot);
|
|
680
|
+
const within = g.parent ? `within ${g.parent.label}` : 'on the canvas';
|
|
681
|
+
opts.onHint?.(`Moving ${g.name} ${within} · ${step === 1 ? 'whole cells (⌥: half cells)' : 'half cells'} · ${g.invalid ? 'overlaps: it won\'t drop here' : 'Esc cancels'}${T.pinHint}`);
|
|
682
|
+
// then the real layout, with its routes and labels, once per cell (and only where it may drop)
|
|
683
|
+
if (changed && !g.invalid && lastS3) {
|
|
684
|
+
clearTimeout(relayout);
|
|
685
|
+
relayout = window.setTimeout(async () => {
|
|
686
|
+
const now = pinDrag();
|
|
687
|
+
if (!now || now.invalid || !now.move) return;
|
|
688
|
+
let next: D;
|
|
689
|
+
try { ({ next, keep: now.keep } = trialLayout(now)); } catch { return; }
|
|
690
|
+
if (pinDrag() !== now) return; // the drag ended meanwhile: don't draw a stale trial
|
|
691
|
+
await draw(next);
|
|
692
|
+
if (pinDrag() !== now) return;
|
|
693
|
+
now.shown = now.move.at;
|
|
694
|
+
shiftDragged(now.id!, [0, 0]);
|
|
695
|
+
paintDrag(now.parent ? { x0: now.parent.box.x0 + now.move.at[0], y0: now.parent.box.y0 + now.move.at[1], x1: now.parent.box.x0 + now.move.at[0] + now.size![0], y1: now.parent.box.y0 + now.move.at[1] + now.size![1] } : foot);
|
|
696
|
+
}, 0);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* The drawing with the dragged item pinned at its move. Siblings placed after it (in the flow, or beside it) would move
|
|
701
|
+
* with it; any that did, and can be pinned, are kept where they stood, and the drop pins them too.
|
|
702
|
+
*/
|
|
703
|
+
function trialLayout(g: NonNullable<typeof drag>): { next: D; keep: [string, [number, number]][] } {
|
|
704
|
+
const base = JSON.parse(JSON.stringify(lastData ?? {})) as Record<string, Record<string, Record<string, unknown>>>;
|
|
705
|
+
// pins kept under the legacy key are read there; the trial puts them where the drop will (x-editor)
|
|
706
|
+
if (K.pins.legacyOnly(base)) { base[PINS_KEY] = base[K.pins.legacyKey!]; delete base[K.pins.legacyKey!]; }
|
|
707
|
+
base[PINS_KEY] ??= {}; base[PINS_KEY].layout ??= {};
|
|
708
|
+
const pins = base[PINS_KEY].layout;
|
|
709
|
+
pins[g.name!] = { at: g.move!.at };
|
|
710
|
+
let next = K.draw(lastS3!, base, opts.theme);
|
|
711
|
+
const orig = g.origCd!, nameOf = new Map([...orig.pinId].map(([n, id]) => [id, n]));
|
|
712
|
+
const me = orig.scene.layout.byId.get(g.id!)!;
|
|
713
|
+
const sibs = me.parent ? me.parent.children : orig.scene.layout.items.filter(i => !i.parent);
|
|
714
|
+
const keep: [string, [number, number]][] = [];
|
|
715
|
+
for (const sb of sibs) {
|
|
716
|
+
if (sb === me) continue;
|
|
717
|
+
const n = nameOf.get(sb.id), was = localAt(orig.scene, sb.id), now = next.scene.layout.byId.get(sb.id)?.box;
|
|
718
|
+
if (!n || !was || !now || n in pins) continue;
|
|
719
|
+
if (Math.abs(now.x0 - sb.box.x0) > 1e-6 || Math.abs(now.y0 - sb.box.y0) > 1e-6) keep.push([n, was]);
|
|
720
|
+
}
|
|
721
|
+
if (keep.length) { for (const [n, at] of keep) pins[n] = { at }; next = K.draw(lastS3!, base, opts.theme); }
|
|
722
|
+
return { next, keep };
|
|
723
|
+
}
|
|
724
|
+
/** move a drawn item, and everything standing on it, by a grid offset (a transform: the next layout replaces it) */
|
|
725
|
+
function shiftDragged(id: string, [gx, gy]: [number, number]) {
|
|
726
|
+
if (!svg || !cd) return;
|
|
727
|
+
const [sx, sy] = [(gx - gy) * C * S, (gx + gy) * 0.5 * S];
|
|
728
|
+
const ids = new Set([id]);
|
|
729
|
+
for (const it of cd.scene.layout.items) { let p = it.parent; while (p) { if (p.id === id) { ids.add(it.id); break; } p = p.parent; } }
|
|
730
|
+
for (const el of svg.querySelectorAll<SVGElement>('[data-id]')) {
|
|
731
|
+
if (!ids.has(el.getAttribute('data-id') ?? '')) continue;
|
|
732
|
+
if (el.parentElement?.closest(`[data-id="${CSS.escape(el.getAttribute('data-id')!)}"]`)) continue;
|
|
733
|
+
el.setAttribute('transform', gx || gy ? `translate(${sx.toFixed(1)} ${sy.toFixed(1)})` : '');
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/** the drag's overlay: the grid on the parent's floor (half cells too, with ⌥), the drop target, the clamped edges */
|
|
737
|
+
function paintDrag(foot: { x0: number; y0: number; x1: number; y1: number }) {
|
|
738
|
+
const g = pinDrag();
|
|
739
|
+
if (!g || !overlay) return;
|
|
740
|
+
paintOverlay();
|
|
741
|
+
const d = fdoc();
|
|
742
|
+
const wrap = d.createElementNS(SVGNS, 'g');
|
|
743
|
+
wrap.setAttribute('class', g.gridShown ? 'gridwrap' : 'gridwrap fresh'); // fades in once per drag, not per re-layout
|
|
744
|
+
g.gridShown = true;
|
|
745
|
+
const z = g.z0!;
|
|
746
|
+
const P = (x: number, y: number) => iso(x, y, z).map(v => v.toFixed(1)).join(',');
|
|
747
|
+
const area = g.parent ? g.parent.box : { x0: Math.floor(foot.x0) - 8, y0: Math.floor(foot.y0) - 8, x1: Math.ceil(foot.x1) + 8, y1: Math.ceil(foot.y1) + 8 };
|
|
748
|
+
const line = (x1: number, y1: number, x2: number, y2: number, cls: string) => {
|
|
749
|
+
const l = d.createElementNS(SVGNS, 'polyline');
|
|
750
|
+
l.setAttribute('class', cls);
|
|
751
|
+
l.setAttribute('points', `${P(x1, y1)} ${P(x2, y2)}`);
|
|
752
|
+
wrap.append(l);
|
|
753
|
+
};
|
|
754
|
+
// the grid's lines, in the parent's frame: whole cells from its origin, and half cells while ⌥ is held
|
|
755
|
+
const ox = g.parent ? g.parent.box.x0 : 0, oy = g.parent ? g.parent.box.y0 : 0;
|
|
756
|
+
const st = g.step ?? 1;
|
|
757
|
+
for (let v = Math.ceil((area.x0 - ox) / st) * st; ox + v <= area.x1 + 1e-9; v += st) line(ox + v, area.y0, ox + v, area.y1, Number.isInteger(v) ? 'dgrid' : 'dgrid sub');
|
|
758
|
+
for (let v = Math.ceil((area.y0 - oy) / st) * st; oy + v <= area.y1 + 1e-9; v += st) line(area.x0, oy + v, area.x1, oy + v, Number.isInteger(v) ? 'dgrid' : 'dgrid sub');
|
|
759
|
+
overlay.append(wrap);
|
|
760
|
+
// the drop target: the footprint, accent where it may drop, red where it can't
|
|
761
|
+
const t = d.createElementNS(SVGNS, 'polygon');
|
|
762
|
+
t.setAttribute('class', `drop${g.invalid ? ' bad' : ''}`);
|
|
763
|
+
t.setAttribute('points', [[foot.x0, foot.y0], [foot.x1, foot.y0], [foot.x1, foot.y1], [foot.x0, foot.y1]].map(([x, y]) => P(x, y)).join(' '));
|
|
764
|
+
overlay.append(t);
|
|
765
|
+
// the parent's edges the move is held at
|
|
766
|
+
if (g.parent && g.move) {
|
|
767
|
+
const pb = g.parent.box, c = g.move.clamped, pad = g.parent.pad;
|
|
768
|
+
const e = (x1: number, y1: number, x2: number, y2: number) => { const l = d.createElementNS(SVGNS, 'polyline'); l.setAttribute('class', 'edge'); l.setAttribute('points', `${P(x1, y1)} ${P(x2, y2)}`); overlay!.append(l); };
|
|
769
|
+
if (c.left) e(pb.x0 + pad, pb.y0, pb.x0 + pad, pb.y1);
|
|
770
|
+
if (c.right) e(pb.x1 - pad, pb.y0, pb.x1 - pad, pb.y1);
|
|
771
|
+
if (c.top) e(pb.x0, pb.y0 + pad, pb.x1, pb.y0 + pad);
|
|
772
|
+
if (c.bottom) e(pb.x0, pb.y1 - pad, pb.x1, pb.y1 - pad);
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/** end a pin drag: the drop commits one command; an overlap, a cancel or no move puts the drawing back */
|
|
776
|
+
async function endPin(commit: boolean) {
|
|
777
|
+
const g = pinDrag();
|
|
778
|
+
if (!g) return;
|
|
779
|
+
drag = undefined;
|
|
780
|
+
clearTimeout(relayout);
|
|
781
|
+
// the grid and the drop target fade out, then the drop
|
|
782
|
+
const shown = overlay ? [...overlay.querySelectorAll('.gridwrap, .drop, .edge')] : [];
|
|
783
|
+
if (shown.length) {
|
|
784
|
+
for (const e of shown) e.classList.add('out');
|
|
785
|
+
if (!matchMedia('(prefers-reduced-motion: reduce)').matches) await new Promise(r => setTimeout(r, 160));
|
|
786
|
+
}
|
|
787
|
+
lastKey = ''; // the frame may hold a trial layout: the next render redraws
|
|
788
|
+
svg?.classList.remove('dragging', 'drag-bad');
|
|
789
|
+
paintNav();
|
|
790
|
+
const m = g.move;
|
|
791
|
+
const moved = m && (m.at[0] !== g.start![0] || m.at[1] !== g.start![1]);
|
|
792
|
+
if (commit && m && moved && !g.invalid) {
|
|
793
|
+
// the item, and the neighbours the move would have pushed, kept where they stand: one command, one undo step
|
|
794
|
+
const label = `Pin ${describe(fromPointer(g.ptr!))} at [${m.at.join(', ')}]`;
|
|
795
|
+
let keep = g.keep ?? [];
|
|
796
|
+
if (!g.shown || g.shown[0] !== m.at[0] || g.shown[1] !== m.at[1]) try { keep = trialLayout(g).keep; } catch { /* drop it as it is */ }
|
|
797
|
+
run(doc, keep.length ? pinsCmd([[g.name!, m.at], ...keep], `${label} (${keep.map(([n]) => n).join(', ')} kept in place)`) : withPinsMoved(setCmd([PINS_KEY, 'layout', g.name!], { at: m.at }, label)), 'canvas', opts.note);
|
|
798
|
+
if (pendingAfterDrag && lastS3) { pendingAfterDrag = false; lastKey = ''; render(lastS3, lastData); }
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
if (commit && g.invalid) opts.note(`${g.name} can't go there: it would overlap`, 'warn');
|
|
802
|
+
await draw(g.origCd!);
|
|
803
|
+
if (pendingAfterDrag && lastS3) { pendingAfterDrag = false; lastKey = ''; render(lastS3, lastData); }
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
function up(e: PointerEvent) {
|
|
807
|
+
if (linking && !linking.pick) { const { x, y } = pageXY(e); endConnect(pathAtEvent(document.elementFromPoint(x, y))); return; }
|
|
808
|
+
const d0 = drag;
|
|
809
|
+
drag = undefined;
|
|
810
|
+
svg?.classList.remove('panning');
|
|
811
|
+
if (!d0) return;
|
|
812
|
+
const { x, y } = pageXY(e);
|
|
813
|
+
if ((d0.kind === 'marquee' && !d0.moved && !d0.add) || (d0.kind === 'pan' && d0.emptyClick)) doc.select([], 'canvas');
|
|
814
|
+
const narrow = d0.kind === 'click' ? d0.ptr : d0.kind === 'pin' && !d0.moved ? d0.narrow : undefined;
|
|
815
|
+
if (narrow) doc.select([fromPointer(narrow)], 'canvas');
|
|
816
|
+
if (d0.kind === 'pin' && d0.moved) {
|
|
817
|
+
// the last position the pointer reached, then the drop
|
|
818
|
+
drag = d0;
|
|
819
|
+
lastPin = { x, y, alt: e.altKey };
|
|
820
|
+
pinFrame = false;
|
|
821
|
+
pinStep();
|
|
822
|
+
endPin(true);
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
paintOverlay();
|
|
826
|
+
}
|
|
827
|
+
let lastMarquee: { x0: number; y0: number; x1: number; y1: number } | undefined;
|
|
828
|
+
/** each drawn resource's footprint on the floor, its own height folded in (see the marquee) */
|
|
829
|
+
function footprints(): Map<string, { x0: number; y0: number; x1: number; y1: number }> {
|
|
830
|
+
const out = new Map<string, { x0: number; y0: number; x1: number; y1: number }>();
|
|
831
|
+
if (!cd) return out;
|
|
832
|
+
for (const [id, ptr] of cd.pathOf) {
|
|
833
|
+
const r = resourceOf(ptr);
|
|
834
|
+
if (!r || r.path !== ptr) continue;
|
|
835
|
+
const item = cd.scene.layout.byId.get(id);
|
|
836
|
+
if (!item || svg?.querySelector(`[data-id="${CSS.escape(id)}"].pre`)) continue;
|
|
837
|
+
const b = item.box, z = b.z0;
|
|
838
|
+
const f = { x0: b.x0 - z, y0: b.y0 - z, x1: b.x1 - z, y1: b.y1 - z };
|
|
839
|
+
const prev = out.get(ptr);
|
|
840
|
+
// a resource drawn as several things (one inside another): the union
|
|
841
|
+
out.set(ptr, prev ? { x0: Math.min(prev.x0, f.x0), y0: Math.min(prev.y0, f.y0), x1: Math.max(prev.x1, f.x1), y1: Math.max(prev.y1, f.y1) } : f);
|
|
842
|
+
}
|
|
843
|
+
return out;
|
|
844
|
+
}
|
|
845
|
+
const round = (v: number) => Math.round(v * 2) / 2;
|
|
846
|
+
const snap = ([x, y]: [number, number]): [number, number] => [round(x), round(y)];
|
|
847
|
+
const gridToScreen = (gx: number, gy: number): [number, number] => { const [ux, uy] = screenToGrid(1, 0), [vx, vy] = screenToGrid(0, 1); const det = ux * vy - uy * vx; return [(gx * vy - gy * vx) / det, (gy * ux - gx * uy) / det]; };
|
|
848
|
+
|
|
849
|
+
function wheel(e: WheelEvent) {
|
|
850
|
+
e.preventDefault();
|
|
851
|
+
const { x, y } = pageXY(e);
|
|
852
|
+
const k = scale();
|
|
853
|
+
// a pinch (ctrlKey on a wheel event) or ⌘-wheel always zooms; ⇧-wheel always pans sideways
|
|
854
|
+
if (e.ctrlKey || e.metaKey) { zoomAt(Math.exp(-e.deltaY * 0.01), x, y); return; }
|
|
855
|
+
if (e.shiftKey) { V.view = { ...V.view!, x: V.view!.x + (e.deltaX || e.deltaY) / k }; applyView(); return; }
|
|
856
|
+
if (nav.wheel === 'zoom') zoomAt(Math.exp(-e.deltaY * 0.0025), x, y);
|
|
857
|
+
else { V.view = { ...V.view!, x: V.view!.x + e.deltaX / k, y: V.view!.y + e.deltaY / k }; applyView(); }
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// ---------- the menu ----------
|
|
861
|
+
function context(e: MouseEvent) {
|
|
862
|
+
e.preventDefault();
|
|
863
|
+
const { x, y } = pageXY(e);
|
|
864
|
+
if (layer?.context?.(e, { x, y })) return;
|
|
865
|
+
const ptr = pathAtEvent(e.target);
|
|
866
|
+
if (ptr !== undefined && !doc.selection.some(p => toPointer(p) === ptr)) doc.select([fromPointer(ptr)], 'canvas');
|
|
867
|
+
openMenu(menuItems(ptr), { x, y }, 'Canvas');
|
|
868
|
+
}
|
|
869
|
+
function menuItems(ptr: string | undefined): MenuItem[] {
|
|
870
|
+
const sel = doc.selection;
|
|
871
|
+
const items: MenuItem[] = [];
|
|
872
|
+
const ro = !doc.doc.ok;
|
|
873
|
+
if (ptr === undefined || !sel.length) {
|
|
874
|
+
for (const s of ui.newOrder) items.push({ label: `New ${kindOf(s).singular}`, icon: 'plus', disabled: ro, onSelect: () => addResource(s) });
|
|
875
|
+
if (opts.clipItems) items.push({ sep: true }, ...opts.clipItems().filter(i => 'label' in i && i.label === 'Paste'));
|
|
876
|
+
items.push({ sep: true }, { label: 'Fit', keys: '0', onSelect: () => fitItems() }, { label: 'Fit the whole drawing', onSelect: () => fit() }, { label: 'Zoom 100%', keys: '1', onSelect: () => actual() });
|
|
877
|
+
const hasPins = !!K.pins.of(doc.goodDoc.data);
|
|
878
|
+
items.push({ label: 'Reset layout', icon: 'rotate-ccw', desc: 'Remove every pin (x-editor.layout)', disabled: ro || !hasPins, why: 'Nothing is pinned', onSelect: resetLayout });
|
|
879
|
+
return items;
|
|
880
|
+
}
|
|
881
|
+
const one = sel.length === 1 ? sel[0] : undefined;
|
|
882
|
+
const isRes = one && resourceOf(toPointer(one))?.path === toPointer(one);
|
|
883
|
+
if (one) {
|
|
884
|
+
items.push(...K.objectItems(doc, one, 'canvas', opts.note));
|
|
885
|
+
if (items.length) items.push({ sep: true });
|
|
886
|
+
items.push({ label: 'Rename…', icon: 'pencil', keys: 'F2', disabled: ro || !isRes, why: T.renameWhy, onSelect: () => renameDialog(doc, one, 'canvas', opts.note) });
|
|
887
|
+
items.push({ label: 'Duplicate', icon: 'copy', keys: '⌘D', disabled: ro || !isRes, why: T.duplicateWhy, onSelect: () => duplicate(doc, one, 'canvas', opts.note) });
|
|
888
|
+
const name = isRes ? resourceOf(toPointer(one))!.name : '';
|
|
889
|
+
const pinned = !!K.pins.of(doc.goodDoc.data)?.[name];
|
|
890
|
+
if (pinned) items.push({ label: 'Unpin', icon: 'rotate-ccw', desc: 'Let the layout place it again', onSelect: () => run(doc, withPinsMoved({ ...deleteCmd([PINS_KEY, 'layout', name]), label: `Unpin ${describe(one)}` }), 'canvas', opts.note) });
|
|
891
|
+
items.push({ sep: true });
|
|
892
|
+
items.push({ label: 'Show in text', icon: 'code-xml', onSelect: () => opts.showInText(one) });
|
|
893
|
+
items.push({ label: 'Show in tree', icon: 'list-tree', onSelect: () => opts.showInTree(one) });
|
|
894
|
+
}
|
|
895
|
+
// (0.10.0) connect and group, where the domain says how
|
|
896
|
+
if (K.connect && one && isRes) items.push({ label: 'Connect to…', icon: 'link', desc: 'Then click what it connects to (Esc cancels)', disabled: ro, onSelect: () => startPick() });
|
|
897
|
+
if (K.group) items.push({ label: sel.length > 1 ? `Group ${sel.length} items` : 'Group', icon: 'box', keys: '⌘G', desc: 'Into a new container, as one step', disabled: ro || !members().length, why: 'Only objects are grouped', onSelect: groupSelection });
|
|
898
|
+
items.push({ label: 'Select parent', icon: 'arrow-up-right', keys: '⌘↑', onSelect: selectParent });
|
|
899
|
+
items.push({ label: 'Select connected', icon: 'link', desc: 'What refers to it, and what it refers to', onSelect: () => doc.select(connected(doc, sel), 'canvas') });
|
|
900
|
+
items.push({ label: 'Zoom to selection', keys: '⇧2', onSelect: zoomToSelection });
|
|
901
|
+
if (opts.clipItems) items.push({ sep: true }, ...opts.clipItems());
|
|
902
|
+
items.push({ sep: true }, { label: sel.length > 1 ? `Delete ${sel.length} items` : 'Delete', icon: 'trash-2', keys: '⌫', danger: true, disabled: ro, onSelect: () => deletePaths(doc, sel, 'canvas', opts.note) });
|
|
903
|
+
return items;
|
|
904
|
+
}
|
|
905
|
+
// ---------- (0.10.0) connect and group, by the domain's plans ----------
|
|
906
|
+
/** the one selected object, if the domain connects and the file reads */
|
|
907
|
+
function connectable(): ObjectRef | undefined {
|
|
908
|
+
if (!K.connect || !doc.doc.ok || doc.selection.length !== 1) return undefined;
|
|
909
|
+
const ptr = toPointer(doc.selection[0]), r = resourceOf(ptr);
|
|
910
|
+
return r && r.path === ptr ? r : undefined;
|
|
911
|
+
}
|
|
912
|
+
function startPick() {
|
|
913
|
+
const from = connectable();
|
|
914
|
+
if (!from) return;
|
|
915
|
+
linking = { from, pick: true };
|
|
916
|
+
opts.note(`Click what ${from.name} connects to (Esc cancels)`);
|
|
917
|
+
paintOverlay();
|
|
918
|
+
}
|
|
919
|
+
/** end a connection on what is under the pointer: the domain's plan, written as one step */
|
|
920
|
+
function endConnect(ptr: string | undefined) {
|
|
921
|
+
const from = linking?.from;
|
|
922
|
+
linking = undefined;
|
|
923
|
+
paintOverlay();
|
|
924
|
+
if (!from || ptr === undefined) return;
|
|
925
|
+
const to = resourceOf(ptr);
|
|
926
|
+
if (!to || to.path === from.path) { opts.note('Not connected: drop it on another object', 'warn'); return; }
|
|
927
|
+
const data = doc.goodDoc.data;
|
|
928
|
+
const plan = K.connect?.(from, to, data);
|
|
929
|
+
if (!plan) { opts.note(`${from.name} and ${to.name} can't be connected`, 'warn'); return; }
|
|
930
|
+
const label = plan.label ?? `Connect ${from.name} to ${to.name}`;
|
|
931
|
+
let cmd: Command, path: Path;
|
|
932
|
+
if (plan.name !== undefined) {
|
|
933
|
+
const name = freshName(doc.text, plan.name);
|
|
934
|
+
cmd = insertCmd(plan.at, name, plan.value, { label });
|
|
935
|
+
path = [...plan.at, name];
|
|
936
|
+
} else {
|
|
937
|
+
const list = plan.at.reduce<unknown>((x, k) => (x && typeof x === 'object' ? (x as Record<string, unknown>)[k as string] : undefined), data);
|
|
938
|
+
path = [...plan.at, Array.isArray(list) ? list.length : 0];
|
|
939
|
+
cmd = insertItemCmd(plan.at, plan.value, undefined, label);
|
|
940
|
+
}
|
|
941
|
+
if (run(doc, { ...cmd, select: [path] }, 'canvas', opts.note)) doc.select([path], 'canvas');
|
|
942
|
+
}
|
|
943
|
+
/** the selection's objects (a key inside one counts as its object), once each */
|
|
944
|
+
function members(): ObjectRef[] {
|
|
945
|
+
const out = new Map<string, ObjectRef>();
|
|
946
|
+
for (const p of doc.selection) { const r = resourceOf(toPointer(p)); if (r) out.set(r.path, r); }
|
|
947
|
+
return [...out.values()];
|
|
948
|
+
}
|
|
949
|
+
/** the selection into a new container: the container, each member's change and its pin dropped (the layout places it
|
|
950
|
+
* in its new frame), as one command, one undo step */
|
|
951
|
+
function groupSelection() {
|
|
952
|
+
if (!K.group || !doc.doc.ok) return;
|
|
953
|
+
const ms = members();
|
|
954
|
+
if (!ms.length) { opts.note('Only objects are grouped', 'warn'); return; }
|
|
955
|
+
const plan = K.group(ms, doc.goodDoc.data);
|
|
956
|
+
if (!plan) { opts.note(ms.length > 1 ? `These ${ms.length} can't be grouped` : `${ms[0].name} can't be grouped`, 'warn'); return; }
|
|
957
|
+
const name = freshName(doc.text, plan.name);
|
|
958
|
+
const pins = K.pins.of(doc.goodDoc.data) ?? {};
|
|
959
|
+
const unpin = ms.filter(m => pins[m.name] !== undefined).map(m => withPinsMoved(deleteCmd([PINS_KEY, 'layout', m.name])));
|
|
960
|
+
const label = plan.label ?? `Group ${ms.length > 1 ? `${ms.length} items` : ms[0].name} into ${name}`;
|
|
961
|
+
const p = [...plan.at, name] as Path;
|
|
962
|
+
const cmd = seqCmd(label, [insertCmd(plan.at, name, plan.value, { label }), ...plan.members(name).map(m => setCmd(m.path, m.value)), ...unpin]);
|
|
963
|
+
if (run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) doc.select([p], 'canvas');
|
|
964
|
+
}
|
|
965
|
+
function addResource(s: string) {
|
|
966
|
+
const k = kindOf(s);
|
|
967
|
+
const name = freshName(doc.text, k.singular);
|
|
968
|
+
const p = [...k.section, name];
|
|
969
|
+
if (run(doc, insertCmd(p.slice(0, -1), name, k.template(), { label: `Add ${k.singular} ${name}` }), 'canvas', opts.note)) {
|
|
970
|
+
doc.select([p], 'canvas');
|
|
971
|
+
renameDialog(doc, p, 'canvas', opts.note);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
// ---------- E11: the palette: add a resource by a click, or by a drag onto the canvas ----------
|
|
975
|
+
/** Where a drop lands, as a pin: the new thing laid out once (a trial), then moved from where the layout put it to
|
|
976
|
+
* the point, in its parent's frame and on the grid. Undefined: the spot is taken, or it can't be placed. */
|
|
977
|
+
function placeAt(name: string, add: Command, at: { x: number; y: number }): [number, number] | undefined {
|
|
978
|
+
if (!cd || !svg) return undefined;
|
|
979
|
+
const text = add.build(doc.text).steps.reduce((t, st) => applyStep(t, st), doc.text);
|
|
980
|
+
let trial: D | undefined;
|
|
981
|
+
try { trial = K.trial(text, opts.theme); } catch { return undefined; }
|
|
982
|
+
if (!trial) return undefined;
|
|
983
|
+
const id = trial.pinId.get(name), item = id ? trial.scene.layout.byId.get(id) : undefined, start = id ? localAt(trial.scene, id) : undefined;
|
|
984
|
+
if (!item || !start) return undefined;
|
|
985
|
+
const b = item.box, par = item.parent;
|
|
986
|
+
// the drawing's coordinates are the projection's: the trial's centre and the drop point, in the same units
|
|
987
|
+
const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2;
|
|
988
|
+
const centre = [(cx - cy) * C * S, (cx + cy) * 0.5 * S - b.z0 * S], drop = toSvg(at.x, at.y);
|
|
989
|
+
const m = snapMove(start, screenToGrid(drop.x - centre[0], drop.y - centre[1]), 1, [b.x1 - b.x0, b.y1 - b.y0],
|
|
990
|
+
par ? { w: par.box.x1 - par.box.x0, d: par.box.y1 - par.box.y0, pad: paddingOf(K.catalog, par.region) } : undefined);
|
|
991
|
+
const dx = m.at[0] - start[0], dy = m.at[1] - start[1];
|
|
992
|
+
const moved = { x0: b.x0 + dx, y0: b.y0 + dy, x1: b.x1 + dx, y1: b.y1 + dy };
|
|
993
|
+
const siblings = (par ? par.children : trial.scene.layout.items.filter(i => !i.parent)).filter(i => i !== item).map(i => i.box);
|
|
994
|
+
return overlaps(moved, siblings) ? undefined : m.at;
|
|
995
|
+
}
|
|
996
|
+
/** The container (of the kind given) whose floor a point is on (its footprint, as drawn), if any. */
|
|
997
|
+
function containerAt(kind: string, at: { x: number; y: number }): string | undefined {
|
|
998
|
+
if (!cd) return undefined;
|
|
999
|
+
const p = toSvg(at.x, at.y);
|
|
1000
|
+
if (flat) {
|
|
1001
|
+
// 2D: the innermost panel of that kind under the point
|
|
1002
|
+
for (const id of flat.panelsAt(p.x, p.y)) {
|
|
1003
|
+
const name = [...cd.pinId].find(([, pid]) => pid === id)?.[0];
|
|
1004
|
+
if (name && resourceOf(cd.pathOf.get(id) ?? '')?.kind === kind) return name;
|
|
1005
|
+
}
|
|
1006
|
+
return undefined;
|
|
1007
|
+
}
|
|
1008
|
+
const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > p.y) !== (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c; } return c; };
|
|
1009
|
+
for (const [name, id] of cd.pinId) {
|
|
1010
|
+
if (resourceOf(cd.pathOf.get(id) ?? '')?.kind !== kind) continue;
|
|
1011
|
+
const item = cd.scene.layout.byId.get(id);
|
|
1012
|
+
if (item && inside(floorOf(item.box))) return name;
|
|
1013
|
+
}
|
|
1014
|
+
return undefined;
|
|
1015
|
+
}
|
|
1016
|
+
/** (0.10.1) the objects whose drawn floor a point is on, innermost first: in 2D the panels under it; in 3D every placed
|
|
1017
|
+
* thing whose floor holds the point, the deepest (then the smallest) first */
|
|
1018
|
+
function objectsUnder(at: { x: number; y: number }): ObjectRef[] {
|
|
1019
|
+
if (!cd) return [];
|
|
1020
|
+
const p = toSvg(at.x, at.y);
|
|
1021
|
+
const refOf = (id: string) => { const ptr = cd!.pathOf.get(id); const r = ptr === undefined ? undefined : resourceOf(ptr); return r && r.path === ptr ? r : undefined; };
|
|
1022
|
+
if (flat) return flat.panelsAt(p.x, p.y).map(refOf).filter((r): r is ObjectRef => !!r);
|
|
1023
|
+
const inside = (poly: [number, number][]) => { let c = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const [xi, yi] = poly[i], [xj, yj] = poly[j]; if ((yi > p.y) !== (yj > p.y) && p.x < (xj - xi) * (p.y - yi) / (yj - yi) + xi) c = !c; } return c; };
|
|
1024
|
+
const depth = (i: { parent?: unknown }) => { let n = 0; for (let q = i.parent as { parent?: unknown } | undefined; q; q = q.parent as { parent?: unknown } | undefined) n++; return n; };
|
|
1025
|
+
// what is drawn under the point, topmost (innermost) first, as the eye sees it; then any whose floor holds the point
|
|
1026
|
+
const seen = new Map<string, ObjectRef>();
|
|
1027
|
+
for (const e of fdoc().elementsFromPoint(at.x, at.y)) {
|
|
1028
|
+
if (!svg?.contains(e)) continue;
|
|
1029
|
+
for (let el = e.closest('[data-id]'); el; el = el.parentElement?.closest('[data-id]') ?? null) {
|
|
1030
|
+
const r = refOf(el.getAttribute('data-id') ?? '');
|
|
1031
|
+
if (r && !seen.has(r.path)) seen.set(r.path, r);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
const hits: { r: ObjectRef; d: number; a: number }[] = [];
|
|
1035
|
+
for (const [, id] of cd.pinId) {
|
|
1036
|
+
const item = cd.scene.layout.byId.get(id), r = refOf(id);
|
|
1037
|
+
if (item && r && !seen.has(r.path) && inside(floorOf(item.box))) hits.push({ r, d: depth(item), a: (item.box.x1 - item.box.x0) * (item.box.y1 - item.box.y0) });
|
|
1038
|
+
}
|
|
1039
|
+
return [...seen.values(), ...hits.sort((x, y) => y.d - x.d || x.a - y.a).map(h => h.r)];
|
|
1040
|
+
}
|
|
1041
|
+
/** Add an object from the palette: dropped at a point, it is pinned there; dropped on a container the kit names, it
|
|
1042
|
+
* is made inside it; else the layout places it. One command (one undo step); then it is selected and named. */
|
|
1043
|
+
function addFromPalette(sec: string, at?: { x: number; y: number }, item?: PaletteItem): Path | undefined {
|
|
1044
|
+
if (!doc.doc.ok) { opts.note('Fix the YAML first', 'warn'); return undefined; }
|
|
1045
|
+
const k = kindOf(sec);
|
|
1046
|
+
// (0.10.0) a palette entry's preset: what it starts as, and the base of its name
|
|
1047
|
+
const preset = item?.value?.() as Record<string, unknown> | undefined;
|
|
1048
|
+
const what = item && preset !== undefined ? item.label.toLowerCase() : k.singular;
|
|
1049
|
+
const name = freshName(doc.text, item?.name ?? k.singular);
|
|
1050
|
+
const p = [...k.section, name] as Path;
|
|
1051
|
+
let value = (preset ?? k.template()) as Record<string, unknown>;
|
|
1052
|
+
let into: string | undefined;
|
|
1053
|
+
const drop = at ? K.dropInto?.(sec) : undefined;
|
|
1054
|
+
if (at && drop) {
|
|
1055
|
+
const c = containerAt(drop.container, at);
|
|
1056
|
+
// dropped into a container: what puts it there, and the preset's own keys over it
|
|
1057
|
+
if (c) { into = c; value = { ...(drop.value(c) as Record<string, unknown>), ...(preset ?? {}) }; }
|
|
1058
|
+
}
|
|
1059
|
+
let intoLabel = into ? drop!.label(into) : '';
|
|
1060
|
+
// (0.10.1) the domain's rule: the innermost object under the drop that holds it
|
|
1061
|
+
if (at && !into && K.dropOnto) {
|
|
1062
|
+
for (const t of objectsUnder(at)) {
|
|
1063
|
+
const plan = K.dropOnto(t, value, sec, doc.goodDoc.data);
|
|
1064
|
+
if (plan) { into = t.name; value = plan.value as Record<string, unknown>; intoLabel = plan.label ? ` ${plan.label}` : ` in ${t.name}`; break; }
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
const label = `Add ${what} ${name}${intoLabel}`;
|
|
1068
|
+
const add = insertCmd(p.slice(0, -1), name, value, { label });
|
|
1069
|
+
const pin = at && !into && mode === '3d' ? placeAt(name, add, at) : undefined;
|
|
1070
|
+
const cmd = pin ? seqCmd(`${label} at [${pin.join(', ')}]`, [add, withPinsMoved(setCmd([PINS_KEY, 'layout', name], { at: pin }))]) : add;
|
|
1071
|
+
if (!run(doc, { ...cmd, select: [p] }, 'canvas', opts.note)) return undefined;
|
|
1072
|
+
if (at && !into && !pin) opts.note(mode === '2d' ? `${k.singular} ${name} added; the layout placed it (in 3D a drop pins it where it lands)` : `${k.singular} ${name} added; that spot is taken, so the layout placed it`);
|
|
1073
|
+
doc.select([p], 'canvas');
|
|
1074
|
+
// (0.10.1) the canvas has the focus while the name is asked, so the dialog gives it back there (⌘Z works at once)
|
|
1075
|
+
stage.focus({ preventScroll: true });
|
|
1076
|
+
renameDialog(doc, p, 'canvas', opts.note);
|
|
1077
|
+
return p;
|
|
1078
|
+
}
|
|
1079
|
+
const palette = h('div', { class: 'palette', role: 'toolbar', 'aria-label': T.palette, 'aria-orientation': 'vertical' });
|
|
1080
|
+
ui.palette.forEach((item, idx) => {
|
|
1081
|
+
const { kind: sec, icon: ic, label } = item;
|
|
1082
|
+
const b = h('button', { type: 'button', class: 'pal-item', 'data-section': sec, 'data-entry': String(idx), title: `Add ${label.toLowerCase()} (click), or drag it where it goes` }, icon(ic), h('span', { class: 'pal-label' }, label));
|
|
1083
|
+
b.addEventListener('pointerdown', e => {
|
|
1084
|
+
if (e.button !== 0) return;
|
|
1085
|
+
e.preventDefault();
|
|
1086
|
+
try { b.setPointerCapture(e.pointerId); } catch { /* a synthetic pointer: the events come to the button anyway */ }
|
|
1087
|
+
const x0 = e.clientX, y0 = e.clientY;
|
|
1088
|
+
let ghost: HTMLElement | undefined;
|
|
1089
|
+
const over = (ev: PointerEvent) => { const r = stage.getBoundingClientRect(); return ev.clientX >= r.left && ev.clientX <= r.right && ev.clientY >= r.top && ev.clientY <= r.bottom && !palette.contains(document.elementFromPoint(ev.clientX, ev.clientY)); };
|
|
1090
|
+
const mv = (ev: PointerEvent) => {
|
|
1091
|
+
if (!ghost && Math.hypot(ev.clientX - x0, ev.clientY - y0) < 4) return;
|
|
1092
|
+
if (!ghost) { ghost = h('div', { class: 'pal-ghost', 'aria-hidden': 'true' }, icon(ic), label); host.append(ghost); }
|
|
1093
|
+
const hr = host.getBoundingClientRect();
|
|
1094
|
+
ghost.style.left = `${ev.clientX - hr.left + 8}px`; ghost.style.top = `${ev.clientY - hr.top + 8}px`;
|
|
1095
|
+
ghost.classList.toggle('bad', !over(ev));
|
|
1096
|
+
};
|
|
1097
|
+
const done = (ev: PointerEvent, drop: boolean) => {
|
|
1098
|
+
b.removeEventListener('pointermove', mv); b.removeEventListener('pointerup', upH); b.removeEventListener('pointercancel', cancelH); removeEventListener('keydown', esc, true);
|
|
1099
|
+
const dragged = !!ghost;
|
|
1100
|
+
ghost?.remove();
|
|
1101
|
+
if (!drop) return;
|
|
1102
|
+
if (!dragged) addFromPalette(sec, undefined, item);
|
|
1103
|
+
else if (over(ev)) addFromPalette(sec, { x: ev.clientX, y: ev.clientY }, item);
|
|
1104
|
+
};
|
|
1105
|
+
const upH = (ev: PointerEvent) => done(ev, true), cancelH = (ev: PointerEvent) => done(ev, false);
|
|
1106
|
+
const esc = (ev: KeyboardEvent) => { if (ev.key === 'Escape') { ev.stopPropagation(); ev.preventDefault(); done(e, false); } };
|
|
1107
|
+
b.addEventListener('pointermove', mv); b.addEventListener('pointerup', upH); b.addEventListener('pointercancel', cancelH); addEventListener('keydown', esc, true);
|
|
1108
|
+
});
|
|
1109
|
+
// the keyboard: Enter or the space key adds (the layout places it)
|
|
1110
|
+
b.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); addFromPalette(sec, undefined, item); } });
|
|
1111
|
+
palette.append(b);
|
|
1112
|
+
});
|
|
1113
|
+
host.append(palette);
|
|
1114
|
+
|
|
1115
|
+
function resetLayout() {
|
|
1116
|
+
// wherever the pins are (x-editor, or the legacy key): removed, and their key too if it holds nothing else
|
|
1117
|
+
const key = K.pins.keyOf(doc.goodDoc.data);
|
|
1118
|
+
const x = (doc.goodDoc.data as Record<string, Record<string, unknown>> | undefined)?.[key];
|
|
1119
|
+
const only = x && Object.keys(x).length === 1;
|
|
1120
|
+
run(doc, { ...deleteCmd(only ? [key] : [key, 'layout']), label: 'Reset the layout' }, 'canvas', opts.note);
|
|
1121
|
+
}
|
|
1122
|
+
function selectParent() {
|
|
1123
|
+
const up = new Map<string, Path>();
|
|
1124
|
+
for (const p of doc.selection) {
|
|
1125
|
+
const r = resourceOf(toPointer(p));
|
|
1126
|
+
// a property → its object; an object → its kind's section; a section → the root
|
|
1127
|
+
const q = r && r.path !== toPointer(p) ? fromPointer(r.path) : r ? kindOf(r.kind).section : [];
|
|
1128
|
+
up.set(toPointer(q), q);
|
|
1129
|
+
}
|
|
1130
|
+
doc.select([...up.values()], 'canvas');
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
// ---------- keys ----------
|
|
1134
|
+
function key(e: KeyboardEvent) {
|
|
1135
|
+
if (e.type === 'keyup' && e.key !== ' ') return;
|
|
1136
|
+
if (e.key === ' ') { spaceKeyDown = e.type === 'keydown'; svg?.classList.toggle(ui.panKeyClass, spaceKeyDown); e.preventDefault(); return; }
|
|
1137
|
+
const lk = layer?.key?.(e);
|
|
1138
|
+
if (lk === 'ignore') return;
|
|
1139
|
+
if (lk === 'handled') { e.preventDefault(); e.stopPropagation(); return; }
|
|
1140
|
+
const mod = e.metaKey || e.ctrlKey;
|
|
1141
|
+
const sel = doc.selection;
|
|
1142
|
+
const drawn = [...new Set([...(cd?.pathOf.values() ?? [])].filter(p => resourceOf(p)?.path === p))];
|
|
1143
|
+
const ro = !doc.doc.ok;
|
|
1144
|
+
switch (e.key) {
|
|
1145
|
+
case '+': case '=': zoomAt(1.25); break;
|
|
1146
|
+
case '-': case '_': zoomAt(0.8); break;
|
|
1147
|
+
case '0': fitItems(); break;
|
|
1148
|
+
case '1': actual(); break;
|
|
1149
|
+
case '@': case '2': if (e.shiftKey || e.key === '@') zoomToSelection(); else return; break;
|
|
1150
|
+
case 'Escape': if (linking) { linking = undefined; paintOverlay(); opts.note('Not connected'); break; } if (pinDrag()) { endPin(false); break; } doc.select([], 'canvas'); break;
|
|
1151
|
+
case 'Delete': case 'Backspace': if (sel.length && !ro) deletePaths(doc, sel, 'canvas', opts.note); break;
|
|
1152
|
+
case 'F2': if (sel.length === 1 && !ro) renameDialog(doc, sel[0], 'canvas', opts.note); break;
|
|
1153
|
+
case 'ArrowUp': if (mod) { selectParent(); break; } return;
|
|
1154
|
+
case 'Tab': case 'ArrowRight': case 'ArrowLeft': case 'ArrowDown': {
|
|
1155
|
+
// move through what is drawn, in the file's order
|
|
1156
|
+
if (!drawn.length) return;
|
|
1157
|
+
const i = sel.length ? drawn.indexOf(toPointer(sel[0])) : -1;
|
|
1158
|
+
const back = e.key === 'ArrowLeft' || (e.key === 'Tab' && e.shiftKey);
|
|
1159
|
+
const j = i < 0 ? 0 : (i + (back ? -1 : 1) + drawn.length) % drawn.length;
|
|
1160
|
+
doc.select([fromPointer(drawn[j])], 'canvas');
|
|
1161
|
+
zoomIfOutside(fromPointer(drawn[j]));
|
|
1162
|
+
break;
|
|
1163
|
+
}
|
|
1164
|
+
case 'ContextMenu': case 'F10':
|
|
1165
|
+
if (e.key === 'F10' && !e.shiftKey) return;
|
|
1166
|
+
{ const b = unionBox(sel); const r = host.getBoundingClientRect(); const k = scale(); openMenu(menuItems(sel.length ? toPointer(sel[0]) : undefined), b ? { x: r.left + (b.x + b.w - V.view!.x) * k, y: r.top + (b.y - V.view!.y) * k } : { x: r.left + 40, y: r.top + 40 }, 'Canvas'); }
|
|
1167
|
+
break;
|
|
1168
|
+
default:
|
|
1169
|
+
if (mod && e.key.toLowerCase() === 'd' && sel.length === 1 && !ro) { duplicate(doc, sel[0], 'canvas', opts.note); break; }
|
|
1170
|
+
if (mod && e.key.toLowerCase() === 'a') { doc.select(drawn.map(fromPointer), 'canvas'); break; }
|
|
1171
|
+
if (mod && e.key.toLowerCase() === 'g' && K.group && sel.length && !ro) { groupSelection(); break; }
|
|
1172
|
+
return;
|
|
1173
|
+
}
|
|
1174
|
+
e.preventDefault();
|
|
1175
|
+
e.stopPropagation();
|
|
1176
|
+
}
|
|
1177
|
+
stage.addEventListener('keydown', key);
|
|
1178
|
+
stage.addEventListener('keyup', key);
|
|
1179
|
+
const focusMark = (on: boolean) => host.classList.toggle('has-focus', on);
|
|
1180
|
+
stage.addEventListener('focus', () => focusMark(true));
|
|
1181
|
+
stage.addEventListener('blur', () => focusMark(false));
|
|
1182
|
+
paintNav();
|
|
1183
|
+
function zoomIfOutside(p: Path) {
|
|
1184
|
+
const b = boxFor(p);
|
|
1185
|
+
if (!b || !V.view) return;
|
|
1186
|
+
if (b.x < V.view.x || b.y < V.view.y || b.x + b.w > V.view.x + V.view.w || b.y + b.h > V.view.y + V.view.h) { V.view = { ...V.view, x: b.x + b.w / 2 - V.view.w / 2, y: b.y + b.h / 2 - V.view.h / 2 }; applyView(); }
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
/** bring these into view: pan to them, and zoom out if they don't fit (never in) */
|
|
1190
|
+
function reveal(paths: Path[]): boolean {
|
|
1191
|
+
if (!V.view || !paths.length) return true;
|
|
1192
|
+
const bs = paths.map(boxFor);
|
|
1193
|
+
if (bs.some(b => !b)) return false; // not drawn yet (just pasted): after the next render
|
|
1194
|
+
const b = union(bs as { x: number; y: number; w: number; h: number }[])!;
|
|
1195
|
+
const m = 24 / scale();
|
|
1196
|
+
if (b.x - m >= V.view.x && b.y - m >= V.view.y && b.x + b.w + m <= V.view.x + V.view.w && b.y + b.h + m <= V.view.y + V.view.h) return true;
|
|
1197
|
+
if (b.w + 2 * m > V.view.w || b.h + 2 * m > V.view.h) { fit({ x: b.x - m, y: b.y - m, w: b.w + 2 * m, h: b.h + 2 * m }); return true; }
|
|
1198
|
+
V.view = { ...V.view, x: b.x + b.w / 2 - V.view.w / 2, y: b.y + b.h / 2 - V.view.h / 2 };
|
|
1199
|
+
applyView();
|
|
1200
|
+
return true;
|
|
1201
|
+
}
|
|
1202
|
+
let pendingReveal: Path[] | undefined;
|
|
1203
|
+
ifEvents();
|
|
1204
|
+
doc.onSelect(c => {
|
|
1205
|
+
paintOverlay();
|
|
1206
|
+
if (c.origin === 'canvas' || !c.paths.length) return;
|
|
1207
|
+
// a selection made elsewhere (the tree, a paste): shown here, once it is drawn
|
|
1208
|
+
pendingReveal = reveal(c.paths) ? undefined : c.paths;
|
|
1209
|
+
});
|
|
1210
|
+
|
|
1211
|
+
const base = {
|
|
1212
|
+
addFromPalette, palette, groupSelection, startPick, objectsUnder, get linking() { return linking; },
|
|
1213
|
+
render, setTheme, paintOverlay, fit: fitItems, fitAll: fit, actual, zoomAt, itemsBox, get moved() { return V.moved; }, settled, get zoom() { return V.zoom; },
|
|
1214
|
+
dispose() { endMorph(); clearTimeout(relayout); V.dispose(); disposed = true; },
|
|
1215
|
+
focus: () => stage.focus(),
|
|
1216
|
+
/** for the tests */
|
|
1217
|
+
get view() { return V.view; },
|
|
1218
|
+
get doc() { return cd; },
|
|
1219
|
+
/** the view (3D or 2D), and the 2D layout while it shows */
|
|
1220
|
+
get mode() { return mode; }, setMode, get flat() { return flat?.layout; },
|
|
1221
|
+
stage, key, scale: () => scale(), nav, paintNav, outlinesFor, footprints, get drag() { return pinDrag(); }, get lastMarquee() { return lastMarquee; },
|
|
1222
|
+
boxFor, pageXYOf: (p: Path) => { const b = boxFor(p); const r = host.getBoundingClientRect(); const k = scale(); return b && V.view ? { x: r.left + (b.x + b.w / 2 - V.view.x) * k, y: r.top + (b.y + b.h / 2 - V.view.y) * k } : undefined; },
|
|
1223
|
+
};
|
|
1224
|
+
// the layer's calls, as they are (its getters stay getters)
|
|
1225
|
+
if (layer) Object.defineProperties(base, Object.getOwnPropertyDescriptors(layer.api));
|
|
1226
|
+
return base as typeof base & A;
|
|
1227
|
+
}
|