morphic-blocks 0.4.0 → 0.5.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.
@@ -22,8 +22,39 @@ export interface MorphicFieldToken {
22
22
  kind: "field";
23
23
  name: string;
24
24
  }
25
- export type MorphicTemplateToken = MorphicImageToken | MorphicTextToken | MorphicPlaceholderToken | MorphicValueTypeToken | MorphicFieldToken;
25
+ /** `%parent.NAME`: the `NAME` field of the nearest block around this one that has it. */
26
+ export interface MorphicParentFieldToken {
27
+ kind: "parentField";
28
+ name: string;
29
+ }
30
+ export type MorphicTemplateToken = MorphicImageToken | MorphicTextToken | MorphicPlaceholderToken | MorphicValueTypeToken | MorphicFieldToken | MorphicParentFieldToken;
26
31
  export declare function parseTemplate(template: string): MorphicTemplateToken[];
32
+ /**
33
+ * Whether the text on each side of a slot leaves the value in it alone. A
34
+ * slot between brackets or commas stands free (`len(%1)`, `max(%1, %2)`), and
35
+ * so does the slot of a statement after its keyword or sign (`return %1`,
36
+ * `if %1:`, `x = %1`). An operator or a word in front of it (`not %1`, `-%1`)
37
+ * or something that goes on from it (`%1.length`) binds to the value.
38
+ */
39
+ export declare function slotSides(tokens: MorphicTemplateToken[], index: number, statement: boolean): {
40
+ before: boolean;
41
+ after: boolean;
42
+ };
43
+ /** Whether the text around a slot binds to the value in it, so a value built from others needs brackets there. */
44
+ export declare function slotIsExposed(tokens: MorphicTemplateToken[], index: number, statement: boolean): boolean;
45
+ /** The mark a field stands between where a template writes it as a text (`"%TEXT"`), else `null`. */
46
+ export declare function quoteAround(before: string | undefined, after: string | undefined): string | null;
47
+ /** A text as it is written between two marks: the mark and the backslash each get a backslash in front. */
48
+ export declare function escapeQuoted(text: string, mark: string): string;
49
+ /**
50
+ * Read a text written between two marks from `pos` on: where the closing
51
+ * mark is, and the text without its backslashes. `null` when the line ends
52
+ * before the mark comes.
53
+ */
54
+ export declare function readQuoted(source: string, pos: number, mark: string): {
55
+ value: string;
56
+ end: number;
57
+ } | null;
27
58
  export declare function normalizeTemplateText(text: string): string;
