morphic-blocks 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -16,8 +16,8 @@
16
16
 
17
17
  Morphic Blocks is an embeddable TypeScript library built on top of
18
18
  [Google Blockly](https://developers.google.com/blockly). It renders one block
19
- model in multiple developer-defined **modes** — iconic, lexical, syntactic, or
20
- any representation you design — to support the gradual transition between
19
+ model in multiple developer-defined **modes** (icons, words, code or any
20
+ representation you design) to support the gradual transition between
21
21
  block-based and text-based programming.
22
22
 
23
23
  ## Install
@@ -26,9 +26,23 @@ block-based and text-based programming.
26
26
  npm i morphic-blocks
27
27
  ```
28
28
 
29
- Blockly is a dependency, so it is installed for you. The code editor,
30
- codespace, and preview views additionally use CodeMirror — install those only if
31
- you need them:
29
+ Blockly comes with it. Its images and sounds (trash can, zoom buttons, clicks)
30
+ load from your own site, so visitors' browsers never contact another server.
31
+ Copy them to `blockly-media/` next to your page before `dev` and `build`:
32
+
33
+ ```json
34
+ "scripts": {
35
+ "dev": "morphic-blocks copy-media public/blockly-media && vite",
36
+ "build": "morphic-blocks copy-media public/blockly-media && vite build"
37
+ }
38
+ ```
39
+
40
+ `public/` is Vite's folder for static files; use your bundler's equivalent.
41
+ You can still load them from Blockly's server instead; see
42
+ [Privacy & External Requests](https://docs.morphicblocks.com/guides/privacy/).
43
+
44
+ The text views (codespace, preview, code editor) use CodeMirror. Install it
45
+ only if you use them:
32
46
 
33
47
  ```sh
34
48
  npm i @codemirror/state @codemirror/view @codemirror/lang-javascript
@@ -36,41 +50,96 @@ npm i @codemirror/state @codemirror/view @codemirror/lang-javascript
36
50
 
37
51
  ## Quick start
38
52
 
53
+ A block is defined once, with one element per representation:
54
+
55
+ ```jsonc
56
+ // definitions.json
57
+ {
58
+ "elementTypes": {
59
+ "title": "text",
60
+ "conceptual": "code",
61
+ "python": "code"
62
+ },
63
+ "modes": [
64
+ { "name": "conceptual", "elements": ["title", "conceptual"] },
65
+ { "name": "python", "elements": ["title", "python"] }
66
+ ],
67
+ "blocks": [
68
+ {
69
+ "identifier": "text_print",
70
+ "elements": {
71
+ "title": "Print",
72
+ "conceptual": "Output %1",
73
+ "python": "print(%1)"
74
+ },
75
+ "inputSlots": {
76
+ "1": { "kind": "value", "name": "TEXT" }
77
+ }
78
+ }
79
+ ]
80
+ }
81
+ ```
82
+
83
+ A behavior writes the JavaScript that runs, one function per block:
84
+
39
85
  ```ts
86
+ // behaviors.ts
87
+ import type { MorphicBehaviorMap } from "morphic-blocks";
88
+
89
+ export const behaviors: MorphicBehaviorMap = {
90
+ text_print(proxy) {
91
+ return `console.log(${proxy.inputs.TEXT ?? "undefined"});\n`;
92
+ },
93
+ };
94
+ ```
95
+
96
+ One call sets up every view it gets a container for:
97
+
98
+ ```ts
99
+ // main.ts
40
100
  import { MorphicBlocks } from "morphic-blocks";
41
101
  import definitions from "./definitions.json";
42
102
  import { behaviors } from "./behaviors";
43
103
 
44
- // Modes, presets and categories all come from the definitions file, passed as
45
- // imported; mount() validates it.
46
104
  const engine = new MorphicBlocks(definitions, behaviors);
47
105
 
48
- // One call sets up every view it gets a container for.
49
106
  engine.mount({
50
107
  workspaceContainer: document.getElementById("workspace")!,
51
108
  toolboxContainer: document.getElementById("toolbox")!,
52
- preset: "conceptual", // a preset from definitions.json; without presets the first mode is used
53
109
  });
54
110
 
55
- // switch representation at runtime; the same blocks re-render
56
- engine.applyPreset("python");
111
+ // Switch the representation at runtime; the same blocks re-render.
112
+ engine.setModes({ workspaceMode: "python", toolboxMode: "python" });
57
113
  ```
58
114
 
115
+ ## How it works
116
+
117
+ 1. **Definitions** name each block's elements: labels, images and code
118
+ templates.
119
+ 2. **Modes** choose which elements show, one CSS file per mode styles them.
120
+ 3. **Views** (workspace, toolbox, codespace, preview) each show a mode, and
121
+ presets switch them together.
122
+
59
123
  ## Features
60
124
 
61
- - **One definition, many representations** — define a block once; render it as
62
- icons, blocks, or source text, switchable at runtime.
63
- - **Config-driven** — blocks in JSON, behaviors in TypeScript, one CSS file per
64
- mode. No per-representation duplication.
65
- - **Headless & embeddable** — bring your own UI; the framework stays unstyled.
66
- - **Built on Blockly** — the proven engine stays authoritative underneath.
125
+ - **One definition, many representations:** define a block once and show it
126
+ as icons, blocks or source text, switchable at runtime.
127
+ - **Blocks and text side by side:** an editable text view of the program, a
128
+ read only preview and selection that follows across views.
129
+ - **Config driven:** blocks in JSON, behaviors in TypeScript, one CSS file per
130
+ mode, with no duplication per representation.
131
+ - **Headless and embeddable:** bring your own UI; the framework stays unstyled.
132
+ - **Accessible toolbox:** tiles work with a mouse, a finger, a pen or the
133
+ keyboard, with names for screen readers.
134
+ - **No external requests:** the framework never contacts another server,
135
+ Blockly's media included.
67
136
 
68
137
  ## Documentation
69
138
 
70
- - **Website** — <https://morphicblocks.com>
71
- - **Docs** — <https://docs.morphicblocks.com>
72
- - **Playground** — <https://playground.morphicblocks.com>
73
- - **Source** — <https://github.com/morphicblocks/morphic-blocks>
139
+ - **Website:** <https://morphicblocks.com>
140
+ - **Docs:** <https://docs.morphicblocks.com>
141
+ - **Playground:** <https://playground.morphicblocks.com>
142
+ - **Source:** <https://github.com/morphicblocks/morphic-blocks>
74
143
 
75
144
  ## License
76
145
 
@@ -25,10 +25,10 @@
25
25
  "type": "array",
26
26
  "items": { "$ref": "#/$defs/preset" }
27
27
  },
