morphic-blocks 0.0.1 → 0.1.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.
@@ -0,0 +1,622 @@
1
+ import type * as Blockly from "blockly";
2
+ export type MorphicModeName = string;
3
+ /**
4
+ * The rendering type of a named element.
5
+ * - "text" — rendered as an HTML label; never shown in the workspace
6
+ * - "code" — template with %N placeholders; rendered as a Blockly block in the workspace or as text in the codespace
7
+ * - "image" — rendered as an <img> in the toolbox tile; never shown in the workspace
8
+ */
9
+ export type MorphicElementType = "text" | "code" | "image";
10
+ /**
11
+ * Configuration for a value slot's empty-state default. Keyed by slot
12
+ * `check` in `elementTypes[name].empty[check]`, or set per-slot via
13
+ * `inputSlot.default`. Both `shadow` and `placeholder` are optional; when
14
+ * both are configured, the placeholder is created first and Blockly's
15
+ * native shadow restoration brings the shadow up if the user removes the
16
+ * placeholder.
17
+ */
18
+ export interface MorphicEmptyDefaultConfig {
19
+ /**
20
+ * Blockly block type used as a *shadow* — ghosted, immutable, auto-replaced
21
+ * when a real block connects, restored when the user disconnects.
22
+ * Standard examples: `"math_number"`, `"text"`, `"logic_boolean"`.
23
+ * The shadow's output type must be compatible with the slot's `check`,
24
+ * otherwise Blockly silently rejects the connection.
25
+ */
26
+ shadow?: string;
27
+ /**
28
+ * Blockly block type used as a *placeholder* — a real (non-shadow) block
29
+ * attached on render. Movable, editable, deletable. When both `shadow`
30
+ * and `placeholder` are configured, the placeholder takes priority on
31
+ * the visible slot.
32
+ */
33
+ placeholder?: string;
34
+ /**
35
+ * Initial values applied to the chosen block's internal Blockly fields
36
+ * (e.g. `{ NUM: "0" }` for `math_number`, `{ TEXT: "text" }` for `text`).
37
+ * Plural because a single shadow/placeholder block can carry multiple
38
+ * fields (`{ MIN: "0", MAX: "100", STEP: "1" }` for a range picker).
39
+ */
40
+ fieldValues?: Record<string, string>;
41
+ }
42
+ /**
43
+ * Optional per-element configuration. Used in place of a bare type string in
44
+ * `elementTypes` when the developer needs to declare extras (e.g. shadows /
45
+ * placeholders for empty value slots).
46
+ */
47
+ export interface MorphicElementTypeConfig {
48
+ type: MorphicElementType;
49
+ /**
50
+ * Per-slot-check defaults for empty value inputs. Keys are the slot's
51
+ * `check` string (e.g. `"Number"`, `"String"`, or any developer-defined
52
+ * check name). Slots without a matching key get no default — the codespace
53
+ * renders a `[TYPE]` marker (e.g. `[NUMBER]`) and the workspace shows an empty
54
+ * socket. Per-slot overrides via `inputSlots[i].default` take priority.
55
+ */
56
+ empty?: Record<string, MorphicEmptyDefaultConfig>;
57
+ /**
58
+ * String delimiter used to wrap framework-supplied literals (shadow values
59
+ * and empty-slot fallbacks) in `String`-checked value slots, so the
60
+ * codespace renders e.g. `print("hello")` rather than `print(hello)`. The
61
+ * quotes are emitted around the value but outside the editable marker, so
62
+ * inline editing targets only the inner text. Only applies to literals the
63
+ * framework supplies; user-attached real blocks render via their own
64
+ * templates (a `var_get` stays bare, a `text_value` quotes itself).
65
+ * Language-specific (`"\""` for most languages); omit to disable quoting.
66
+ */
67
+ stringQuote?: string;
68
+ /**
69
+ * Display size for `type: "image"` elements. Used when the element value is
70
+ * a file path (e.g. `"assets/icon.svg"`) and the framework auto-wraps it as
71
+ * an `<img>` tag. Accepted formats:
72
+ * - number: square, e.g. `32` → 32×32
73
+ * - `"32"`: square
74
+ * - `"32x32"`: explicit width × height
75
+ * Defaults to 16×16 if omitted. Ignored for non-image element types and for
76
+ * values that are already `<img>` HTML.
77
+ */
78
+ size?: number | string;
79
+ }
80
+ /** Either a bare type or a config object with extras. */
81
+ export type MorphicElementTypeEntry = MorphicElementType | MorphicElementTypeConfig;
82
+ export type MorphicConnectionSpec = boolean | string | string[];
83
+ export type MorphicInputKind = "value" | "statement";
84
+ export type MorphicInputAlign = "left" | "centre" | "right";
85
+ /**
86
+ * One choice in a declared `dropdown` field. The `value` is the source of
87
+ * truth: it is what the block *generates*, serializes, and executes. The
88
+ * optional `label` is a display-only override shown on the workspace block
89
+ * (e.g. show `÷` while generating `/`); when omitted the value is shown.
90
+ *
91
+ * `display` makes the *shown* text mode-aware without touching the value: it
92
+ * maps an **element name** (like `highlighting` is keyed) to the text shown
93
+ * when that element is rendered — so a Python source shows `True` while
94
+ * JavaScript shows `true`, both storing/executing the same value. Resolution
95
+ * when rendering element `E`: block text `display[E] ?? label ?? value`;
96
+ * codespace/preview text `display[E] ?? value` (`label` stays block-only).
97
+ * Only the representation axis — natural-language translation is separate.
98
+ *
99
+ * Forms:
100
+ * - `"=="` → value = label = `"=="`
101
+ * - `["-", "−"]` → value `"-"`, shown as `"−"` on the block
102
+ * - `{ value, label?, display? }` → explicit object form
103
+ */
104
+ export type MorphicDropdownOption = string | [value: string, label: string] | {
105
+ value: string;
106
+ label?: string;
107
+ display?: Record<string, string>;
108
+ };
109
+ /**
110
+ * A field declared directly on a block (rendered at the `%FIELDNAME` token
111
+ * position). Lets dropdown / text / number / checkbox fields live in the
112
+ * definitions file instead of requiring a behavior's `onViewApplied`. Fields
113
+ * outside these four (variables, colour, plugin/custom) still use
114
+ * `onViewApplied` — the `%FIELDNAME` token is skipped when no declaration
115
+ * exists, leaving the behavior to supply the field.
116
+ */
117
+ export type MorphicFieldDefinition = {
118
+ type: "dropdown";
119
+ options: MorphicDropdownOption[];
120
+ default?: string;
121
+ } | {
122
+ type: "text";
123
+ default?: string;
124
+ } | {
125
+ type: "number";
126
+ default?: number;
127
+ min?: number;
128
+ max?: number;
129
+ precision?: number;
130
+ } | {
131
+ type: "checkbox";
132
+ default?: boolean;
133
+ };
134
+ export interface MorphicInputSlotDefinition {
135
+ kind?: MorphicInputKind;
136
+ name?: string;
137
+ check?: string | string[];
138
+ align?: MorphicInputAlign;
139
+ label?: string;
140
+ /**
141
+ * Block-level override for this slot's empty-state default. Highest
142
+ * priority: when set, takes precedence over the elementType-level
143
+ * `empty[check]` lookup. Lets a specific block (e.g. a tutorial's first
144
+ * `print` block) supply richer defaults than its language's generic ones.
145
+ */
146
+ default?: MorphicEmptyDefaultConfig;
147
+ }
148
+ /**
149
+ * Named visual parts of a Morphic Block.
150
+ * Keys are element names (e.g. "icon", "block", "code", "text") — free-form, not enforced.
151
+ * Values are template strings (same syntax as before: %1 placeholders, <img> tags, plain text).
152
+ * The "block" element is used as the Blockly workspace template.
153
+ */
154
+ export type MorphicBlockElements = Record<string, string>;
155
+ /**
156
+ * A named per-view mode configuration. Presence of a view key means that view
157
+ * is part of the preset: `toolbox` is required, and at least one editing
158
+ * space (`workspace` or `codespace`) must be set; `preview` is optional.
159
+ */
160
+ /**
161
+ * A preset's toolbox: either a bare mode name (all code elements render as
162
+ * blocks) or an object that additionally overrides, per element, whether a
163
+ * `code` element renders as a draggable block or as source text in the tile.
164
+ */
165
+ export type MorphicPresetToolbox = MorphicModeName | {
166
+ mode: MorphicModeName;
167
+ render?: Record<string, "block" | "text">;
168
+ };
169
+ export interface MorphicPresetDefinition {
170
+ name: string;
171
+ /** Display label (e.g. for buttons). Falls back to `name`. */
172
+ label?: string;
173
+ toolbox: MorphicPresetToolbox;
174
+ workspace?: MorphicModeName;
175
+ codespace?: MorphicModeName;
176
+ preview?: MorphicModeName;
177
+ }
178
+ /**
179
+ * Declares which elements are visible for a given mode.
180
+ * CSS (one file per mode) controls how those elements look.
181
+ * A mode's source element (rendered in editing spaces and previews) is the
182
+ * first element in `elements` whose type is "code".
183
+ */
184
+ export interface MorphicModeDefinition {
185
+ name: string;
186
+ /** Element names that are visible in this mode (e.g. ["icon", "text"]). */
187
+ elements: string[];
188
+ }
189
+ export interface MorphicBlockDefinition {
190
+ identifier: string;
191
+ /**
192
+ * Named visual elements of this Morphic Block.
193
+ * The "block" element (if present) is used as the Blockly workspace template.
194
+ * Falls back to the first element if "block" is absent.
195
+ */
196
+ elements: MorphicBlockElements;
197
+ /**
198
+ * Input slot definitions keyed by placeholder index ("1", "2", …).
199
+ * Applies to the workspace ("block") element template.
200
+ */
201
+ inputSlots?: Record<string, MorphicInputSlotDefinition>;
202
+ /**
203
+ * Inline field definitions keyed by `%FIELDNAME` token name (uppercase, e.g.
204
+ * "OP", "NUM", "TEXT"). Rendered at the token position on the workspace block
205
+ * and read by text/preview views and codegen. Types outside the built-in four
206
+ * (dropdown / text / number / checkbox) are supplied by a behavior's
207
+ * `onViewApplied` instead.
208
+ */
209
+ fields?: Record<string, MorphicFieldDefinition>;
210
+ color?: number | string;
211
+ output?: MorphicConnectionSpec;
212
+ previousStatement?: MorphicConnectionSpec;
213
+ nextStatement?: MorphicConnectionSpec;
214
+ inputsInline?: boolean;
215
+ tooltip?: string;
216
+ helpUrl?: string;
217
+ /** Category name this block belongs to. */
218
+ category?: string;
219
+ }
220
+ /**
221
+ * Token-level highlighting rules for a code element. Keyed by element name
222
+ * (e.g. "python", "javascript", "concept") so a mode's source element already
223
+ * names the language — no separate `language` field is needed on modes.
224
+ *
225
+ * The framework applies these as `Decoration.mark` ranges via a CodeMirror
226
+ * `ViewPlugin`. Highlighting deliberately does NOT install a CodeMirror
227
+ * language (no bracket matching, no auto-indent, no autocomplete) — Code
228
+ * Blocks treats text as a rendered view, not a freeform editing surface.
229
+ */
230
+ export interface MorphicHighlightDefinition {
231
+ /** Words to highlight as keywords (exact match against `[A-Za-z_]\w*` tokens). */
232
+ keywords?: string[];
233
+ /** String delimiters (e.g. `["\"", "'"]`). Span until matching close on same line. */
234
+ strings?: string[];
235
+ /** Line-comment marker (e.g. `"#"`, `"//"`). Highlights from the marker to end of line. */
236
+ comment?: string;
237
+ /** Highlight integer/decimal numeric literals. Defaults to true; pass `false` to disable. */
238
+ numbers?: boolean;
239
+ /** Per-token-class color overrides. Each is optional; framework provides sensible defaults. */
240
+ colors?: {
241
+ keyword?: string;
242
+ string?: string;
243
+ number?: string;
244
+ comment?: string;
245
+ };
246
+ }
247
+ /** Top-level format for a definitions JSON file. */
248
+ export interface MorphicBlocksFormat {
249
+ /** JSON Schema reference for editor tooling. Ignored by the framework. */
250
+ $schema?: string;
251
+ /** Definitions format version. Current: 1. */
252
+ version?: number;
253
+ /**
254
+ * Global element type registry.
255
+ * Maps each element name to either a bare type ("text" | "code" | "image")
256
+ * or a config object (`{ type, empty? }`). Declared once here; per-block
257
+ * elements remain plain name→content strings.
258
+ */
259
+ elementTypes?: Record<string, MorphicElementTypeEntry>;
260
+ /** Explicit mode definitions — which elements are visible per mode. */
261
+ modes?: MorphicModeDefinition[];
262
+ /** Named per-view mode configurations. Used as the mount default for `presets`. */
263
+ presets?: MorphicPresetDefinition[];
264
+ /**
265
+ * Per-element highlight rules, keyed by element name. The codespace and
266
+ * preview modes' source elements look up entries here for their editors.
267
+ */
268
+ highlighting?: Record<string, MorphicHighlightDefinition>;
269
+ /** Optional category metadata. Blocks reference categories by name. */
270
+ categories?: MorphicToolboxCategory[];
271
+ /** Flat array of block definitions. */
272
+ blocks: MorphicBlockDefinition[];
273
+ }
274
+ export type MorphicRenderContext = "workspace" | "toolbox";
275
+ export interface MorphicBehaviorContext {
276
+ Blockly: typeof Blockly;
277
+ workspace: Blockly.WorkspaceSvg;
278
+ mode: MorphicModeName;
279
+ context: MorphicRenderContext;
280
+ definition: MorphicBlockDefinition;
281
+ }
282
+ export interface MorphicBehaviorProxy {
283
+ blockId: string;
284
+ blockType: string;
285
+ mode: MorphicModeName;
286
+ context: MorphicRenderContext;
287
+ inputs: Record<string, string>;
288
+ fields: Record<string, string>;
289
+ }
290
+ export type MorphicCodeBehavior = (proxy: MorphicBehaviorProxy) => string;
291
+ export interface MorphicBlockBehavior {
292
+ init?: (block: Blockly.BlockSvg, context: MorphicBehaviorContext) => void;
293
+ onViewApplied?: (block: Blockly.BlockSvg, context: MorphicBehaviorContext) => void;
294
+ generate?: MorphicCodeBehavior;
295
+ }
296
+ export type MorphicBehaviorDefinition = MorphicBlockBehavior | MorphicCodeBehavior;
297
+ export type MorphicBehaviorMap = Record<string, MorphicBehaviorDefinition>;
298
+ export interface MorphicModeStyle {
299
+ mode: MorphicModeName;
300
+ href?: string;
301
+ cssText?: string;
302
+ }
303
+ export interface MorphicStyleBundle {
304
+ href?: string;
305
+ cssText?: string;
306
+ }
307
+ export interface MorphicToolboxCategory {
308
+ name: string;
309
+ color?: string;
310
+ /** Explicit block list. If omitted the framework derives it from block definitions whose `category` matches this name. */
311
+ blocks?: string[];
312
+ }
313
+ export type MorphicToolboxLayout = "flyout" | "category";
314
+ export interface MorphicToolboxConfig {
315
+ kind?: "flyoutToolbox" | "categoryToolbox";
316
+ blocks?: string[];
317
+ categories?: MorphicToolboxCategory[];
318
+ }
319
+ /** Options for the custom HTML toolbox canvas (mountToolbox). */
320
+ export interface MorphicToolboxCanvasOptions {
321
+ /** Render a "Mode: <name>" header at the top of the toolbox. Defaults to true. */
322
+ modeLabel?: boolean;
323
+ /** Show only a subset of blocks. Defaults to all blocks in definitions. */
324
+ blocks?: string[];
325
+ /**
326
+ * Category grouping for the toolbox canvas.
327
+ * If omitted, falls back to categories from mount config.
328
+ * If neither is provided, blocks render as a flat list.
329
+ */
330
+ categories?: MorphicToolboxCategory[];
331
+ }
332
+ export interface MorphicJavaScriptConfig {
333
+ statementPrefix?: string | null;
334
+ statementSuffix?: string | null;
335
+ infiniteLoopTrap?: string | null;
336
+ reservedWords?: string;
337
+ }
338
+ export interface MorphicMountConfig {
339
+ /**
340
+ * Container for the Blockly workspace. Optional — may be omitted when only a
341
+ * codespace is used. At least one of `workspaceContainer` or `codespaceContainer`
342
+ * must be provided. When omitted, Blockly runs headless (offscreen) so the block
343
+ * model stays available.
344
+ */
345
+ workspaceContainer?: HTMLElement;
346
+ /**
347
+ * Container for the primary text editor (codespace). Optional — required
348
+ * when a `codespaceMode` is used.
349
+ */
350
+ codespaceContainer?: HTMLElement;
351
+ /** Mode definitions — drives automatic element visibility CSS. */
352
+ modes?: MorphicModeDefinition[];
353
+ /**
354
+ * Named per-view mode configurations. Validated at mount. When provided,
355
+ * the initial modes are derived from `preset` (or the first preset).
356
+ */
357
+ presets?: MorphicPresetDefinition[];
358
+ /** Name of the preset applied at mount. Defaults to the first preset. */
359
+ preset?: string;
360
+ /**
361
+ * Called after a preset is applied — at mount and on every `applyPreset` —
362
+ * so the host can lay out pane visibility (a view is shown iff its key is
363
+ * present on the preset).
364
+ */
365
+ onPresetApplied?: (preset: MorphicPresetDefinition) => void;
366
+ toolbox?: MorphicToolboxConfig;
367
+ toolboxLayout?: MorphicToolboxLayout;
368
+ /**
369
+ * When true, Blockly is injected without a built-in toolbox.
370
+ * Use this when calling `mountToolbox()` to avoid Blockly toolbox type conflicts.
371
+ */
372
+ canvasToolbox?: boolean;
373
+ workspaceMode?: MorphicModeName;
374
+ toolboxMode?: MorphicModeName;
375
+ /**
376
+ * Independent mode for the codespace. When set, the codespace renders the
377
+ * source element of this mode instead of following `workspaceMode`.
378
+ */
379
+ codespaceMode?: MorphicModeName;
380
+ /**
381
+ * Mode for the preview editor. The preview renders the source element of
382
+ * this mode. When unset, the preview falls back to the active workspace
383
+ * mode's `preview` element (legacy behavior).
384
+ */
385
+ previewMode?: MorphicModeName;
386
+ ui?: {
387
+ workspaceClassName?: string | string[];
388
+ toolboxClassName?: string | string[];
389
+ };
390
+ modeStyles?: MorphicModeStyle[];
391
+ /**
392
+ * Pass the result of `import.meta.glob('./modes/*.css', { eager: true, query: '?url' })`
393
+ * (or `{ eager: true, as: 'url' }` for older Vite).
394
+ * The framework derives mode names from CSS filenames and loads the stylesheets automatically.
395
+ * Takes precedence over `modeStyles` for the same modes.
396
+ */
397
+ modesFolder?: Record<string, unknown>;
398
+ baseStyle?: MorphicStyleBundle;
399
+ blockly?: Blockly.BlocklyOptions;
400
+ blocklyOptions?: Blockly.BlocklyOptions;
401
+ javascript?: MorphicJavaScriptConfig;
402
+ /**
403
+ * Per-element highlight rules, keyed by element name. The codespace and
404
+ * preview modes' source elements are used to look up entries here for
405
+ * their editors. Optional — when absent, editors render plain text.
406
+ */
407
+ highlighting?: Record<string, MorphicHighlightDefinition>;
408
+ }
409
+ /**
410
+ * Resolved workspace template for a block in a given mode.
411
+ * The template comes from the block's "block" element (or first element as fallback).
412
+ * Used internally by block-view and view-resolver.
413
+ */
414
+ export interface MorphicResolvedView {
415
+ mode: MorphicModeName;
416
+ template: string;
417
+ /** Element name the template came from. Used to look up per-element config (e.g. `empty` defaults). */
418
+ elementName?: string;
419
+ inputSlots?: Record<string, MorphicInputSlotDefinition>;
420
+ }
421
+ /** Line range a single block occupies in the generated code (1-based, inclusive). */
422
+ export interface MorphicCodeBlockPosition {
423
+ startLine: number;
424
+ endLine: number;
425
+ /**
426
+ * Character-offset range the block's rendered text occupies in the
427
+ * generated code (0-based, half-open: `[startChar, endChar)`). Provides
428
+ * inline precision so value children sharing a line (e.g. `1 + 2`) can
429
+ * still be distinguished. Used by the codespace to resolve value-slot drops.
430
+ */
431
+ startChar?: number;
432
+ endChar?: number;
433
+ /**
434
+ * True when the block's whole rendered text is a single editable cell
435
+ * (atomic single-field block — `math_number`, `text`, `logic_boolean`, etc.).
436
+ * Used by the codespace's hover background so it can prefer the surrounding
437
+ * non-atomic wrapper (e.g. the whole `1 + 2` expression) instead of
438
+ * highlighting just the atomic value the cursor lands on.
439
+ */
440
+ atomic?: boolean;
441
+ /**
442
+ * Body line range of each statement input declared on this block, keyed by
443
+ * the input name. Includes empty bodies — the start/end line points to the
444
+ * indented body line where children would render. Used by the codespace to
445
+ * resolve drops into empty `for`/`if` bodies.
446
+ */
447
+ statementSlots?: Record<string, {
448
+ startLine: number;
449
+ endLine: number;
450
+ }>;
451
+ }
452
+ /** Maps Blockly block IDs to their positions in the generated code. */
453
+ export type MorphicCodeMetadata = Map<string, MorphicCodeBlockPosition>;
454
+ /**
455
+ * Edit target for a placeholder range, when its content is an atomic
456
+ * single-field block (shadow, placeholder, or user-attached value block with
457
+ * exactly one field and no nested children). Empty-fallback ranges and
458
+ * multi-field blocks have no `edit` and are not inline-editable.
459
+ */
460
+ export interface MorphicPlaceholderEditTarget {
461
+ /** Blockly block id whose field produced the rendered text. */
462
+ blockId: string;
463
+ /** Field name on that block. */
464
+ fieldName: string;
465
+ /** Input UI form to use for editing. */
466
+ fieldType: "text" | "number" | "dropdown";
467
+ /** Dropdown options as `[label, value]` pairs (only when `fieldType === "dropdown"`). */
468
+ options?: [string, string][];
469
+ }
470
+ /**
471
+ * Range in the generated code occupied by a value slot. The codespace overlays
472
+ * an always-on underline on every value position; `kind: "default"` adds dim
473
+ * italic styling for shadow targets and empty fallbacks (framework-supplied
474
+ * defaults), while `kind: "set"` marks user-attached or placeholder content.
475
+ */
476
+ export interface MorphicPlaceholderRange {
477
+ /** Inclusive 0-based character offset in `code`. */
478
+ start: number;
479
+ /** Exclusive 0-based character offset in `code`. */
480
+ end: number;
481
+ kind: "default" | "set";
482
+ /** Editing target when the slot contains an atomic single-field block. */
483
+ edit?: MorphicPlaceholderEditTarget;
484
+ /**
485
+ * Set when the range is a *truly empty* value slot (rendered as a `[TYPE]`
486
+ * marker, with no block in it). Identifies the parent block and input so the
487
+ * codespace can resolve a drop into the empty slot — there's no child block
488
+ * to walk up from, unlike an occupied or shadow-filled slot.
489
+ */
490
+ emptySlot?: {
491
+ parentBlockId: string;
492
+ inputName: string;
493
+ };
494
+ }
495
+ /** Result of `generateJavaScriptWithMetadata()`. */
496
+ export interface MorphicCodeGenerationResult {
497
+ code: string;
498
+ metadata: MorphicCodeMetadata;
499
+ /** Value-slot ranges with default/set classification. Empty if no value slots emitted. */
500
+ placeholders: MorphicPlaceholderRange[];
501
+ }
502
+ /** Theme configuration for the code editor. */
503
+ export interface MorphicCodeEditorTheme {
504
+ /** Editor text size (e.g. "14px"). */
505
+ fontSize?: string;
506
+ /** Editor font family (e.g. "monospace"). */
507
+ fontFamily?: string;
508
+ /** Line spacing multiplier (e.g. 1.5). */
509
+ lineHeight?: number;
510
+ /** Editor background colour. */
511
+ background?: string;
512
+ /** Default text colour. */
513
+ foreground?: string;
514
+ /** Line number column background colour. */
515
+ gutterBackground?: string;
516
+ /** Line number text colour. */
517
+ gutterForeground?: string;
518
+ /** Text selection highlight colour. */
519
+ selectionBackground?: string;
520
+ }
521
+ /** Options for `mountCodeEditor()`. */
522
+ export interface MorphicCodeEditorOptions {
523
+ /** Visual theme — the framework provides sensible defaults. */
524
+ theme?: MorphicCodeEditorTheme;
525
+ /** Raw CodeMirror extensions for power users. Appended after the built-in ones. */
526
+ extensions?: unknown[];
527
+ /**
528
+ * Called when the user requests to delete the block at a given 1-based line
529
+ * (via Delete/Backspace on an empty selection, or a click on the gutter ✕).
530
+ * When set, the editor installs a keymap and a delete gutter.
531
+ */
532
+ onDelete?: (line: number) => void;
533
+ /**
534
+ * If provided, a "grip" gutter (⋮⋮) appears on the start line of every block
535
+ * id for which this returns `true`. Mousedown on the grip starts an HTML5
536
+ * drag whose data transfer includes `morphic/block-id` set to the block id —
537
+ * the host can then handle the drop (e.g. reorder).
538
+ */
539
+ canDragBlock?: (blockId: string) => boolean;
540
+ /**
541
+ * Token-level syntax highlighting rules. When set, the editor installs a
542
+ * CodeMirror `ViewPlugin` that emits `Decoration.mark` ranges for keywords,
543
+ * strings, numbers, and line comments per these rules. Swappable at runtime
544
+ * via `setHighlightRules`.
545
+ */
546
+ highlightRules?: MorphicHighlightDefinition;
547
+ /**
548
+ * Called when the user commits an inline placeholder edit. The host should
549
+ * write `newValue` to `edit.fieldName` on the Blockly block identified by
550
+ * `edit.blockId`. Re-codegen + re-render then refresh the codespace.
551
+ */
552
+ onPlaceholderApply?: (edit: MorphicPlaceholderEditTarget, newValue: string) => void;
553
+ /**
554
+ * Whether value-slot underline markers are shown in this editor. The codespace
555
+ * uses them as a form-field affordance for inline editing; read-only display
556
+ * surfaces (e.g. the preview editor) should disable them. Default: `true`.
557
+ */
558
+ showPlaceholderMarkers?: boolean;
559
+ }
560
+ /** Options for `enableSelectionSync()`. */
561
+ export interface MorphicSelectionSyncOptions {
562
+ /** CSS background colour for highlighted code lines. Defaults to a semi-transparent blue. */
563
+ highlightColor?: string;
564
+ /** Enable block → code direction. Defaults to true. */
565
+ blockToCode?: boolean;
566
+ /** Enable code → block direction. Defaults to true. */
567
+ codeToBlock?: boolean;
568
+ }
569
+ /** Surface a toolbar binds to. Drives stateful items (undo enabled-state,
570
+ * language label source, what "clear" affects). */
571
+ export type MorphicToolbarPane = "workspace" | "codespace" | "preview";
572
+ /** How items render their built-in icon + label pair. */
573
+ export type MorphicToolbarDisplay = "icon" | "label" | "both";
574
+ /**
575
+ * Runtime context passed to every toolbar item callback. Items use this to
576
+ * read pane state and request a re-render.
577
+ */
578
+ export interface MorphicToolbarCtx {
579
+ engine: import("./MorphicBlocks").MorphicBlocks;
580
+ pane: MorphicToolbarPane;
581
+ /** Current rendered text for the bound pane. Empty for workspace pane unless
582
+ * the engine has a codespace/preview mounted to derive text from. */
583
+ getText: () => string;
584
+ /** Triggers the bound pane's re-render (codegen + redraw). */
585
+ refresh: () => void;
586
+ }
587
+ /** Output of an item's render — string is treated as text content. */
588
+ export type MorphicToolbarRender = HTMLElement | string;
589
+ /**
590
+ * One toolbar entry. Buttons supply `label` and/or `icon` plus `onClick`;
591
+ * custom widgets supply `render`. `visible` is evaluated on every refresh.
592
+ */
593
+ export interface MorphicToolbarItem {
594
+ /** Stable id; reflected as `data-toolbar-id` for CSS targeting. */
595
+ id: string;
596
+ /** Lays out left of the spacer or right of it. Defaults to "left". */
597
+ align?: "left" | "right";
598
+ /** Plain-text label used in `label` / `both` display modes. */
599
+ label?: string;
600
+ /** Inline SVG string used in `icon` / `both` display modes. */
601
+ icon?: string;
602
+ /** Native `title` attribute / tooltip. */
603
+ title?: string;
604
+ /** Button click handler. Omit for non-interactive items (badges, labels). */
605
+ onClick?: (ctx: MorphicToolbarCtx) => void;
606
+ /** Optional predicate; item is omitted when this returns false on refresh. */
607
+ visible?: (ctx: MorphicToolbarCtx) => boolean;
608
+ /** Disable predicate; rendered with `disabled` and reduced opacity. */
609
+ disabled?: (ctx: MorphicToolbarCtx) => boolean;
610
+ /** Escape hatch — fully custom DOM. When set, label/icon/onClick are ignored. */
611
+ render?: (ctx: MorphicToolbarCtx) => MorphicToolbarRender;
612
+ }
613
+ /** Configuration for `engine.mountToolbar(container, config)`. */
614
+ export interface MorphicToolbarConfig {
615
+ /** Which pane this toolbar reflects. */
616
+ pane: MorphicToolbarPane;
617
+ /** Items to render. When omitted, the framework uses
618
+ * `toolbarItems.defaultsFor(pane)`. To render no items, pass `[]`. */
619
+ items?: MorphicToolbarItem[];
620
+ /** Display mode for items that have both icon and label. Defaults to "icon". */
621
+ display?: MorphicToolbarDisplay;
622
+ }
@@ -0,0 +1,31 @@
1
+ import type { MorphicBehaviorMap, MorphicBlockDefinition, MorphicElementTypeEntry, MorphicHighlightDefinition, MorphicModeDefinition, MorphicPresetDefinition, MorphicToolboxCategory } from "./types";
2
+ /**
3
+ * Inputs for a definitions validation pass. Everything is optional except the
4
+ * definitions + elementTypes (available at construction); the cross-reference
5
+ * data (modes / highlighting / categories) arrives from the mount config.
6
+ */
7
+ export interface ValidateDefinitionsArgs {
8
+ definitions: ReadonlyMap<string, MorphicBlockDefinition>;
9
+ elementTypes: Record<string, MorphicElementTypeEntry>;
10
+ behaviors: MorphicBehaviorMap;
11
+ modes?: MorphicModeDefinition[];
12
+ presets?: MorphicPresetDefinition[];
13
+ highlighting?: Record<string, MorphicHighlightDefinition>;
14
+ categories?: MorphicToolboxCategory[];
15
+ }
16
+ export interface DefinitionValidationResult {
17
+ /** Structural problems that guarantee wrong output — the caller should throw. */
18
+ errors: string[];
19
+ /** Degraded / dead-config problems — the caller should warn. */
20
+ warnings: string[];
21
+ }
22
+ /**
23
+ * Static validation of a definitions file. Complements the constructor-time
24
+ * checks in `createDefinitionMap` (identifier / element / duplicate) with the
25
+ * cross-field checks that would otherwise fail silently at render time.
26
+ *
27
+ * Pure and side-effect free: it collects every problem into `errors` (throw)
28
+ * and `warnings` (console.warn) so the caller reports them all at once rather
29
+ * than failing on the first. A known-good file yields two empty arrays.
30
+ */
31
+ export declare function validateDefinitions(args: ValidateDefinitionsArgs): DefinitionValidationResult;
@@ -0,0 +1,17 @@
1
+ import type { MorphicBlockDefinition, MorphicElementTypeEntry, MorphicModeDefinition, MorphicModeName, MorphicResolvedView } from "./types";
2
+ /**
3
+ * Source element of a mode: the first element in `mode.elements` whose type
4
+ * is "code". This is the element a codespace or preview renders when the mode
5
+ * is assigned to it.
6
+ */
7
+ export declare function resolveModeSourceElement(mode: MorphicModeDefinition, elementTypes?: Record<string, MorphicElementTypeEntry>): string | undefined;
8
+ /**
9
+ * Resolves the workspace template for a block in a given mode.
10
+ *
11
+ * Resolution order:
12
+ * 1. First element in the mode's `elements` array whose type is "code"
13
+ * 2. First element in the block definition whose type is "code"
14
+ * 3. Element literally named "block" (backward-compat fallback)
15
+ * 4. First element in the block definition
16
+ */
17
+ export declare function resolveBlockView(definition: MorphicBlockDefinition, mode: MorphicModeName, elementTypes?: Record<string, MorphicElementTypeEntry>, modeDefs?: MorphicModeDefinition[]): MorphicResolvedView;