morphic-blocks 0.2.1 → 0.4.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,24 @@ 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
+ A bundler plugin copies them to `public/blockly-media/` when `dev` or `build`
32
+ starts:
33
+
34
+ ```ts
35
+ // vite.config.ts (also morphic-blocks/webpack, /rspack, /rollup, /esbuild)
36
+ import blocklyMedia from "morphic-blocks/vite";
37
+ export default { plugins: [blocklyMedia()] };
38
+ ```
39
+
40
+ With Parcel, Turbopack or no bundler, run `morphic-blocks copy-media
41
+ public/blockly-media` before `dev` and `build` instead. You can still load them
42
+ from Blockly's server; see
43
+ [Privacy & External Requests](https://docs.morphicblocks.com/guides/privacy/).
44
+
45
+ The text views (codespace, code editor) use CodeMirror. Install it only if
46
+ you use them:
32
47
 
33
48
  ```sh
34
49
  npm i @codemirror/state @codemirror/view @codemirror/lang-javascript
@@ -36,75 +51,100 @@ npm i @codemirror/state @codemirror/view @codemirror/lang-javascript
36
51
 
37
52
  ## Quick start
38
53
 
54
+ A block is defined once, with one element per representation:
55
+
56
+ ```jsonc
57
+ // definitions.json
58
+ {
59
+ "elementTypes": {
60
+ "title": "text",
61
+ "concept": "code",
62
+ "python": "code"
63
+ },
64
+ "modes": [
65
+ { "name": "concept-tiles", "elements": ["title", "concept"] },
66
+ { "name": "python-tiles", "elements": ["title", "python"] }
67
+ ],
68
+ "blocks": [
69
+ {
70
+ "identifier": "text_print",
71
+ "elements": {
72
+ "title": "Print",
73
+ "concept": "Output %1",
74
+ "python": "print(%1)"
75
+ },
76
+ "inputSlots": {
77
+ "1": { "kind": "value", "name": "TEXT" }
78
+ }
79
+ }
80
+ ]
81
+ }
82
+ ```
83
+
84
+ A behavior writes the JavaScript that runs, one function per block:
85
+
86
+ ```ts
87
+ // behaviors.ts
88
+ import type { MorphicBehaviorMap } from "morphic-blocks";
89
+
90
+ export const behaviors: MorphicBehaviorMap = {
91
+ text_print(proxy) {
92
+ return `console.log(${proxy.inputs.TEXT ?? "undefined"});\n`;
93
+ },
94
+ };
95
+ ```
96
+
97
+ One call sets up every view it gets a container for:
98
+
39
99
  ```ts
100
+ // main.ts
40
101
  import { MorphicBlocks } from "morphic-blocks";
41
102
  import definitions from "./definitions.json";
42
103
  import { behaviors } from "./behaviors";
43
104
 
44
- // Modes, presets and categories all come from the definitions file, passed as
45
- // imported; mount() validates it.
46
105
  const engine = new MorphicBlocks(definitions, behaviors);
47
106
 
48
- // One call sets up every view it gets a container for.
49
107
  engine.mount({
50
108
  workspaceContainer: document.getElementById("workspace")!,
51
109
  toolboxContainer: document.getElementById("toolbox")!,
52
- preset: "conceptual", // a preset from definitions.json; without presets the first mode is used
53
110
  });
54
111
 
55
- // switch representation at runtime; the same blocks re-render
56
- engine.applyPreset("python");
112
+ // Switch the representation at runtime; the same blocks re-render.
113
+ engine.show({ toolbox: "python-tiles", views: { workspace: "python" } });
57
114
  ```
58
115
 
59
- ## Serve Blockly's media yourself
60
-
61
- By default Blockly loads its images and sounds from Google's server
62
- (`blockly-demo.appspot.com`), so every visitor's browser contacts it. To keep
63
- all requests on your own site, copy Blockly's `media` folder into your static
64
- files before `dev` and `build`:
65
-
66
- ```js
67
- // scripts/copy-blockly-media.mjs
68
- import { cpSync } from "node:fs";
69
- import { createRequire } from "node:module";
70
- import { dirname, join } from "node:path";
71
-
72
- // Blockly comes with morphic-blocks, so look it up from there.
73
- const require = createRequire(import.meta.url);
74
- const blockly = dirname(require.resolve("blockly", { paths: [dirname(require.resolve("morphic-blocks"))] }));
75
- cpSync(join(blockly, "media"), "public/blockly-media", { recursive: true });
76
- ```
77
-
78
- Then point Blockly at the copy:
79
-
80
- ```ts
81
- engine.mount({
82
- workspaceContainer: document.getElementById("workspace")!,
83
- blockly: { media: "blockly-media/" },
84
- });
85
- ```
116
+ ## How it works
86
117
 
87
- This works with every package manager. `public/` is Vite's folder for static
88
- files; use your bundler's equivalent.
118
+ 1. **Definitions** name each block's elements: labels, images and code
119
+ templates.
120
+ 2. **Modes** choose which elements the toolbox tiles show; one CSS file per
121
+ mode styles them.
122
+ 3. **Views** (workspaces and codespaces, declared by name) each show a code
123
+ element, and presets switch the toolbox and the views together.
89
124
 
90
125
  ## Features
91
126
 
92
- - **One definition, many representations** — define a block once; render it as
93
- icons, blocks, or source text, switchable at runtime.
94
- - **Config-driven** — blocks in JSON, behaviors in TypeScript, one CSS file per
95
- mode. No per-representation duplication.
96
- - **Headless & embeddable** — bring your own UI; the framework stays unstyled.
97
- - **Built on Blockly** — the proven engine stays authoritative underneath.
98
- - **No external requests.** The framework never contacts another server, so
99
- your site decides every request its visitors make. Blockly's own media is
100
- the one exception, and you can [serve it yourself](#serve-blocklys-media-yourself).
127
+ - **One definition, many representations:** define a block once and show it
128
+ as icons, blocks or source text, switchable at runtime.
129
+ - **Blocks and text side by side:** editable and read-only text views of the
130
+ program, any number of views, and selection that follows across them.
131
+ - **Config driven:** blocks in JSON, behaviors in TypeScript, one CSS file per
132
+ mode, with no duplication per representation.
133
+ - **Headless and embeddable:** bring your own UI; the framework stays unstyled.
134
+ - **Accessible toolbox:** tiles work with a mouse, a finger, a pen or the
135
+ keyboard, with names for screen readers; categories have headings, collapse,
136
+ or show as tabs.
137
+ - **No external requests:** the framework never contacts another server,
138
+ Blockly's media included.
139
+ - **Themes:** ready-made code view colors in
140
+ [`@morphicblocks/themes`](https://www.npmjs.com/package/@morphicblocks/themes).
101
141
 
102
142
  ## Documentation
103
143
 
104
- - **Website** — <https://morphicblocks.com>
105
- - **Docs** — <https://docs.morphicblocks.com>
106
- - **Playground** — <https://playground.morphicblocks.com>
107
- - **Source** — <https://github.com/morphicblocks/morphic-blocks>
144
+ - **Website:** <https://morphicblocks.com>
145
+ - **Docs:** <https://docs.morphicblocks.com>
146
+ - **Playground:** <https://playground.morphicblocks.com>
147
+ - **Source:** <https://github.com/morphicblocks/morphic-blocks>
108
148
 
109
149
  ## License
110
150
 
@@ -21,14 +21,19 @@
21
21
  "type": "array",
22
22
  "items": { "$ref": "#/$defs/mode" }
23
23
  },
24
+ "views": {
25
+ "description": "The views by name; mount() sets up each one it gets a container for. The first workspace with a container holds the program.",
26
+ "type": "object",
27
+ "additionalProperties": { "$ref": "#/$defs/view" }
28
+ },
24
29
  "presets": {
25
30
  "type": "array",
26
31
  "items": { "$ref": "#/$defs/preset" }
27
32
  },
28
- "highlighting": {
29
- "description": "Token-level highlight rules, keyed by code-element name.",
33
+ "code": {
34
+ "description": "How each code element's language is written, keyed by code element name.",
30
35
  "type": "object",
31
- "additionalProperties": { "$ref": "#/$defs/highlight" }
36
+ "additionalProperties": { "$ref": "#/$defs/codeElement" }
32
37
  },
33
38
  "categories": {
34
39
  "type": "array",
@@ -42,7 +47,7 @@
42
47
  "additionalProperties": false,
43
48
  "$defs": {
44
49
  "elementType": {
45
- "enum": ["text", "code", "image"]
50
+ "enum": ["text", "code", "image", "custom"]
46
51
  },
47
52
  "elementTypeEntry": {
48
53
  "oneOf": [
@@ -52,15 +57,6 @@
52
57
  "required": ["type"],
53
58
  "properties": {
54
59
  "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
60
  "size": {
65
61
  "description": "Display size for image elements: a number, \"32\", or \"32x32\".",
66
62
  "type": ["number", "string"]
@@ -70,6 +66,55 @@
70
66
  }
71
67
  ]
72
68
  },
69
+ "codeElement": {
70
+ "type": "object",
71
+ "properties": {
72
+ "stringQuote": {
73
+ "description": "Delimiter wrapped around framework-supplied literals in String slots.",
74
+ "type": "string"
75
+ },
76
+ "empty": {
77
+ "description": "Per-check empty-slot defaults, keyed by the slot's check (e.g. Number, String, Boolean).",
78
+ "type": "object",
79
+ "additionalProperties": { "$ref": "#/$defs/emptyDefault" }
80
+ },
81
+ "emptyStatement": {
82
+ "description": "Written into an empty statement slot where an empty body is invalid, e.g. \"pass\" for Python.",
83
+ "type": "string"
84
+ },
85
+ "types": {
86
+ "description": "Names %1:type writes, keyed by the value's type (its output check, or the slot's check while empty), e.g. { \"Number\": \"int\", \"default\": \"var\" }.",
87
+ "type": "object",
88
+ "additionalProperties": { "type": "string" }
89
+ },
90
+ "highlighting": { "$ref": "#/$defs/highlight" },
91
+ "values": {
92
+ "description": "How printed values are written while this element is shown, e.g. Python's True, None and ['a', 'b'].",
93
+ "type": "object",
94
+ "properties": {
95
+ "true": { "type": "string" },
96
+ "false": { "type": "string" },
97
+ "null": { "type": "string" },
98
+ "undefined": { "type": "string" },
99
+ "NaN": { "type": "string" },
100
+ "Infinity": { "type": "string" },
101
+ "-Infinity": { "type": "string" },
102
+ "list": {
103
+ "type": "object",
104
+ "properties": {
105
+ "open": { "type": "string" },
106
+ "close": { "type": "string" },
107
+ "separator": { "type": "string" },
108
+ "quote": { "type": "string" }
109
+ },
110
+ "additionalProperties": false
111
+ }
112
+ },
113
+ "additionalProperties": false
114
+ }
115
+ },
116
+ "additionalProperties": false
117
+ },
73
118
  "emptyDefault": {
74
119
  "type": "object",
75
120
  "properties": {
@@ -90,21 +135,34 @@
90
135
  "elements": {
91
136
  "type": "array",
92
137
  "items": { "type": "string" }
138
+ },
139
+ "render": {
140
+ "description": "How the mode's code elements are drawn on toolbox tiles, by element name. Blocks unless \"text-based\".",
141
+ "type": "object",
142
+ "additionalProperties": { "enum": ["block-based", "text-based"] }
93
143
  }
94
144
  },
95
145
  "additionalProperties": false
96
146
  },
97
- "presetToolbox": {
147
+ "view": {
98
148
  "oneOf": [
99
- { "type": "string" },
149
+ { "enum": ["workspace", "codespace"] },
100
150
  {
101
151
  "type": "object",
102
- "required": ["mode"],
152
+ "required": ["kind"],
103
153
  "properties": {
104
- "mode": { "type": "string" },
105
- "render": {
154
+ "kind": { "enum": ["workspace", "codespace"] },
155
+ "editable": { "description": "Whether the program can be changed in the view. Default true.", "type": "boolean" },
156
+ "rtl": { "description": "Right to left (true) or left to right (false). Left out, a workspace follows blockly.rtl and a codespace the page.", "type": "boolean" },
157
+ "delete": {
158
+ "description": "How blocks are deleted in a codespace; each way is on unless set to false.",
106
159
  "type": "object",
107
- "additionalProperties": { "enum": ["block", "text"] }
160
+ "properties": {
161
+ "lineButtons": { "type": "boolean" },
162
+ "keys": { "type": "boolean" },
163
+ "toolbarButton": { "type": "boolean" }
164
+ },
165
+ "additionalProperties": false
108
166
  }
109
167
  },
110
168
  "additionalProperties": false
@@ -113,14 +171,16 @@
113
171
  },
114
172
  "preset": {
115
173
  "type": "object",
116
- "required": ["name", "toolbox"],
174
+ "required": ["name", "toolbox", "views"],
117
175
  "properties": {
118
176
  "name": { "type": "string" },
119
177
  "label": { "type": "string" },
120
- "toolbox": { "$ref": "#/$defs/presetToolbox" },
121
- "workspace": { "type": "string" },
122
- "codespace": { "type": "string" },
123
- "preview": { "type": "string" }
178
+ "toolbox": { "description": "The mode of the toolbox tiles.", "type": "string" },
179
+ "views": {
180
+ "description": "What each view the preset shows shows, by view name.",
181
+ "type": "object",
182
+ "additionalProperties": { "type": "string" }
183
+ }
124
184
  },
125
185
  "additionalProperties": false
126
186
  },
@@ -128,7 +188,16 @@
128
188
  "type": "object",
129
189
  "properties": {
130
190
  "keywords": { "type": "array", "items": { "type": "string" } },
131
- "strings": { "type": "array", "items": { "type": "string" } },
191
+ "strings": {
192
+ "description": "A mark that opens and closes, or an [open, close] pair.",
193
+ "type": "array",
194
+ "items": {
195
+ "oneOf": [
196
+ { "type": "string" },
197
+ { "type": "array", "items": { "type": "string" }, "minItems": 2, "maxItems": 2 }
198
+ ]
199
+ }
200
+ },
132
201
  "comment": { "type": "string" },
133
202
  "numbers": { "type": "boolean" },
134
203
  "colors": {
@@ -188,7 +257,24 @@
188
257
  "required": ["value"],
189
258
  "properties": {
190
259
  "value": { "type": "string" },
191
- "label": { "type": "string" },
260
+ "label": {
261
+ "description": "Text, or a picture (image file or color swatch) shown on the block instead of text (text views still write the value).",
262
+ "oneOf": [
263
+ { "type": "string" },
264
+ {
265
+ "type": "object",
266
+ "oneOf": [{ "required": ["src"] }, { "required": ["color"] }],
267
+ "properties": {
268
+ "src": { "type": "string" },
269
+ "color": { "type": "string", "description": "A CSS color drawn as a swatch, e.g. #e53935." },
270
+ "alt": { "type": "string", "description": "What screen readers say. Default: the value." },
271
+ "width": { "type": "number", "description": "Default 16." },
272
+ "height": { "type": "number", "description": "Default 16." }
273
+ },
274
+ "additionalProperties": false
275
+ }
276
+ ]
277
+ },
192
278
  "display": {
193
279
  "type": "object",
194
280
  "description": "Per-element display text (element name → shown text). Overrides label/value when that element is rendered; the value still drives execution and codegen.",
package/dist/cli.js ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { c as copyBlocklyMedia } from "./copy-media-CllRyMqQ.js";
3
+ import "node:fs";
4
+ import "node:module";
5
+ import "node:path";
6
+ const USAGE = `Usage: morphic-blocks copy-media <folder>
7
+
8
+ Copies Blockly's images, cursors and sounds into <folder>, so your app serves
9
+ them itself. Morphic Blocks loads them from "blockly-media/" next to the page
10
+ unless you set blockly.media, so copy them to the folder served there:
11
+
12
+ npx morphic-blocks copy-media public/blockly-media
13
+
14
+ Copies only when the folder is new or Blockly was updated, so it can run
15
+ before every dev or build.`;
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 { version, copied } = copyBlocklyMedia(folder);
24
+ console.log(copied ? `Copied Blockly ${version} media to ${folder}` : `Blockly ${version} media is already in ${folder}`);
25
+ }
@@ -0,0 +1,21 @@
1
+ import { readFileSync, existsSync, cpSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, resolve } from "node:path";
4
+ const MARKER = ".blockly-version";
5
+ function copyBlocklyMedia(folder) {
6
+ const require2 = createRequire(import.meta.url);
7
+ const blockly = dirname(require2.resolve("blockly"));
8
+ const version = JSON.parse(readFileSync(join(blockly, "package.json"), "utf8")).version;
9
+ const target = resolve(folder);
10
+ const marker = join(target, MARKER);
11
+ if (existsSync(marker) && readFileSync(marker, "utf8").trim() === version) {
12
+ return { version, copied: false };
13
+ }
14
+ cpSync(join(blockly, "media"), target, { recursive: true });
15
+ writeFileSync(marker, `${version}
16
+ `);
17
+ return { version, copied: true };
18
+ }
19
+ export {
20
+ copyBlocklyMedia as c
21
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Copy Blockly's media into `folder`, unless it holds this Blockly version's
3
+ * media already, so it can run before every dev or build.
4
+ */
5
+ export declare function copyBlocklyMedia(folder: string): {
6
+ version: string;
7
+ copied: boolean;
8
+ };
@@ -0,0 +1,3 @@
1
+ export type { BlocklyMediaOptions } from "./plugin";
2
+ declare const _default: (options?: import("./plugin").BlocklyMediaOptions | undefined) => import("unplugin").EsbuildPlugin;
3
+ export default _default;
@@ -0,0 +1,10 @@
1
+ import { b as blocklyMedia } from "./plugin-h3QH8ods.js";
2
+ import "unplugin";
3
+ import "./copy-media-CllRyMqQ.js";
4
+ import "node:fs";
5
+ import "node:module";
6
+ import "node:path";
7
+ const esbuild = blocklyMedia.esbuild;
8
+ export {
9
+ esbuild as default
10
+ };
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, MorphicViewDeclaration, MorphicViewKind, MorphicViewOptions, MorphicCodeBehavior, MorphicCodeBlockPosition, MorphicCodeEditorOptions, MorphicCodeEditorTheme, MorphicCodespaceDeleteOptions, MorphicCodeGenerationResult, MorphicCodeMetadata, MorphicConnectionSpec, MorphicDropdownImage, MorphicElementRenderContext, MorphicElementRenderer, MorphicDropdownOption, MorphicFieldDefinition, MorphicInputAlign, MorphicInputKind, MorphicInputSlotDefinition, MorphicModeName, MorphicMountConfig, MorphicPlaceholderEditTarget, MorphicPlaceholderRange, MorphicRenderContext, MorphicResolvedView, MorphicStyleBundle, MorphicToolbarConfig, MorphicToolbarCtx, MorphicToolbarDisplay, MorphicToolbarItem, MorphicToolbarRender, MorphicToolboxCanvasOptions, MorphicToolboxCategory, MorphicToolboxConfig, MorphicToolboxLayout, MorphicToolboxModeLabel, MorphicBlockElements, MorphicModeDefinition, MorphicTileRender, MorphicPresetDefinition, MorphicRunOutputLine, MorphicRunResult, MorphicSelectionSyncOptions, } from "./morphic/types";