28
- "highlighting": {
29
- "description": "Token-level highlight rules, keyed by code-element name.",
28
+ "code": {
29
+ "description": "How each code element's language is written, keyed by code element name.",
30
30
  "type": "object",
31
- "additionalProperties": { "$ref": "#/$defs/highlight" }
31
+ "additionalProperties": { "$ref": "#/$defs/codeElement" }
32
32
  },
33
33
  "categories": {
34
34
  "type": "array",
@@ -52,15 +52,6 @@
52
52
  "required": ["type"],
53
53
  "properties": {
54
54
  "type": { "$ref": "#/$defs/elementType" },
55
- "empty": {
56
- "description": "Per-check empty-slot defaults, keyed by the slot's check (e.g. Number, String, Boolean).",
57
- "type": "object",
58
- "additionalProperties": { "$ref": "#/$defs/emptyDefault" }
59
- },
60
- "stringQuote": {
61
- "description": "Delimiter wrapped around framework-supplied literals in String slots (code elements).",
62
- "type": "string"
63
- },
64
55
  "size": {
65
56
  "description": "Display size for image elements: a number, \"32\", or \"32x32\".",
66
57
  "type": ["number", "string"]
@@ -70,6 +61,50 @@
70
61
  }
71
62
  ]
72
63
  },
64
+ "codeElement": {
65
+ "type": "object",
66
+ "properties": {
67
+ "stringQuote": {
68
+ "description": "Delimiter wrapped around framework-supplied literals in String slots.",
69
+ "type": "string"
70
+ },
71
+ "empty": {
72
+ "description": "Per-check empty-slot defaults, keyed by the slot's check (e.g. Number, String, Boolean).",
73
+ "type": "object",
74
+ "additionalProperties": { "$ref": "#/$defs/emptyDefault" }
75
+ },
76
+ "emptyStatement": {
77
+ "description": "Written into an empty statement slot where an empty body is invalid, e.g. \"pass\" for Python.",
78
+ "type": "string"
79
+ },
80
+ "highlighting": { "$ref": "#/$defs/highlight" },
81
+ "values": {
82
+ "description": "How printed values are written while this element is shown, e.g. Python's True, None and ['a', 'b'].",
83
+ "type": "object",
84
+ "properties": {
85
+ "true": { "type": "string" },
86
+ "false": { "type": "string" },
87
+ "null": { "type": "string" },
88
+ "undefined": { "type": "string" },
89
+ "NaN": { "type": "string" },
90
+ "Infinity": { "type": "string" },
91
+ "-Infinity": { "type": "string" },
92
+ "list": {
93
+ "type": "object",
94
+ "properties": {
95
+ "open": { "type": "string" },
96
+ "close": { "type": "string" },
97
+ "separator": { "type": "string" },
98
+ "quote": { "type": "string" }
99
+ },
100
+ "additionalProperties": false
101
+ }
102
+ },
103
+ "additionalProperties": false
104
+ }
105
+ },
106
+ "additionalProperties": false
107
+ },
73
108
  "emptyDefault": {
74
109
  "type": "object",
75
110
  "properties": {
@@ -120,7 +155,12 @@
120
155
  "toolbox": { "$ref": "#/$defs/presetToolbox" },
121
156
  "workspace": { "type": "string" },
122
157
  "codespace": { "type": "string" },
123
- "preview": { "type": "string" }
158
+ "preview": { "type": "string" },
159
+ "views": {
160
+ "description": "Modes of views added with addView(), by view name.",
161
+ "type": "object",
162
+ "additionalProperties": { "type": "string" }
163
+ }
124
164
  },
125
165
  "additionalProperties": false
126
166
  },
@@ -128,7 +168,16 @@
128
168
  "type": "object",
129
169
  "properties": {
130
170
  "keywords": { "type": "array", "items": { "type": "string" } },
131
- "strings": { "type": "array", "items": { "type": "string" } },
171
+ "strings": {
172
+ "description": "A mark that opens and closes, or an [open, close] pair.",
173
+ "type": "array",
174
+ "items": {
175
+ "oneOf": [
176
+ { "type": "string" },
177
+ { "type": "array", "items": { "type": "string" }, "minItems": 2, "maxItems": 2 }
178
+ ]
179
+ }
180
+ },
132
181
  "comment": { "type": "string" },
133
182
  "numbers": { "type": "boolean" },
134
183
  "colors": {
package/dist/cli.js ADDED
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, existsSync, cpSync, writeFileSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { dirname, join, resolve } from "node:path";
5
+ const USAGE = `Usage: morphic-blocks copy-media <folder>
6
+
7
+ Copies Blockly's images, cursors and sounds into <folder>, so your app serves
8
+ them itself. Morphic Blocks loads them from "blockly-media/" next to the page
9
+ unless you set blockly.media, so copy them to the folder served there:
10
+
11
+ npx morphic-blocks copy-media public/blockly-media
12
+
13
+ Copies only when the folder is new or Blockly was updated, so it can run
14
+ before every dev or build.`;
15
+ const MARKER = ".blockly-version";
16
+ const [command, folder, ...rest] = process.argv.slice(2);
17
+ if (command === "--help" || command === "-h") {
18
+ console.log(USAGE);
19
+ } else if (command !== "copy-media" || !folder || rest.length > 0) {
20
+ console.error(USAGE);
21
+ process.exitCode = 1;
22
+ } else {
23
+ const require2 = createRequire(import.meta.url);
24
+ const blockly = dirname(require2.resolve("blockly"));
25
+ const version = JSON.parse(readFileSync(join(blockly, "package.json"), "utf8")).version;
26
+ const target = resolve(folder);
27
+ const marker = join(target, MARKER);
28
+ if (existsSync(marker) && readFileSync(marker, "utf8").trim() === version) {
29
+ console.log(`Blockly ${version} media is already in ${folder}`);
30
+ } else {
31
+ cpSync(join(blockly, "media"), target, { recursive: true });
32
+ writeFileSync(marker, `${version}
33
+ `);
34
+ console.log(`Copied Blockly ${version} media to ${folder}`);
35
+ }
36
+ }
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import "blockly/blocks";
2
2
  export { MorphicBlocks } from "./morphic/MorphicBlocks";
3
3
  export { MorphicToolboxCanvas } from "./morphic/toolbox-canvas";
4
+ export { toCleanId } from "./morphic/block-namespace";
4
5
  export { toolbarItems, renderToolbar } from "./morphic/toolbar";
5
6
  export type { MorphicRunEventDetail, MorphicToolbarHandle, } from "./morphic/toolbar";
6
7
  export { makeResizable } from "./morphic/resize";
7
8
  export { validateDefinitions } from "./morphic/validate-definitions";
8
9
  export type { ValidateDefinitionsArgs, DefinitionValidationResult, } from "./morphic/validate-definitions";
9
10
  export type { MorphicResizeOptions, MorphicResizeHandle, } from "./morphic/resize";
10
- export type { MorphicElementType, MorphicElementTypeConfig, MorphicElementTypeEntry, MorphicEmptyDefaultConfig, MorphicHighlightDefinition, MorphicJavaScriptConfig, MorphicBehaviorContext, MorphicBehaviorDefinition, MorphicBehaviorMap, MorphicBehaviorProxy, MorphicBlockBehavior, MorphicBlockDefinition, MorphicBlockShape, MorphicBlocksFormat, MorphicBlocksFormatJson, MorphicCodeBehavior, MorphicCodeBlockPosition, MorphicCodeEditorOptions, MorphicCodeEditorTheme, MorphicCodeGenerationResult, MorphicCodeMetadata, MorphicConnectionSpec, MorphicDropdownOption, MorphicFieldDefinition, MorphicInputAlign, MorphicInputKind, MorphicInputSlotDefinition, MorphicModeName, MorphicMountConfig, MorphicPlaceholderEditTarget, MorphicPlaceholderRange, MorphicRenderContext, MorphicResolvedView, MorphicStyleBundle, MorphicToolbarConfig, MorphicToolbarCtx, MorphicToolbarDisplay, MorphicToolbarItem, MorphicToolbarPane, MorphicToolbarRender, MorphicToolboxCanvasOptions, MorphicToolboxCategory, MorphicToolboxConfig, MorphicToolboxLayout, MorphicBlockElements, MorphicModeDefinition, MorphicPresetDefinition, MorphicRunOutputLine, MorphicRunResult, MorphicPresetToolbox, MorphicSelectionSyncOptions, } from "./morphic/types";
11
+ export type { MorphicElementType, MorphicElementTypeConfig, MorphicElementTypeEntry, MorphicEmptyDefaultConfig, MorphicHighlightDefinition, MorphicJavaScriptConfig, MorphicBehaviorContext, MorphicBehaviorDefinition, MorphicBehaviorMap, MorphicBehaviorProxy, MorphicBlockBehavior, MorphicBlockDefinition, MorphicBlockShape, MorphicBlocksFormat, MorphicBlocksFormatJson, MorphicCodeElementConfig, MorphicValueFormat, MorphicViewHandle, MorphicViewKind, MorphicViewOptions, MorphicCodeBehavior, MorphicCodeBlockPosition, MorphicCodeEditorOptions, MorphicCodeEditorTheme, MorphicCodeGenerationResult, MorphicCodeMetadata, MorphicConnectionSpec, MorphicDropdownOption, MorphicFieldDefinition, MorphicInputAlign, MorphicInputKind, MorphicInputSlotDefinition, MorphicModeName, MorphicMountConfig, MorphicPlaceholderEditTarget, MorphicPlaceholderRange, MorphicRenderContext, MorphicResolvedView, MorphicStyleBundle, MorphicToolbarConfig, MorphicToolbarCtx, MorphicToolbarDisplay, MorphicToolbarItem, MorphicToolbarPane, MorphicToolbarRender, MorphicToolboxCanvasOptions, MorphicToolboxCategory, MorphicToolboxConfig, MorphicToolboxLayout, MorphicToolboxModeLabel, MorphicBlockElements, MorphicModeDefinition, MorphicPresetDefinition, MorphicRunOutputLine, MorphicRunResult, MorphicPresetToolbox, MorphicSelectionSyncOptions, } from "./morphic/types";
@@ -1,10 +1,12 @@
1
1
  import * as Blockly from "blockly";
2
2
  import { type MorphicToolbarHandle } from "./toolbar";
3
- import type { MorphicBehaviorMap, MorphicBlocksFormat, MorphicBlocksFormatJson, MorphicCodeEditorOptions, MorphicCodeEditorTheme, MorphicCodeGenerationResult, MorphicModeName, MorphicMountConfig, MorphicPresetDefinition, MorphicRunResult, MorphicSelectionSyncOptions, MorphicToolbarConfig, MorphicToolboxCanvasOptions } from "./types";
3
+ import type { MorphicBehaviorMap, MorphicBlocksFormat, MorphicBlocksFormatJson, MorphicCodeEditorOptions, MorphicCodeEditorTheme, MorphicCodeGenerationResult, MorphicModeName, MorphicMountConfig, MorphicPresetDefinition, MorphicRunResult, MorphicSelectionSyncOptions, MorphicToolbarConfig, MorphicToolboxCanvasOptions, MorphicViewHandle, MorphicViewOptions } from "./types";
4
4
  export declare class MorphicBlocks extends EventTarget {
5
5
  private readonly definitions;
6
6
  private readonly behaviors;
7
- private readonly elementTypes;
7
+ /** Element types with the mounted `code` settings folded in (see withCodeSettings). */
8
+ private elementTypes;
9
+ private readonly formatElementTypes;
8
10
  private readonly styles;
9
11
  private readonly registeredBlockTypes;
10
12
  private readonly toolbars;
@@ -16,11 +18,21 @@ export declare class MorphicBlocks extends EventTarget {
16
18
  private workspace?;
17
19
  private flyoutWorkspace?;
18
20
  private toolboxCanvas?;
21
+ /** Codespaces a tile dragged by touch or pen can be dropped on. */
22
+ private readonly tileDropTargets;
19
23
  private codeEditor?;
20
24
  private codespace?;
21
25
  private previewEditor?;
26
+ /** Views added with `addView()`, beside the ones `mount()` sets up. */
27
+ private readonly views;
28
+ /** The mode of each added workspace, read when its blocks are built. */
29
+ private readonly viewWorkspaceModes;
30
+ /** Numbers added views that are not given a name. */
31
+ private viewCount;
22
32
  private selectionSync?;
23
33
  private toolboxDefinition?;
34
+ /** Container the preview editor was mounted into. */
35
+ private previewHost?;
24
36
  private blockCategoryIndex;
25
37
  private appliedWorkspaceClasses;
26
38
  private appliedToolboxFlyoutClasses;
@@ -45,7 +57,9 @@ export declare class MorphicBlocks extends EventTarget {
45
57
  * runtime `mount()` call only carries DOM / runtime concerns. */
46
58
  private readonly formatModes?;
47
59
  private readonly formatPresets?;
48
- private readonly formatHighlighting?;
60
+ private readonly formatCode?;
61
+ /** The definitions still use the old top level `highlighting` map. */
62
+ private readonly formatHasHighlighting;
49
63
  private readonly formatCategories?;
50
64
  /**
51
65
  * Build an engine from a whole definitions file plus its behaviors — the two
@@ -97,6 +111,13 @@ export declare class MorphicBlocks extends EventTarget {
97
111
  * directly (e.g. creating blocks from code). Everyday use goes through the
98
112
  * engine. `undefined` before `mount`.
99
113
  */
114
+ /**
115
+ * Measure blocks and toolbox tiles again. Blockly measures block text only
116
+ * when it draws a block, so call this after the app changes the block font
117
+ * through its own CSS (a font size switch, say). Stylesheets and web fonts
118
+ * that finish loading are handled already.
119
+ */
120
+ refresh(): void;
100
121
  getWorkspace(): Blockly.WorkspaceSvg | undefined;
101
122
  /**
102
123
  * The declared mode names (`modes[].name` from the mount config). Empty until
@@ -113,6 +134,12 @@ export declare class MorphicBlocks extends EventTarget {
113
134
  getCodespaceMode(): MorphicModeName | undefined;
114
135
  /** Preview mode name, or `undefined` when no preview mode is set. */
115
136
  getPreviewMode(): MorphicModeName | undefined;
137
+ /**
138
+ * Change which elements a mode shows while the app runs, e.g. to let the
139
+ * user pick what a toolbox tile shows. Every view using the mode is redrawn;
140
+ * a mode a codespace or preview renders must keep a code element.
141
+ */
142
+ setModeElements(mode: MorphicModeName, elements: string[]): void;
116
143
  /** Mode definition by name, or `undefined`. */
117
144
  private modeDef;
118
145
  /** Source element rendered by the codespace (label + highlighting source). */
@@ -161,7 +188,7 @@ export declare class MorphicBlocks extends EventTarget {
161
188
  * (1) Blockly's selected block, (2) for codespace/preview, the deepest block
162
189
  * enclosing the active line. Returns true when something was copied.
163
190
  */
164
- copyActiveBlock(pane: "workspace" | "codespace" | "preview"): boolean;
191
+ copyActiveBlock(view: string): boolean;
165
192
  /**
166
193
  * Paste the last copied block at the active pane's natural location.
167
194
  * Workspace: Blockly's default (workspace centre, slightly offset).
@@ -170,18 +197,18 @@ export declare class MorphicBlocks extends EventTarget {
170
197
  * specific slot is deferred; the current behaviour matches Ctrl+V in
171
198
  * standard Blockly.) Returns true if something was pasted.
172
199
  */
173
- pasteActiveBlock(_pane: "workspace" | "codespace" | "preview"): boolean;
200
+ pasteActiveBlock(_view: string): boolean;
174
201
  private resolveActiveBlock;
175
202
  /** Serialize the workspace to a plain object (Blockly's native format). */
176
203
  serializeWorkspace(): unknown;
177
204
  /** Restore the workspace from a previously serialized state. */
178
205
  loadWorkspace(state: unknown): void;
179
206
  /**
180
- * Adjust the pane's zoom level. Direction is `"in" | "out" | "fit"`. For
181
- * the workspace pane this maps to `workspace.zoomCenter(±1)` /
182
- * `zoomToFit()`. For codespace/preview it scales the editor's font-size.
207
+ * Adjust a view's zoom level, by view name. Direction is `"in" | "out" |
208
+ * "fit"`. For the workspace this maps to `workspace.zoomCenter(±1)` /
209
+ * `zoomToFit()`. For a text view it scales the editor's font-size.
183
210
  */
184
- zoomPane(pane: "workspace" | "codespace" | "preview", direction: "in" | "out" | "fit"): void;
211
+ zoomPane(view: string, direction: "in" | "out" | "fit"): void;
185
212
  private ensureToolbarBlocklyListener;
186
213
  private teardownToolbarBlocklyListener;
187
214
  setModes(modes: {
@@ -252,6 +279,18 @@ export declare class MorphicBlocks extends EventTarget {
252
279
  * Connects to the slot directly when the slot is empty; otherwise walks to
253
280
  * the chain's tail and connects there.
254
281
  */
282
+ /**
283
+ * The drop as it will happen: unchanged when its connections fit, turned into
284
+ * its own stack when it was aimed into a top level chain, `null` otherwise.
285
+ */
286
+ private fitOrLoose;
287
+ /**
288
+ * Whether a codespace drop makes only connections the workspace would make:
289
+ * every connection it plans passes Blockly's connection checker, and no
290
+ * block is left behind outside the chain. Checked before anything changes,
291
+ * so a refused drop leaves the program as it was.
292
+ */
293
+ private codespaceDropAllowed;
255
294
  private connectIntoSlot;
256
295
  /**
257
296
  * Resolve a char-offset in the codespace to the value slot the drop should
@@ -270,6 +309,12 @@ export declare class MorphicBlocks extends EventTarget {
270
309
  private findValueSlotDropAtChar;
271
310
  /** Find the value-input that holds `child`, returning its parent + input name. */
272
311
  private resolveValueParent;
312
+ /**
313
+ * Add a block chosen on a tile with the keyboard: after the selected block
314
+ * when its connections fit there, else as a new stack below the others.
315
+ * The new block is selected, so choosing again builds a chain.
316
+ */
317
+ private addBlockFromTile;
273
318
  /**
274
319
  * Place a freshly-orphaned block at a clear workspace coordinate, below the
275
320
  * current bottom-most top block. Keeps replaced value children visible in
@@ -293,6 +338,8 @@ export declare class MorphicBlocks extends EventTarget {
293
338
  /** Connect `source` into `target`'s statement chain before/after `target`. */
294
339
  private connectStatement;
295
340
  private applyTopBlockOrder;
341
+ /** Write every text view again, added views included. */
342
+ private refreshTextViews;
296
343
  /**
297
344
  * Mounts a read-only preview editor that renders the current mode's
298
345
  * `preview` element as text. Re-renders on workspace and mode changes.
@@ -300,11 +347,52 @@ export declare class MorphicBlocks extends EventTarget {
300
347
  */
301
348
  mountPreview(container: HTMLElement, options?: MorphicCodeEditorOptions): Promise<void>;
302
349
  private generatePreviewText;
350
+ /** The program as `mode`'s source element writes it, as a preview shows it. */
351
+ private generateModeText;
352
+ /** Highlight rules of `mode`'s source element. */
353
+ private highlightRulesFor;
354
+ /**
355
+ * Add a view beside the ones `mount()` sets up, e.g. a second preview in
356
+ * another mode. Returns a handle to change its mode or remove it; a new
357
+ * `mount()` removes every added view.
358
+ */
359
+ addView(options: MorphicViewOptions): MorphicViewHandle;
360
+ /**
361
+ * A read only Blockly workspace in its own mode that mirrors the main one:
362
+ * it starts from a copy of the program and replays every change, the way
363
+ * Blockly mirrors workspaces. Selection runs both ways through the main
364
+ * workspace, so the text views follow a click in the mirror too.
365
+ */
366
+ private addWorkspaceView;
367
+ /** The mode's classes and block font on an added workspace. */
368
+ private styleWorkspaceView;
369
+ /** Draw every block of an added workspace in the view's mode. */
370
+ private renderWorkspaceView;
371
+ /** Remove an added view and everything it set up. */
372
+ private disposeView;
373
+ /**
374
+ * Take a ready added view into selection sync: relink an active sync, or
375
+ * start one now that more than one view is shown, as `mount()` would have,
376
+ * unless the host turned it off.
377
+ */
378
+ private linkAddedView;
379
+ /** A view by name, built in or added; `undefined` when there is none. */
380
+ private resolveView;
381
+ /** The mode a view shows, by name (`workspace`, `codespace`, `preview`, or an added view's). */
382
+ getViewMode(name: string): MorphicModeName | undefined;
383
+ /** A text view's mode must exist and have a code element to render. */
384
+ private checkTextViewMode;
303
385
  /**
304
386
  * Write `newValue` to `edit.fieldName` on the Blockly block identified by
305
387
  * `edit.blockId`. The change event listener will trigger codespace re-sync.
306
388
  */
307
389
  private applyPlaceholderEdit;
390
+ /**
391
+ * Whether a codespace grip may move the block: statement blocks
392
+ * (previousConnection) and value blocks (outputConnection), so the
393
+ * codespace mirrors Blockly's full set of moveable blocks.
394
+ */
395
+ private canMoveInCodespace;
308
396
  private deleteBlockAtCodespaceLine;
309
397
  private generateCodespaceText;
310
398
  showCodeEditor(): void;
@@ -335,6 +423,13 @@ export declare class MorphicBlocks extends EventTarget {
335
423
  private createHeadlessHost;
336
424
  private resolveMode;
337
425
  private applyView;
426
+ /**
427
+ * The classes and colours a block's drawing takes from its definition and
428
+ * the mode's CSS. Needs the block's SVG, so a block built before it had one
429
+ * is styled again once it does.
430
+ */
431
+ private styleBlock;
432
+ private applyTextViewClasses;
338
433
  private applyWorkspaceContainerClass;
339
434
  /**
340
435
  * Measure block text with the font the workspace mode's CSS draws it in.
@@ -343,6 +438,8 @@ export declare class MorphicBlocks extends EventTarget {
343
438
  * overrides it, exactly like real block text.
344
439
  */
345
440
  private syncWorkspaceFont;
441
+ /** Measure a workspace's blocks with the font its host's mode CSS sets. */
442
+ private syncFontOf;
346
443
  private readonly onStylesLoaded;
347
444
  private applyFlyoutClass;
348
445
  private renderWorkspaceBlocks;
@@ -12,6 +12,12 @@ export type MorphicManagedBlock = Blockly.BlockSvg & {
12
12
  * lifecycle and restores them by design.
13
13
  */
14
14
  __morphicPlaceholderSlots?: Set<string>;
15
+ /**
16
+ * Every field value the block has had, by field name. A mode whose template
17
+ * leaves a field out rebuilds the block without it; the value waits here
18
+ * until a mode that shows the field again restores it.
19
+ */
20
+ __morphicFieldMemory?: Map<string, unknown>;
15
21
  };
16
22
  export interface MorphicApplyBlockViewParams {
17
23
  block: Blockly.BlockSvg;
@@ -35,6 +41,12 @@ export interface MorphicApplyBlockViewParams {
35
41
  resolveBlocklyType?: (ref: string) => string;
36
42
  }
37
43
  export declare function applyBlockView(params: MorphicApplyBlockViewParams): void;
44
+ /**
45
+ * Whether a block is drawn on its workspace yet. Blockly calls a new block
46
+ * `rendered` before its SVG is placed; drawing it then draws it at 0,0, and
47
+ * Blockly pushes blocks there out of its way.
48
+ */
49
+ export declare function isOnCanvas(block: Blockly.BlockSvg): boolean;
38
50
  export declare function applyRootModeClasses(root: Element, mode: MorphicModeName, context: MorphicRenderContext, rootClassName: string): void;
39
51
  export declare function getManagedBlockMode(block: Blockly.Block): string | undefined;
40
52
  export declare function applyBlockCategoryClass(block: Blockly.BlockSvg, categoryToken?: string): void;
@@ -50,5 +62,11 @@ export declare function applyBlockIdentifierClass(block: Blockly.BlockSvg, ident
50
62
  * when a value is found. This lets mode CSS files drive block colours declaratively.
51
63
  */
52
64
  export declare function applyBlockColorFromCSS(block: Blockly.BlockSvg): void;
65
+ /**
66
+ * Mark a text view (codespace, preview) with the mode it shows, so a mode's
67
+ * CSS can style it like the workspace and the tiles.
68
+ */
69
+ export declare function applyTextViewModeClass(root: Element, mode: MorphicModeName | undefined, rootClassName: string): void;
70
+ export declare function decorateBlockRoot(block: Blockly.BlockSvg, mode: MorphicModeName, context: MorphicRenderContext): void;
53
71
  export declare function captureFieldValues(block: Blockly.BlockSvg): Map<string, unknown>;
54
72
  export declare function restoreFieldValues(block: Blockly.BlockSvg, values: Map<string, unknown>): void;
@@ -18,6 +18,8 @@ export declare function getActiveGripDragSourceId(): string | undefined;
18
18
  /** Mark a block id as the active grip-drag source (e.g. from a placeholder-range drag). */
19
19
  export declare function setActiveGripDragSourceId(id: string | undefined): void;
20
20
  export declare class MorphicCodeEditor {
21
+ /** Use JavaScript language support; only the code editor does. */
22
+ private readonly javascript;
21
23
  private editorView?;
22
24
  private container;
23
25
  private options;
@@ -72,7 +74,11 @@ export declare class MorphicCodeEditor {
72
74
  private themeCompartment?;
73
75
  private syntaxHighlightCompartment?;
74
76
  private highlightEffect?;
75
- private highlightColor;
77
+ /** The host's highlight colour; without one, the theme's selection colour is used. */
78
+ private highlightColor?;
79
+ private themeSelection;
80
+ /** The lines highlighted now, drawn again when the colour changes. */
81
+ private activeHighlight?;
76
82
  private metadataEffect?;
77
83
  private placeholderEffect?;
78
84
  private dropIndicatorEffect?;
@@ -81,7 +87,9 @@ export declare class MorphicCodeEditor {
81
87
  private editableHoverHighlightEffect?;
82
88
  private emptyClickListener?;
83
89
  private disposed;
84
- constructor(container: HTMLElement, workspace: Blockly.WorkspaceSvg, generateWithMetadata: () => MorphicCodeGenerationResult, options?: MorphicCodeEditorOptions);
90
+ constructor(container: HTMLElement, workspace: Blockly.WorkspaceSvg, generateWithMetadata: () => MorphicCodeGenerationResult, options?: MorphicCodeEditorOptions,
91
+ /** Use JavaScript language support; only the code editor does. */
92
+ javascript?: boolean);
85
93
  mount(): Promise<void>;
86
94
  private buildDeleteExtensions;
87
95
  private buildGripExtensions;
@@ -124,8 +132,8 @@ export declare class MorphicCodeEditor {
124
132
  highlightLines(spans: LineSpan | LineSpan[]): void;
125
133
  /** Remove all line highlights. */
126
134
  clearHighlight(): void;
127
- /** Update the highlight background colour. */
128
- setHighlightColor(color: string): void;
135
+ /** Update the highlight background colour; `undefined` follows the theme's selection colour. */
136
+ setHighlightColor(color: string | undefined): void;
129
137
  /** Show a drop-position indicator above (or below) the given 1-based line. */
130
138
  showDropIndicator(line: number, position?: "above" | "below"): void;
131
139
  /** Hide the drop-position indicator if currently shown. */
@@ -1,6 +1,14 @@
1
- import type { MorphicElementType, MorphicElementTypeEntry, MorphicEmptyDefaultConfig, MorphicInputSlotDefinition } from "./types";
1
+ import type { MorphicCodeElementConfig, MorphicElementType, MorphicElementTypeConfig, MorphicElementTypeEntry, MorphicEmptyDefaultConfig, MorphicInputSlotDefinition } from "./types";
2
2
  /** Get the rendering type of an entry, normalising bare strings vs config. */
3
3
  export declare function resolveElementType(entry: MorphicElementTypeEntry | undefined): MorphicElementType | undefined;
4
+ /**
5
+ * An element type entry with its code element's settings from the `code`
6
+ * section folded in. Internal: the renderers read the settings from the entry
7
+ * they already hold for the element.
8
+ */
9
+ export type MorphicElementTypeWithCode = MorphicElementTypeConfig & Pick<MorphicCodeElementConfig, "empty" | "stringQuote" | "emptyStatement">;
10
+ /** `elementTypes` with each code element's `code` settings folded in. */
11
+ export declare function withCodeSettings(elementTypes: Record<string, MorphicElementTypeEntry>, code: Record<string, MorphicCodeElementConfig> | undefined): Record<string, MorphicElementTypeEntry>;
4
12
  /**
5
13
  * Resolve the display size for a `type: "image"` element. Reads the optional
6
14
  * `size` field on `MorphicElementTypeConfig`; falls back to 16×16. Accepts a
@@ -12,8 +20,8 @@ export declare function resolveImageSize(entry: MorphicElementTypeEntry | undefi
12
20
  };
13
21
  /**
14
22
  * Resolve the empty-state default config for a value slot. Honours the
15
- * priority chain: per-slot `default` (highest) → elementType `empty[check]` →
16
- * elementType `empty.default` (catch-all, also used when the slot has no
23
+ * priority chain: per-slot `default` (highest) → the code element's
24
+ * `empty[check]` → its `empty.default` (catch-all, also used when the slot has no
17
25
  * `check`). Returns undefined when nothing is configured — callers should treat
18
26
  * that as "show the codespace marker / empty workspace socket."
19
27
  */