28
59
  /**
29
60
  * A name as a CSS class part. The name is kept as written (`icon-tiles`,
@@ -0,0 +1,34 @@
1
+ import type * as Blockly from "blockly";
2
+ import type { MorphicBlockDefinition, MorphicCodeElementConfig } from "./types";
3
+ /**
4
+ * Text to blocks: read the text of a code element back into the blocks that
5
+ * write it. There is no parser per language. Each block's template is its
6
+ * pattern, read the way it is written: `print(%1)` is the text `print(`, a
7
+ * value, and `)`. Statements are read line by line, a body by its
8
+ * indentation, a value down to the blocks without slots.
9
+ *
10
+ * This first version reads valid text only. Where two blocks write the same
11
+ * text (`x = 1` creates a variable or sets one), the names declared so far
12
+ * decide: a reference prefers a name that exists, a declaration one that does
13
+ * not. Operators are read in the order the language gives their signs (see
14
+ * operators.ts), and brackets group whatever is in them; a sign without a
15
+ * rank needs brackets around its parts.
16
+ */
17
+ type BlockState = Blockly.serialization.blocks.State;
18
+ /** What reading a text gives: the program's stacks, or the line that fits no block. */
19
+ export type MorphicTextParseResult = {
20
+ ok: true;
21
+ stacks: BlockState[];
22
+ blocks: number;
23
+ } | {
24
+ ok: false;
25
+ line: number;
26
+ message: string;
27
+ };
28
+ /**
29
+ * Read `source`, written in the code element `element`, into blocks.
30
+ * `settings` are the element's `code` settings: its keywords are no names,
31
+ * its comment sign and empty statement are read as it writes them.
32
+ */
33
+ export declare function parseTextToBlocks(source: string, element: string, definitions: ReadonlyMap<string, MorphicBlockDefinition>, settings?: MorphicCodeElementConfig): MorphicTextParseResult;
34
+ export {};
@@ -21,7 +21,7 @@ export declare class MorphicToolboxCanvas {
21
21
  private readonly blockColors;
22
22
  private readonly behaviors;
23
23
  private readonly elementTypes;
24
- private readonly options;
24
+ private options;
25
25
  private readonly modes;
26
26
  private currentMode;
27
27
  private readonly code;
@@ -40,6 +40,8 @@ export declare class MorphicToolboxCanvas {
40
40
  private categoryParts;
41
41
  /** The category shown with the `"tabs"` layout; the first one until chosen. */
42
42
  private activeCategory?;
43
+ /** Tiles under their categories, or one list; presets switch it. */
44
+ private grouped;
43
45
  private readonly onScroll;
44
46
  private readonly resizeObserver;
45
47
  /** Adds a tile's block when the tile is chosen with the keyboard. */
@@ -57,11 +59,17 @@ export declare class MorphicToolboxCanvas {
57
59
  /** Code element settings; their highlighting colours code shown as text. */
58
60
  code?: Record<string, MorphicCodeElementConfig>;
59
61
  options?: MorphicToolboxCanvasOptions;
62
+ /** Whether tiles are grouped under the categories. Default `true`. */
63
+ grouped?: boolean;
60
64
  /** Called once with the hidden workspace used to draw block previews. */
61
65
  onPreviewWorkspace?: (workspace: Blockly.WorkspaceSvg) => void;
62
66
  dropTargets?: () => TileDropTarget[];
63
67
  onChoose?: (blockType: string) => void;
64
68
  });
69
+ /** Group the tiles under the categories (`true`) or show one list, from the next render on. */
70
+ setGrouped(grouped: boolean): void;
71
+ /** Show only these blocks (all when `undefined`) from the next render on. */
72
+ setBlocks(blocks: string[] | undefined): void;
65
73
  rerender(mode: MorphicModeName): void;
66
74
  dispose(): void;
67
75
  /**
@@ -113,6 +113,16 @@ export interface MorphicCodeElementConfig {
113
113
  * `default` is used when no key fits; without it nothing is written.
114
114
  */
115
115
  types?: Record<string, string>;
116
+ /**
117
+ * The order of this language's operators, by the sign as it is written:
118
+ * `{ "**": { "rank": 80, "direction": "right" }, "//": 60 }`. Text views
119
+ * write brackets only where the order needs them, and `loadText()` reads
120
+ * `2 + 3 * 4` as the language means it. The common signs have an order
121
+ * without this setting (see the docs); an entry here changes one sign,
122
+ * `null` takes a sign's order away, and `false` turns the order off, so
123
+ * every value built from others is written in brackets.
124
+ */
125
+ operators?: false | Record<string, MorphicOperatorOrder | null>;
116
126
  /** Token highlighting for the codespace and preview showing this element. */
117
127
  highlighting?: MorphicHighlightDefinition;
118
128
  /**
@@ -121,6 +131,21 @@ export interface MorphicCodeElementConfig {
121
131
  */
122
132
  values?: MorphicValueFormat;
123
133
  }
134
+ /**
135
+ * Where an operator stands among the others: a rank (the higher, the tighter
136
+ * it binds), or the rank with more about it. `direction` says how the same
137
+ * rank reads without brackets: from the `"left"` (`10 - 4 - 3`, the default),
138
+ * from the `"right"` (`2 ** 3 ** 2`), or not at all (`"none"`: `1 < x < 5`
139
+ * needs brackets). `"any"` is for a sign whose grouping does not matter
140
+ * (`out << a << b`): no brackets are written between two of it, and text
141
+ * reads from the left. `prefix` is the rank of the sign in front of one
142
+ * value (`-x`, `not x`).
143
+ */
144
+ export type MorphicOperatorOrder = number | {
145
+ rank?: number;
146
+ direction?: "left" | "right" | "none" | "any";
147
+ prefix?: number;
148
+ };
124
149
  /**
125
150
  * Printed values in a language's own spelling, e.g. Python:
126
151
  * `{ "true": "True", "false": "False", "null": "None", "list": { "quote": "'" } }`.
@@ -204,9 +229,9 @@ export type MorphicDropdownImage = ({
204
229
  };
205
230
  /**
206
231
  * A field declared directly on a block (rendered at the `%FIELDNAME` token
207
- * position). Lets dropdown / text / number / checkbox fields live in the
208
- * definitions file instead of requiring a behavior's `onViewApplied`. Fields
209
- * outside these four (variables, colour, plugin/custom) still use
232
+ * position). Lets dropdown / reference / text / number / checkbox fields live
233
+ * in the definitions file instead of requiring a behavior's `onViewApplied`.
234
+ * Fields outside these (Blockly's variables, colour, plugin/custom) still use
210
235
  * `onViewApplied` — the `%FIELDNAME` token is skipped when no declaration
211
236
  * exists, leaving the behavior to supply the field.
212
237
  */
@@ -214,6 +239,22 @@ export type MorphicFieldDefinition = {
214
239
  type: "dropdown";
215
240
  options: MorphicDropdownOption[];
216
241
  default?: string;
242
+ }
243
+ /**
244
+ * A dropdown of the names the program declares: `to` names a block and one
245
+ * of its fields (`"class_define.NAME"`, or a list of them), and the field
246
+ * lists what that field holds on every such block. Renaming a declaration
247
+ * renames the references to it. `default` is the name a new block starts
248
+ * with; in a program that declares other names it takes the first of them.
249
+ * `scope` names a block (or several): the field then lists only what is
250
+ * declared inside the nearest such block around it, e.g. the fields of the
251
+ * class a method is in.
252
+ */
253
+ | {
254
+ type: "reference";
255
+ to: string | string[];
256
+ default?: string;
257
+ scope?: string | string[];
217
258
  } | {
218
259
  type: "text";
219
260
  default?: string;
@@ -227,10 +268,33 @@ export type MorphicFieldDefinition = {
227
268
  type: "checkbox";
228
269
  default?: boolean;
229
270
  };
271
+ /** How a repeating slot behaves. */
272
+ export interface MorphicRepeatConfig {
273
+ /**
274
+ * What is written between two entries: one text for every element, or a
275
+ * text per element name (`{ "python": ", ", "concept": " and " }`). `, ` by default.
276
+ */
277
+ separator?: string | Record<string, string>;
278
+ /** How many entries a new block starts with (1 by default). */
279
+ count?: number;
280
+ }
230
281
  export interface MorphicInputSlotDefinition {
231
282
  kind?: MorphicInputKind;
232
283
  name?: string;
233
284
  check?: string | string[];
285
+ /**
286
+ * Take only blocks whose check matches `check`. Without it, a block that has
287
+ * no check fits every slot (Blockly's rule); with it, such a block is
288
+ * refused, here and below the blocks already in the slot. Needs a `check`.
289
+ */
290
+ strict?: boolean;
291
+ /**
292
+ * Let the slot hold any number of values, e.g. the parameters of a function
293
+ * or the items of a list. The template names the slot once (`def f(%1):`);
294
+ * the entries are written one after the other with `separator` between
295
+ * them. Value slots only.
296
+ */
297
+ repeat?: MorphicRepeatConfig;
234
298
  align?: MorphicInputAlign;
235
299
  label?: string;
236
300
  /**
@@ -268,7 +332,27 @@ export interface MorphicPresetDefinition {
268
332
  * out keep what they show.
269
333
  */
270
334
  views: Record<string, string>;
335
+ /**
336
+ * The block set whose blocks the toolbox shows. Without it, the toolbox
337
+ * shows all of its blocks.
338
+ */
339
+ blockSet?: string;
340
+ /**
341
+ * Whether the toolbox groups its tiles under the categories. Default `true`;
342
+ * `false` shows them as one list, e.g. for a level with few blocks. Blocks
343
+ * keep their category colors either way.
344
+ */
345
+ categories?: boolean;
271
346
  }
347
+ /**
348
+ * Blocks for the toolbox, by name in `blockSets`: a list of block
349
+ * identifiers, or another set with blocks added at the end and removed.
350
+ */
351
+ export type MorphicBlockSet = string[] | {
352
+ extends: string;
353
+ add?: string[];
354
+ remove?: string[];
355
+ };
272
356
  /** Kinds of view: blocks, or the program as text. */
273
357
  export type MorphicViewKind = "workspace" | "codespace";
274
358
  /** A view in the definitions' `views`, by name. A bare kind is the short form. */
@@ -336,6 +420,13 @@ export interface MorphicBlockDefinition {
336
420
  shape?: MorphicBlockShape;
337
421
  previousStatement?: MorphicConnectionSpec;
338
422
  nextStatement?: MorphicConnectionSpec;
423
+ /**
424
+ * Let the block go only where the place above it (a slot, or the block it
425
+ * hangs below) has a check matching its own `previousStatement` or `output`
426
+ * check. Without it, a block with a check still fits every place that has
427
+ * none, so a class field could be dropped into ordinary code. Needs a check.
428
+ */
429
+ strict?: boolean;
339
430
  inputsInline?: boolean;
340
431
  tooltip?: string;
341
432
  helpUrl?: string;
@@ -411,6 +502,8 @@ export interface MorphicBlocksFormat {
411
502
  views?: Record<string, MorphicViewKind | MorphicViewDeclaration>;
412
503
  /** Named per-view mode configurations. Used as the mount default for `presets`. */
413
504
  presets?: MorphicPresetDefinition[];
505
+ /** Named lists of blocks for the toolbox, used by presets and `show({ blockSet })`. */
506
+ blockSets?: Record<string, MorphicBlockSet>;
414
507
  /**
415
508
  * How each code element's language is written, keyed by element name:
416
509
  * string quotes, empty slot defaults and highlighting.
@@ -468,6 +561,12 @@ export interface MorphicBehaviorProxy {
468
561
  * Use these where the value is emitted as a string (e.g. a text block).
469
562
  */
470
563
  quoted: Record<string, string>;
564
+ /**
565
+ * The generated code of each filled entry of a repeating slot, keyed by the
566
+ * slot's name: `proxy.lists.PARAMS` is `["a", "b"]`. `proxy.inputs.PARAMS`
567
+ * holds the same entries joined with `, `.
568
+ */
569
+ lists: Record<string, string[]>;
471
570
  }
472
571
  export type MorphicCodeBehavior = (proxy: MorphicBehaviorProxy) => string;
473
572
  export interface MorphicBlockBehavior {
@@ -500,7 +599,10 @@ export interface MorphicToolboxDisplayOptions {
500
599
  layout?: "stacked" | "tabs";
501
600
  /** A heading with the category's name above its tiles. Default `true`. */
502
601
  categoryHeadings?: boolean;
503
- /** A click on a heading collapses or expands its category. Default `true`. */
602
+ /**
603
+ * A click on a heading collapses or expands its category. Default `true`.
604
+ * Without headings, categories stay open.
605
+ */
504
606
  collapsible?: boolean;
505
607
  /**
506
608
  * Categories collapsed at the start: `true` for all, or their names.
@@ -646,6 +748,13 @@ export interface MorphicMountConfig {
646
748
  * them in the app's own development mode.
647
749
  */
648
750
  onWarning?: (message: string) => void;
751
+ /**
752
+ * Where an image the definitions name is loaded from: a template's `<img>`,
753
+ * an image element's path, a dropdown picture. Return its address, or
754
+ * `undefined` to keep the path (next to the page), e.g. to show images an
755
+ * app keeps in memory: `assetUrl: (path) => blobUrls[path]`.
756
+ */
757
+ assetUrl?: (path: string) => string | undefined;
649
758
  toolbox?: MorphicToolboxConfig;
650
759
  toolboxLayout?: MorphicToolboxLayout;
651
760
  /**
@@ -761,6 +870,8 @@ export interface MorphicPlaceholderRange {
761
870
  /** Exclusive 0-based character offset in `code`. */
762
871
  end: number;
763
872
  kind: "default" | "set";
873
+ /** Set when the range is a reference whose name nothing declares; text views mark it. */
874
+ missing?: boolean;
764
875
  /** Editing target when the slot contains an atomic single-field block. */
765
876
  edit?: MorphicPlaceholderEditTarget;
766
877
  /**
@@ -774,12 +885,33 @@ export interface MorphicPlaceholderRange {
774
885
  inputName: string;
775
886
  };
776
887
  }
888
+ /** What `loadText()` returns: how many blocks the text became, or the line that fits no block. */
889
+ export type MorphicTextLoadResult = {
890
+ ok: true;
891
+ blocks: number;
892
+ } | {
893
+ ok: false;
894
+ line: number;
895
+ message: string;
896
+ };
897
+ /** Where the entries of a repeating slot end in generated text; text views put the slot's buttons there. */
898
+ export interface MorphicRepeatRange {
899
+ blockId: string;
900
+ /** The slot's name (the entries' inputs are `<name>_0`, `<name>_1`, …). */
901
+ slotName: string;
902
+ /** How many entries the slot has. */
903
+ count: number;
904
+ /** Character offset right after the last entry (or where the first would be). */
905
+ at: number;
906
+ }
777
907
  /** Result of `generateJavaScriptWithMetadata()`. */
778
908
  export interface MorphicCodeGenerationResult {
779
909
  code: string;
780
910
  metadata: MorphicCodeMetadata;
781
911
  /** Value-slot ranges with default/set classification. Empty if no value slots emitted. */
782
912
  placeholders: MorphicPlaceholderRange[];
913
+ /** Where each repeating slot's entries end in the text. Empty if the text has none. */
914
+ repeats?: MorphicRepeatRange[];
783
915
  /**
784
916
  * Line range (1-based, inclusive) of each group of connected blocks, a stack
785
917
  * in the workspace, in text order. Text views mark these lines with classes.
@@ -807,6 +939,13 @@ export interface MorphicCodeEditorTheme {
807
939
  gutterForeground?: string;
808
940
  /** Text selection highlight colour. */
809
941
  selectionBackground?: string;
942
+ /**
943
+ * A CodeMirror theme (an extension, e.g. `oneDark` from
944
+ * `@codemirror/theme-one-dark`) for the editor's colours. The colours above
945
+ * then default to the theme's; any set here still win. Token colours stay
946
+ * with `highlighting`.
947
+ */
948
+ codemirror?: unknown;
810
949
  }
811
950
  /** Ways to delete blocks in a codespace, each on unless set to `false`. */
812
951
  export interface MorphicCodespaceDeleteOptions {
@@ -901,6 +1040,13 @@ export interface MorphicCodeEditorOptions {
901
1040
  * `edit.blockId`. Re-codegen + re-render then refresh the codespace.
902
1041
  */
903
1042
  onPlaceholderApply?: (edit: MorphicPlaceholderEditTarget, newValue: string) => void;
1043
+ /**
1044
+ * Called when a plus or minus button of a repeating slot is pressed, with
1045
+ * the block, the slot's name and +1 or -1. When set, the editor shows the
1046
+ * buttons after each repeating slot's last entry, on the line the pointer
1047
+ * is over and on selected lines.
1048
+ */
1049
+ onRepeat?: (blockId: string, slotName: string, delta: number) => void;
904
1050
  /**
905
1051
  * Whether value-slot underline markers are shown in this editor. The codespace
906
1052
  * uses them as a form-field affordance for inline editing; read-only display
@@ -1,4 +1,4 @@
1
- import type { MorphicBehaviorMap, MorphicBlockDefinition, MorphicCodeElementConfig, MorphicElementTypeEntry, MorphicModeDefinition, MorphicPresetDefinition, MorphicToolboxCategory } from "./types";
1
+ import type { MorphicBehaviorMap, MorphicBlockSet, MorphicBlockDefinition, MorphicCodeElementConfig, MorphicElementTypeEntry, MorphicModeDefinition, MorphicPresetDefinition, MorphicToolboxCategory } from "./types";
2
2
  /**
3
3
  * Inputs for a definitions validation pass. Everything is optional except the
4
4
  * definitions + elementTypes (available at construction); the cross-reference
@@ -14,6 +14,7 @@ export interface ValidateDefinitionsArgs {
14
14
  categories?: MorphicToolboxCategory[];
15
15
  /** Names of the views the developer declared (not the defaults). */
16
16
  views?: string[];
17
+ blockSets?: Record<string, MorphicBlockSet>;
17
18
  }
18
19
  export interface DefinitionValidationResult {
19
20
  /** Structural problems that guarantee wrong output — the caller should throw. */