From 38440674929864897bb50cc42bb79a1540bdb7ab Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:04:20 -0400 Subject: [PATCH 01/10] feat: first version of plugin with requirements API --- package-lock.json | 17 +++ packages/plugins/lesson-authoring/README.md | 61 +++++++++ .../plugins/lesson-authoring/package.json | 53 ++++++++ .../lesson-authoring/src/artifact_types.ts | 26 ++++ .../plugins/lesson-authoring/src/index.ts | 11 ++ .../lesson-authoring/src/requirements.ts | 119 ++++++++++++++++++ .../plugins/lesson-authoring/test/index.html | 18 +++ .../plugins/lesson-authoring/test/index.ts | 39 ++++++ .../plugins/lesson-authoring/tsconfig.json | 16 +++ 9 files changed, 360 insertions(+) create mode 100644 packages/plugins/lesson-authoring/README.md create mode 100644 packages/plugins/lesson-authoring/package.json create mode 100644 packages/plugins/lesson-authoring/src/artifact_types.ts create mode 100644 packages/plugins/lesson-authoring/src/index.ts create mode 100644 packages/plugins/lesson-authoring/src/requirements.ts create mode 100644 packages/plugins/lesson-authoring/test/index.html create mode 100644 packages/plugins/lesson-authoring/test/index.ts create mode 100644 packages/plugins/lesson-authoring/tsconfig.json diff --git a/package-lock.json b/package-lock.json index 146f6654d4b..24d4fd24d23 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2118,6 +2118,10 @@ "resolved": "packages/plugins/cross-tab-copy-paste", "link": true }, + "node_modules/@blockly/plugin-lesson-authoring": { + "resolved": "packages/plugins/lesson-authoring", + "link": true + }, "node_modules/@blockly/plugin-modal": { "resolved": "packages/plugins/modal", "link": true @@ -32687,6 +32691,19 @@ "blockly": "^13.5.0" } }, + "packages/plugins/lesson-authoring": { + "name": "@blockly/plugin-lesson-authoring", + "version": "13.4.0", + "license": "Apache-2.0", + "devDependencies": { + "@blockly/dev-scripts": "^13.4.0", + "@blockly/dev-tools": "^13.4.0", + "typescript": "^6.0.3" + }, + "peerDependencies": { + "blockly": "^13.4.0" + } + }, "packages/plugins/migration": { "name": "@blockly/migrate", "version": "13.5.0", diff --git a/packages/plugins/lesson-authoring/README.md b/packages/plugins/lesson-authoring/README.md new file mode 100644 index 00000000000..aa43c5699a6 --- /dev/null +++ b/packages/plugins/lesson-authoring/README.md @@ -0,0 +1,61 @@ +# @blockly/plugin-lesson-authoring [![Built on Blockly](https://tinyurl.com/built-on-blockly)](https://github.com/RaspberryPiFoundation/blockly) + +Tools for authoring Blockly lessons + +> **Prototype.** This package is private and its API and artifact format will change +> without notice. Lesson files written by earlier versions may not load. + +## Installation + +### Yarn + +``` +yarn add @blockly/plugin-lesson-authoring +``` + +### npm + +``` +npm install @blockly/plugin-lesson-authoring --save +``` + +## Usage + +```js +import * as Blockly from 'blockly'; +import {findMissingRequirements} from '@blockly/plugin-lesson-authoring'; + +const artifact = JSON.parse(lessonJson); +const missing = findMissingRequirements(artifact, { + blockTypes: Object.keys(Blockly.Blocks), +}); +if (missing.blockTypes.length) { + throw new Error(`Missing blocks: ${missing.blockTypes.join(', ')}`); +} +``` + +## API + +### `LessonArtifact` + +A lesson as portable JSON, currently: + +- `title`: the lesson title. +- `toolbox`: a standard JSON toolbox definition (`ToolboxInfo`). +- `initialWorkspaceState`: the starter workspace, as saved by + `Blockly.serialization.workspaces.save`. + +### `getRequirements(artifact)` + +Returns the `LessonRequirements` an artifact depends on: currently `blockTypes`, +a sorted list of every block type used in the toolbox and initial workspace state. +Throws if the toolbox contains `blockxml` entries; only JSON block state is supported. + +### `findMissingRequirements(artifact, supported)` + +Returns the requirements of `artifact` that are not in `supported`. Hosts typically +pass `{blockTypes: Object.keys(Blockly.Blocks)}` (or a smaller subset of types). + +## License + +Apache 2.0 diff --git a/packages/plugins/lesson-authoring/package.json b/packages/plugins/lesson-authoring/package.json new file mode 100644 index 00000000000..a56212671aa --- /dev/null +++ b/packages/plugins/lesson-authoring/package.json @@ -0,0 +1,53 @@ +{ + "name": "@blockly/plugin-lesson-authoring", + "version": "13.4.0", + "description": "A set of tools for authoring Blockly lessons", + "scripts": { + "audit-fix": "blockly-scripts auditFix", + "build": "blockly-scripts build", + "clean": "blockly-scripts clean", + "lint": "eslint .", + "predeploy": "blockly-scripts predeploy", + "start": "blockly-scripts start", + "test": "blockly-scripts test" + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "unpkg": "./dist/index.js", + "private": true, + "author": "Blockly Team", + "keywords": [ + "blockly", + "blockly-plugin", + "lesson-authoring" + ], + "homepage": "https://github.com/mikeharv/blockly/tree/lesson-editor-prototype/packages/plugins/lesson-authoring#readme", + "bugs": { + "url": "https://github.com/mikeharv/blockly/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/mikeharv/blockly.git", + "directory": "packages/plugins/lesson-authoring" + }, + "license": "Apache-2.0", + "directories": { + "dist": "dist", + "src": "src" + }, + "files": [ + "dist", + "src" + ], + "devDependencies": { + "@blockly/dev-scripts": "^13.4.0", + "@blockly/dev-tools": "^13.4.0", + "typescript": "^6.0.3" + }, + "peerDependencies": { + "blockly": "^13.4.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/packages/plugins/lesson-authoring/src/artifact_types.ts b/packages/plugins/lesson-authoring/src/artifact_types.ts new file mode 100644 index 00000000000..4f5a58ff3f3 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/artifact_types.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +import type * as Blockly from 'blockly/core'; + +export type WorkspaceState = ReturnType< + typeof Blockly.serialization.workspaces.save +>; + +/** Names a lesson refers to that the host must provide. */ +export interface LessonRequirements { + blockTypes: string[]; + // Later, needed: + // dynamicCategories?: string[]; // toolbox `custom` values + // categoryStyles?: string[]; // `categorystyle` names + // buttonCallbacks?: string[]; // button `callbackKey`s +} + +export interface LessonArtifact { + title: string; + toolbox: Blockly.utils.toolbox.ToolboxInfo; + initialWorkspaceState: WorkspaceState; +} diff --git a/packages/plugins/lesson-authoring/src/index.ts b/packages/plugins/lesson-authoring/src/index.ts new file mode 100644 index 00000000000..10dff3c90c4 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/index.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview A set of tools for authoring Blockly lessons. + */ +export * from './artifact_types'; +export * from './requirements'; diff --git a/packages/plugins/lesson-authoring/src/requirements.ts b/packages/plugins/lesson-authoring/src/requirements.ts new file mode 100644 index 00000000000..7421adbecba --- /dev/null +++ b/packages/plugins/lesson-authoring/src/requirements.ts @@ -0,0 +1,119 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview Functions for determining the requirements of a lesson artifact. + */ + +import type {LessonArtifact, LessonRequirements} from './artifact_types'; + +import type * as Blockly from 'blockly/core'; + +/** + * Derives the requirements by walking the toolbox and every workspace state. + * + * @param artifact The lesson artifact to analyze. + * @returns The requirements (e.g. block types) of the artifact. + */ +export function getRequirements(artifact: LessonArtifact): LessonRequirements { + const {toolbox, initialWorkspaceState} = artifact; + const blockTypes = new Set(); + // Get block types from the toolbox or flyout. + if (toolbox) { + addBlockTypesFromCategoryInfo(toolbox, blockTypes); + } + // Get block types from the initial workspace state. + if (initialWorkspaceState) { + const blocks: Blockly.serialization.blocks.State[] = + initialWorkspaceState.blocks?.blocks ?? []; + blocks.forEach((block) => { + addBlockTypesFromBlockInfo(block, blockTypes); + }); + } + return { + blockTypes: Array.from(blockTypes).sort(), + }; +} + +function addBlockTypesFromCategoryInfo( + categoryInfo: Pick, + blockTypes: Set, +): void { + if (categoryInfo.contents) { + categoryInfo.contents.forEach((content) => { + const kind = content.kind.toLowerCase(); + if (kind === 'block') { + if ('blockxml' in content && content.blockxml) { + throw new Error( + 'blockxml is not supported in lesson authoring requirements', + ); + } + if ('type' in content && content.type) { + addBlockTypesFromBlockInfo(content, blockTypes); + } + } + // TODO: Dynamic categories aren't checked here because they don't get blocks + // until runtime. We will need to add their `custom` values to the requirements + // in order to validate that the host provides them. This will require a change + // to the LessonRequirements interface. + if (kind === 'category' && 'contents' in content && content.contents) { + addBlockTypesFromCategoryInfo(content, blockTypes); + } + }); + } +} + +function addBlockTypesFromBlockInfo( + blockInfo: Pick, + blockTypes: Set, +): void { + if (blockInfo.type) { + blockTypes.add(blockInfo.type); + } + // Walk nested inputs and next blocks. + if (blockInfo.inputs) { + const inputs = blockInfo.inputs; + Object.keys(inputs).forEach((key) => { + const input = inputs[key]; + if (input.block) { + addBlockTypesFromBlockInfo(input.block, blockTypes); + } + if (input.shadow) { + addBlockTypesFromBlockInfo(input.shadow, blockTypes); + } + }); + } + if (blockInfo.next) { + if (blockInfo.next.block) { + addBlockTypesFromBlockInfo(blockInfo.next.block, blockTypes); + } + if (blockInfo.next.shadow) { + addBlockTypesFromBlockInfo(blockInfo.next.shadow, blockTypes); + } + } +} + +/** + * Returns the requirements for an `artifact` that `supported` doesn't provide. + * `supported.blockTypes` can be derived from Blockly.Blocks or specified by the host. + * In the future, `supported` will potentially include dynamic category names, category + * style names and colours, and button callback keys. + * + * @param artifact The lesson artifact to analyze + * @param supported A list of supported block types (or other requirements in the future). + * @returns The requirements that are needed but not available. + */ +export function findMissingRequirements( + artifact: LessonArtifact, + supported: LessonRequirements, +): LessonRequirements { + const required = getRequirements(artifact); + const supportedBlockTypes = new Set(supported.blockTypes); + return { + blockTypes: required.blockTypes.filter( + (type) => !supportedBlockTypes.has(type), + ), + }; +} diff --git a/packages/plugins/lesson-authoring/test/index.html b/packages/plugins/lesson-authoring/test/index.html new file mode 100644 index 00000000000..602916314be --- /dev/null +++ b/packages/plugins/lesson-authoring/test/index.html @@ -0,0 +1,18 @@ + + + + + Blockly Lesson Authoring Plugin Test + + + + +
+ + + diff --git a/packages/plugins/lesson-authoring/test/index.ts b/packages/plugins/lesson-authoring/test/index.ts new file mode 100644 index 00000000000..458b9f48648 --- /dev/null +++ b/packages/plugins/lesson-authoring/test/index.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @fileoverview Plugin test. + */ + +import * as Blockly from 'blockly'; +import {toolboxCategories, createPlayground} from '@blockly/dev-tools'; + +/** + * Create a workspace. + * + * @param blocklyDiv The blockly container div. + * @param options The Blockly options. + * @returns The created workspace. + */ +function createWorkspace( + blocklyDiv: HTMLElement, + options: Blockly.BlocklyOptions, +): Blockly.WorkspaceSvg { + const workspace = Blockly.inject(blocklyDiv, options); + + return workspace; +} + +document.addEventListener('DOMContentLoaded', function () { + const defaultOptions = { + toolbox: toolboxCategories, + }; + const rootElement = document.getElementById('root'); + if (!rootElement) { + throw new Error(`div with id 'root' not found`); + } + createPlayground(rootElement, createWorkspace, defaultOptions); +}); diff --git a/packages/plugins/lesson-authoring/tsconfig.json b/packages/plugins/lesson-authoring/tsconfig.json new file mode 100644 index 00000000000..99858c525f1 --- /dev/null +++ b/packages/plugins/lesson-authoring/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "rootDir": "./src", + "outDir": "dist", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "module": "es2015", + "moduleResolution": "bundler", + "target": "es6", + "strict": true + }, + // NOTE: `test/**/*` is automatically included in `blockly-scripts start`. + // Only src matters for production builds. + "include": ["src"] +} From 467a54a9f37713bf3352962974d3318f2381ccfa Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:34:34 -0400 Subject: [PATCH 02/10] chore: add requirements tests to lesson-authoring plugin --- .../test/requirements.mocha.js | 255 ++++++++++++++++++ 1 file changed, 255 insertions(+) create mode 100644 packages/plugins/lesson-authoring/test/requirements.mocha.js diff --git a/packages/plugins/lesson-authoring/test/requirements.mocha.js b/packages/plugins/lesson-authoring/test/requirements.mocha.js new file mode 100644 index 00000000000..41c648b526e --- /dev/null +++ b/packages/plugins/lesson-authoring/test/requirements.mocha.js @@ -0,0 +1,255 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +import {assert} from 'chai'; +import {findMissingRequirements, getRequirements} from '../src/index'; + +const EMPTY_TOOLBOX = {kind: 'flyoutToolbox', contents: []}; + +/** + * Builds a lesson artifact from a toolbox and top-level block states. + * @param {object} options The artifact contents. + * @param {object=} options.toolbox The toolbox definition. + * @param {!Array=} options.blocks Top-level block states for the + * initial workspace. An empty list gives an empty workspace state. + * @returns {object} The lesson artifact. + */ +function makeArtifact({toolbox = EMPTY_TOOLBOX, blocks = []} = {}) { + return { + title: 'Test lesson', + toolbox, + initialWorkspaceState: blocks.length + ? {blocks: {languageVersion: 0, blocks}} + : {}, + }; +} + +suite('Lesson requirements', function () { + suite('getRequirements', function () { + suite('workspace state', function () { + test('top-level block', function () { + const artifact = makeArtifact({blocks: [{type: 'math_number'}]}); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['math_number'], + }); + }); + + test('blocks nested in inputs', function () { + const artifact = makeArtifact({ + blocks: [ + { + type: 'controls_if', + inputs: { + IF0: { + block: { + type: 'logic_compare', + inputs: {A: {block: {type: 'math_number'}}}, + }, + }, + }, + }, + ], + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['controls_if', 'logic_compare', 'math_number'], + }); + }); + + test('shadow blocks, including ones covered by a real block', function () { + const artifact = makeArtifact({ + blocks: [ + { + type: 'controls_repeat_ext', + inputs: { + TIMES: { + shadow: {type: 'math_number', fields: {NUM: 10}}, + block: {type: 'math_random_int'}, + }, + }, + }, + ], + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['controls_repeat_ext', 'math_number', 'math_random_int'], + }); + }); + + test('next chains', function () { + const artifact = makeArtifact({ + blocks: [ + { + type: 'variables_set', + next: { + block: { + type: 'text_print', + next: {block: {type: 'controls_flow_statements'}}, + }, + }, + }, + ], + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: [ + 'controls_flow_statements', + 'text_print', + 'variables_set', + ], + }); + }); + + test('multiple top-level blocks', function () { + const artifact = makeArtifact({ + blocks: [{type: 'text'}, {type: 'logic_boolean'}], + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['logic_boolean', 'text'], + }); + }); + + test('empty workspace', function () { + const artifact = makeArtifact({ + toolbox: { + kind: 'flyoutToolbox', + contents: [{kind: 'block', type: 'text'}], + }, + }); + assert.deepEqual(getRequirements(artifact), {blockTypes: ['text']}); + }); + }); + + suite('toolbox', function () { + test('flyout toolbox without categories', function () { + const artifact = makeArtifact({ + toolbox: { + kind: 'flyoutToolbox', + contents: [ + {kind: 'block', type: 'text'}, + {kind: 'sep'}, + {kind: 'label', text: 'Logic'}, + {kind: 'block', type: 'logic_boolean'}, + ], + }, + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['logic_boolean', 'text'], + }); + }); + + test('nested categories', function () { + const artifact = makeArtifact({ + toolbox: { + kind: 'categoryToolbox', + contents: [ + { + kind: 'category', + name: 'Outer', + contents: [ + {kind: 'block', type: 'text'}, + { + kind: 'category', + name: 'Inner', + contents: [{kind: 'block', type: 'math_number'}], + }, + ], + }, + ], + }, + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['math_number', 'text'], + }); + }); + + test('toolbox blocks with inputs and next', function () { + const artifact = makeArtifact({ + toolbox: { + kind: 'flyoutToolbox', + contents: [ + { + kind: 'block', + type: 'controls_repeat_ext', + inputs: {TIMES: {shadow: {type: 'math_number'}}}, + next: {block: {type: 'text_print'}}, + }, + ], + }, + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['controls_repeat_ext', 'math_number', 'text_print'], + }); + }); + + test('empty toolbox and empty workspace', function () { + assert.deepEqual(getRequirements(makeArtifact()), {blockTypes: []}); + }); + }); + + test('dedupes across toolbox and workspace', function () { + const artifact = makeArtifact({ + toolbox: { + kind: 'flyoutToolbox', + contents: [ + {kind: 'block', type: 'text'}, + {kind: 'block', type: 'math_number'}, + {kind: 'block', type: 'controls_if'}, + {kind: 'block', type: 'text'}, + ], + }, + blocks: [ + { + type: 'text_print', + inputs: {TEXT: {block: {type: 'text'}}}, + next: {block: {type: 'text_print'}}, + }, + ], + }); + assert.deepEqual(getRequirements(artifact), { + blockTypes: ['controls_if', 'math_number', 'text', 'text_print'], + }); + }); + }); + + suite('findMissingRequirements', function () { + const artifact = makeArtifact({ + toolbox: { + kind: 'flyoutToolbox', + contents: [ + {kind: 'block', type: 'math_number'}, + {kind: 'block', type: 'controls_if'}, + ], + }, + blocks: [{type: 'text_print', inputs: {TEXT: {block: {type: 'text'}}}}], + }); + + test('all supported', function () { + const supported = { + blockTypes: [ + 'controls_if', + 'math_number', + 'text', + 'text_print', + 'logic_boolean', + ], + }; + assert.deepEqual(findMissingRequirements(artifact, supported), { + blockTypes: [], + }); + }); + + test('some missing, sorted', function () { + const supported = {blockTypes: ['text', 'math_number']}; + assert.deepEqual(findMissingRequirements(artifact, supported), { + blockTypes: ['controls_if', 'text_print'], + }); + }); + + test('nothing supported', function () { + assert.deepEqual(findMissingRequirements(artifact, {blockTypes: []}), { + blockTypes: ['controls_if', 'math_number', 'text', 'text_print'], + }); + }); + }); +}); From 15697793f32d659668e9fb75b096cf626fd6b98f Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:48:31 -0400 Subject: [PATCH 03/10] feat: add context menu options for toggling block state --- .../lesson-authoring/src/block_state_menu.ts | 468 ++++++++++++++++++ .../plugins/lesson-authoring/src/index.ts | 1 + 2 files changed, 469 insertions(+) create mode 100644 packages/plugins/lesson-authoring/src/block_state_menu.ts diff --git a/packages/plugins/lesson-authoring/src/block_state_menu.ts b/packages/plugins/lesson-authoring/src/block_state_menu.ts new file mode 100644 index 00000000000..89be0b17ead --- /dev/null +++ b/packages/plugins/lesson-authoring/src/block_state_menu.ts @@ -0,0 +1,468 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview Context menu options for lesson authoring, including making blocks deletable, uneditable, and immovable. + */ + +import * as Blockly from 'blockly/core'; + +/** + * Returns all blocks in the workspace that are not shadows. + * + * @param workspace The workspace with blocks to filter. + * @returns An array of non-shadow blocks. + */ +function nonShadowBlocks(workspace: Blockly.Workspace) { + return workspace.getAllBlocks().filter((block) => !block.isShadow()); +} + +/** + * Option to make a block deletable. + */ +function registerDeletable() { + const deletableOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + throw new Error('No block in scope for context menu item'); + } + return block.isOwnDeletable() + ? 'Make block undeletable' + : 'Make block deletable'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (block && !block.isInFlyout) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + throw new Error('No block in scope for context menu item'); + } + block.setDeletable(!block.isOwnDeletable()); + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, + id: 'lessonBlockDeletable', + weight: 8, + }; + Blockly.ContextMenuRegistry.registry.register(deletableOption); +} + +/** + * Option to make all blocks deletable. + */ +function registerAllDeletable() { + const deletableAllOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + if ( + nonShadowBlocks(workspace).every((block) => !block.isOwnDeletable()) + ) { + return 'Make ALL blocks deletable'; + } + return 'Make ALL blocks undeletable'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + if (workspace.getTopBlocks(false).length > 0) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + const allBlocks = nonShadowBlocks(workspace); + if (allBlocks.every((block) => !block.isOwnDeletable())) { + allBlocks.forEach((block) => block.setDeletable(true)); + } else { + allBlocks + .filter((block) => block.isOwnDeletable()) + .forEach((block) => block.setDeletable(false)); + } + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE, + id: 'lessonAllBlocksDeletable', + weight: 8, + }; + Blockly.ContextMenuRegistry.registry.register(deletableAllOption); +} + +/** + * Option to make a block editable. + */ +function registerEditable() { + const editableOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + throw new Error('No block in scope for context menu item'); + } + return block.isOwnEditable() + ? 'Make block uneditable' + : 'Make block editable'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + return 'enabled'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + throw new Error('No block in scope for context menu item'); + } + const editable = !block.isOwnEditable(); + block.setEditable(editable); + block + .getChildren(false) + .filter((child) => child.isShadow()) + .forEach((shadow) => + shadow + .getDescendants(false) + .forEach((descendant) => descendant.setEditable(editable)), + ); + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, + id: 'lessonBlockEditable', + weight: 9, + }; + Blockly.ContextMenuRegistry.registry.register(editableOption); +} + +/** + * Option to make all blocks editable. + */ +function registerAllEditable() { + const editableAllOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + if (workspace.getAllBlocks().every((block) => !block.isOwnEditable())) { + return 'Make ALL blocks editable'; + } + return 'Make ALL blocks uneditable'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + if (workspace.getTopBlocks(false).length > 0) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + + const allBlocks = workspace.getAllBlocks(); + if (allBlocks.every((block) => !block.isOwnEditable())) { + allBlocks.forEach((block) => block.setEditable(true)); + } else { + allBlocks + .filter((block) => block.isOwnEditable()) + .forEach((block) => block.setEditable(false)); + } + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE, + id: 'lessonAllBlocksEditable', + weight: 9, + }; + Blockly.ContextMenuRegistry.registry.register(editableAllOption); +} + +/** + * Option to make a block movable. + */ +function registerMovable() { + const movableOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + throw new Error('No block in scope for context menu item'); + } + return block.isOwnMovable() + ? 'Make block immovable' + : 'Make block movable'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (block && !block.isInFlyout) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + throw new Error('No block in scope for context menu item'); + } + block.setMovable(!block.isOwnMovable()); + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, + id: 'lessonBlockMovable', + weight: 10, + }; + Blockly.ContextMenuRegistry.registry.register(movableOption); +} + +/** + * Option to make all blocks movable. + */ +function registerAllMovable() { + const movableAllOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + if (nonShadowBlocks(workspace).every((block) => !block.isOwnMovable())) { + return 'Make ALL blocks movable'; + } + return 'Make ALL blocks immovable'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + if (workspace.getTopBlocks(false).length > 0) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const workspace = scope.workspace; + if (!workspace) { + throw new Error('No workspace in scope for context menu item'); + } + + const allBlocks = nonShadowBlocks(workspace); + if (allBlocks.every((block) => !block.isOwnMovable())) { + allBlocks.forEach((block) => block.setMovable(true)); + } else { + allBlocks + .filter((block) => block.isOwnMovable()) + .forEach((block) => block.setMovable(false)); + } + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE, + id: 'lessonAllBlocksMovable', + weight: 10, + }; + Blockly.ContextMenuRegistry.registry.register(movableAllOption); +} + +/** + * Returns the connections a block's children attach to: one per input, plus + * the next connection. + * + * @param block The parent block. + * @returns The block's child connections. + */ +function childConnections(block: Blockly.Block): Blockly.Connection[] { + return [ + ...block.inputList.map((input) => input.connection), + block.nextConnection, + ].filter((connection) => !!connection); +} + +/** + * Returns the child connections of a block that have shadow state, whether + * the shadow is visible or covered by a real block. + * + * @param block The parent block. + * @returns The connections with shadow state. + */ +function shadowConnections(block: Blockly.Block) { + return childConnections(block).filter((connection) => + connection.getShadowState(true), + ); +} + +/** + * Returns the connection a block is attached to on its parent, if any. + * + * @param block The child block. + * @returns The parent's connection, or null if the block is top-level. + */ +function parentConnection(block: Blockly.Block) { + return ( + block.outputConnection?.targetConnection ?? + block.previousConnection?.targetConnection ?? + null + ); +} + +/** + * Option to turn a block into a shadow of the input it is attached to. + */ +function registerMakeShadow() { + const makeShadowOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText() { + return 'Make block a shadow'; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block || block.isInFlyout || !parentConnection(block)) { + return 'hidden'; + } + // Shadows cannot have real children, and variable fields cannot exist + // on shadows. Descendants are already shadows, so cannot have them. + const allDescendantsAreShadows = block + .getDescendants(false) + .slice(1) + .every((descendant) => descendant.isShadow()); + const hasVariableField = block.inputList.some((input) => + input.fieldRow.some((field) => field instanceof Blockly.FieldVariable), + ); + return allDescendantsAreShadows && !hasVariableField + ? 'enabled' + : 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + const connection = block && parentConnection(block); + if (!block || !connection) { + return; + } + // Without saveIds, the temporary shadow that setShadowState builds + // cannot collide with the IDs of the still-attached block. + const state = Blockly.serialization.blocks.save(block, { + addCoordinates: false, + saveIds: false, + }); + if (!state) { + return; + } + connection.setShadowState(state); + // Unplugging the block respawns the shadow in its place. + block.dispose(false); + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, + id: 'lessonMakeShadow', + weight: 11, + }; + Blockly.ContextMenuRegistry.registry.register(makeShadowOption); +} + +/** + * Option to turn a block's shadows into real blocks. Any real block covering a + * shadow is unplugged to make room, and the shadow state is removed. + */ +function registerMakeShadowsReal() { + const makeShadowsRealOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const count = scope.block ? shadowConnections(scope.block).length : 0; + return `Make ${count} shadow block${count === 1 ? '' : 's'} real`; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (block && !block.isInFlyout && shadowConnections(block).length) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + return; + } + for (const connection of shadowConnections(block)) { + const state = connection.getShadowState(true); + if (!state) { + continue; + } + // Clear the shadow first, so that unplugging a covering block does + // not respawn it. + connection.setShadowState(null); + const coveringBlock = connection.targetBlock(); + coveringBlock?.unplug(); + + const realBlock = Blockly.serialization.blocks.append( + state, + block.workspace, + {recordUndo: true}, + ); + const childConnection = + realBlock.outputConnection ?? realBlock.previousConnection; + if (childConnection) { + connection.connect(childConnection); + } + // Move the unplugged block so it isn't hidden behind the new one. + coveringBlock?.bumpNeighbours(); + } + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, + id: 'lessonMakeShadowsReal', + weight: 12, + }; + Blockly.ContextMenuRegistry.registry.register(makeShadowsRealOption); +} + +/** + * Option to remove the shadows from a block's inputs, whether they are visible + * or covered by a real block. + */ +function registerRemoveShadows() { + const removeShadowsOption: Blockly.ContextMenuRegistry.RegistryItem = { + displayText(scope: Blockly.ContextMenuRegistry.Scope) { + const count = scope.block ? shadowConnections(scope.block).length : 0; + return `Remove ${count} shadow block${count === 1 ? '' : 's'}`; + }, + preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (block && !block.isInFlyout && shadowConnections(block).length) { + return 'enabled'; + } + return 'hidden'; + }, + callback(scope: Blockly.ContextMenuRegistry.Scope) { + const block = scope.block; + if (!block) { + return; + } + // Disposes a visible shadow, or forgets a covered one. + shadowConnections(block).forEach((connection) => + connection.setShadowState(null), + ); + }, + scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, + id: 'lessonRemoveShadows', + weight: 13, + }; + Blockly.ContextMenuRegistry.registry.register(removeShadowsOption); +} + +/** + * Registers the lesson-authoring context menu options. + */ +export function registerLessonAuthoringContextMenuOptions() { + registerDeletable(); + registerAllDeletable(); + registerEditable(); + registerAllEditable(); + registerMovable(); + registerAllMovable(); + registerMakeShadow(); + registerMakeShadowsReal(); + registerRemoveShadows(); +} diff --git a/packages/plugins/lesson-authoring/src/index.ts b/packages/plugins/lesson-authoring/src/index.ts index 10dff3c90c4..59e7579f8f2 100644 --- a/packages/plugins/lesson-authoring/src/index.ts +++ b/packages/plugins/lesson-authoring/src/index.ts @@ -9,3 +9,4 @@ */ export * from './artifact_types'; export * from './requirements'; +export * from './block_state_menu'; From b5cace83f11788aec5a396cd8db14d42ceba2ac7 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:17:00 -0500 Subject: [PATCH 04/10] fix: Make shadow changes undo-able and only apply to value inputs --- .../lesson-authoring/src/block_state_menu.ts | 159 ++++++++++-------- .../src/shadow_state_change.ts | 152 +++++++++++++++++ 2 files changed, 238 insertions(+), 73 deletions(-) create mode 100644 packages/plugins/lesson-authoring/src/shadow_state_change.ts diff --git a/packages/plugins/lesson-authoring/src/block_state_menu.ts b/packages/plugins/lesson-authoring/src/block_state_menu.ts index 89be0b17ead..6ff6c96523f 100644 --- a/packages/plugins/lesson-authoring/src/block_state_menu.ts +++ b/packages/plugins/lesson-authoring/src/block_state_menu.ts @@ -8,6 +8,7 @@ */ import * as Blockly from 'blockly/core'; +import {setShadowState} from './shadow_state_change'; /** * Returns all blocks in the workspace that are not shadows. @@ -15,7 +16,7 @@ import * as Blockly from 'blockly/core'; * @param workspace The workspace with blocks to filter. * @returns An array of non-shadow blocks. */ -function nonShadowBlocks(workspace: Blockly.Workspace) { +function getNonShadowBlocks(workspace: Blockly.Workspace) { return workspace.getAllBlocks().filter((block) => !block.isShadow()); } @@ -65,7 +66,7 @@ function registerAllDeletable() { throw new Error('No workspace in scope for context menu item'); } if ( - nonShadowBlocks(workspace).every((block) => !block.isOwnDeletable()) + getNonShadowBlocks(workspace).every((block) => !block.isOwnDeletable()) ) { return 'Make ALL blocks deletable'; } @@ -86,7 +87,7 @@ function registerAllDeletable() { if (!workspace) { throw new Error('No workspace in scope for context menu item'); } - const allBlocks = nonShadowBlocks(workspace); + const allBlocks = getNonShadowBlocks(workspace); if (allBlocks.every((block) => !block.isOwnDeletable())) { allBlocks.forEach((block) => block.setDeletable(true)); } else { @@ -234,7 +235,9 @@ function registerAllMovable() { if (!workspace) { throw new Error('No workspace in scope for context menu item'); } - if (nonShadowBlocks(workspace).every((block) => !block.isOwnMovable())) { + if ( + getNonShadowBlocks(workspace).every((block) => !block.isOwnMovable()) + ) { return 'Make ALL blocks movable'; } return 'Make ALL blocks immovable'; @@ -255,7 +258,7 @@ function registerAllMovable() { throw new Error('No workspace in scope for context menu item'); } - const allBlocks = nonShadowBlocks(workspace); + const allBlocks = getNonShadowBlocks(workspace); if (allBlocks.every((block) => !block.isOwnMovable())) { allBlocks.forEach((block) => block.setMovable(true)); } else { @@ -272,44 +275,21 @@ function registerAllMovable() { } /** - * Returns the connections a block's children attach to: one per input, plus - * the next connection. - * - * @param block The parent block. - * @returns The block's child connections. - */ -function childConnections(block: Blockly.Block): Blockly.Connection[] { - return [ - ...block.inputList.map((input) => input.connection), - block.nextConnection, - ].filter((connection) => !!connection); -} - -/** - * Returns the child connections of a block that have shadow state, whether - * the shadow is visible or covered by a real block. + * Returns the value input connections of a block that have shadow state, + * whether the shadow is visible or covered by a real block. * * @param block The parent block. * @returns The connections with shadow state. */ -function shadowConnections(block: Blockly.Block) { - return childConnections(block).filter((connection) => - connection.getShadowState(true), - ); -} - -/** - * Returns the connection a block is attached to on its parent, if any. - * - * @param block The child block. - * @returns The parent's connection, or null if the block is top-level. - */ -function parentConnection(block: Blockly.Block) { - return ( - block.outputConnection?.targetConnection ?? - block.previousConnection?.targetConnection ?? - null - ); +function getShadowInputConnections(block: Blockly.Block) { + return block.inputList + .map((input) => input.connection) + .filter((connection) => !!connection) + .filter( + (connection) => + connection.type === Blockly.ConnectionType.INPUT_VALUE && + !!connection.getShadowState(true), + ); } /** @@ -322,7 +302,11 @@ function registerMakeShadow() { }, preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { const block = scope.block; - if (!block || block.isInFlyout || !parentConnection(block)) { + if ( + !block || + block.isInFlyout || + !block.outputConnection?.targetConnection + ) { return 'hidden'; } // Shadows cannot have real children, and variable fields cannot exist @@ -340,7 +324,7 @@ function registerMakeShadow() { }, callback(scope: Blockly.ContextMenuRegistry.Scope) { const block = scope.block; - const connection = block && parentConnection(block); + const connection = block?.outputConnection?.targetConnection; if (!block || !connection) { return; } @@ -353,9 +337,15 @@ function registerMakeShadow() { if (!state) { return; } - connection.setShadowState(state); - // Unplugging the block respawns the shadow in its place. - block.dispose(false); + const existingGroup = Blockly.Events.getGroup(); + if (!existingGroup) Blockly.Events.setGroup(true); + try { + setShadowState(connection, state); + // Unplugging the block respawns the shadow in its place. + block.dispose(false); + } finally { + Blockly.Events.setGroup(existingGroup); + } }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonMakeShadow', @@ -371,12 +361,18 @@ function registerMakeShadow() { function registerMakeShadowsReal() { const makeShadowsRealOption: Blockly.ContextMenuRegistry.RegistryItem = { displayText(scope: Blockly.ContextMenuRegistry.Scope) { - const count = scope.block ? shadowConnections(scope.block).length : 0; + const count = scope.block + ? getShadowInputConnections(scope.block).length + : 0; return `Make ${count} shadow block${count === 1 ? '' : 's'} real`; }, preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { const block = scope.block; - if (block && !block.isInFlyout && shadowConnections(block).length) { + if ( + block && + !block.isInFlyout && + getShadowInputConnections(block).length + ) { return 'enabled'; } return 'hidden'; @@ -386,29 +382,34 @@ function registerMakeShadowsReal() { if (!block) { return; } - for (const connection of shadowConnections(block)) { - const state = connection.getShadowState(true); - if (!state) { - continue; - } - // Clear the shadow first, so that unplugging a covering block does - // not respawn it. - connection.setShadowState(null); - const coveringBlock = connection.targetBlock(); - coveringBlock?.unplug(); + const existingGroup = Blockly.Events.getGroup(); + if (!existingGroup) Blockly.Events.setGroup(true); + try { + for (const connection of getShadowInputConnections(block)) { + const state = connection.getShadowState(true); + if (!state) { + continue; + } + // Clear the shadow first, so that unplugging a covering block does + // not respawn it. + setShadowState(connection, null); + const coveringBlock = connection.targetBlock(); + coveringBlock?.unplug(); - const realBlock = Blockly.serialization.blocks.append( - state, - block.workspace, - {recordUndo: true}, - ); - const childConnection = - realBlock.outputConnection ?? realBlock.previousConnection; - if (childConnection) { - connection.connect(childConnection); + const realBlock = Blockly.serialization.blocks.append( + state, + block.workspace, + {recordUndo: true}, + ); + const childConnection = realBlock.outputConnection; + if (childConnection) { + connection.connect(childConnection); + } + // Move the unplugged block so it isn't hidden behind the new one. + coveringBlock?.bumpNeighbours(); } - // Move the unplugged block so it isn't hidden behind the new one. - coveringBlock?.bumpNeighbours(); + } finally { + Blockly.Events.setGroup(existingGroup); } }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, @@ -425,12 +426,18 @@ function registerMakeShadowsReal() { function registerRemoveShadows() { const removeShadowsOption: Blockly.ContextMenuRegistry.RegistryItem = { displayText(scope: Blockly.ContextMenuRegistry.Scope) { - const count = scope.block ? shadowConnections(scope.block).length : 0; + const count = scope.block + ? getShadowInputConnections(scope.block).length + : 0; return `Remove ${count} shadow block${count === 1 ? '' : 's'}`; }, preconditionFn(scope: Blockly.ContextMenuRegistry.Scope) { const block = scope.block; - if (block && !block.isInFlyout && shadowConnections(block).length) { + if ( + block && + !block.isInFlyout && + getShadowInputConnections(block).length + ) { return 'enabled'; } return 'hidden'; @@ -440,10 +447,16 @@ function registerRemoveShadows() { if (!block) { return; } - // Disposes a visible shadow, or forgets a covered one. - shadowConnections(block).forEach((connection) => - connection.setShadowState(null), - ); + const existingGroup = Blockly.Events.getGroup(); + if (!existingGroup) Blockly.Events.setGroup(true); + try { + // Disposes a visible shadow, or forgets a covered one. + getShadowInputConnections(block).forEach((connection) => + setShadowState(connection, null), + ); + } finally { + Blockly.Events.setGroup(existingGroup); + } }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonRemoveShadows', diff --git a/packages/plugins/lesson-authoring/src/shadow_state_change.ts b/packages/plugins/lesson-authoring/src/shadow_state_change.ts new file mode 100644 index 00000000000..b47b76fb4e7 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/shadow_state_change.ts @@ -0,0 +1,152 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview An event for changes to a connection's shadow state, which + * core does not fire one for, so that those changes can be undone. + */ + +import * as Blockly from 'blockly/core'; + +const SHADOW_STATE_CHANGE = 'lesson_shadow_state_change'; + +type ShadowState = Blockly.serialization.blocks.State | null; + +interface ShadowStateChangeJson extends Blockly.Events.BlockBaseJson { + inputName: string; + oldState: ShadowState; + newState: ShadowState; +} + +/** + * Notifies listeners that the shadow state of one of a block's value + * inputs has changed. + */ +class ShadowStateChange extends Blockly.Events.BlockBase { + override type = SHADOW_STATE_CHANGE; + + /** The input whose connection changed. */ + inputName: string; + + /** The shadow state before the change. */ + oldState: ShadowState; + + /** The shadow state after the change. */ + newState: ShadowState; + + /** + * @param block The block that owns the connection. Undefined for a blank + * event. + * @param inputName The input whose connection changed. + * @param oldState The shadow state before the change. + * @param newState The shadow state after the change. + */ + constructor( + block?: Blockly.Block, + inputName = '', + oldState: ShadowState = null, + newState: ShadowState = null, + ) { + super(block); + this.inputName = inputName; + this.oldState = oldState; + this.newState = newState; + } + + /** + * Encodes this event as JSON. + * + * @returns JSON representation. + */ + override toJson(): ShadowStateChangeJson { + const json = super.toJson() as ShadowStateChangeJson; + json.inputName = this.inputName; + json.oldState = this.oldState; + json.newState = this.newState; + return json; + } + + /** + * Deserializes the JSON event. + * + * @param json The JSON representation of the event. + * @param workspace The workspace the event belongs to. + * @param event The event to populate, if any. + * @returns The deserialized event. + */ + static fromJson( + json: ShadowStateChangeJson, + workspace: Blockly.Workspace, + event?: ShadowStateChange, + ): ShadowStateChange { + const newEvent = super.fromJson( + json, + workspace, + event ?? new ShadowStateChange(), + ) as ShadowStateChange; + newEvent.inputName = json.inputName; + newEvent.oldState = json.oldState; + newEvent.newState = json.newState; + return newEvent; + } + + /** + * Does this event record any change of state? + * + * @returns False if something changed. + */ + override isNull(): boolean { + return JSON.stringify(this.oldState) === JSON.stringify(this.newState); + } + + /** + * Applies the old or new shadow state to the connection. + * + * @param forward True to apply the new state, false to restore the old one. + */ + override run(forward: boolean) { + const block = this.blockId + ? this.getEventWorkspace_().getBlockById(this.blockId) + : null; + const connection = block?.getInput(this.inputName)?.connection; + if (!connection) { + console.warn("Can't set shadow state of non-existent connection"); + return; + } + connection.setShadowState(forward ? this.newState : this.oldState); + } +} + +Blockly.registry.register( + Blockly.registry.Type.EVENT, + SHADOW_STATE_CHANGE, + ShadowStateChange, +); + +/** + * Sets a connection's shadow state, firing an event so it can be undone. + * + * @param connection The connection to change. + * @param newState The new shadow state, or null to remove the shadow. + */ +export function setShadowState( + connection: Blockly.Connection, + newState: ShadowState, +) { + const block = connection.getSourceBlock(); + const inputName = block.inputList.find( + (input) => input.connection === connection, + )?.name; + if (!inputName) { + throw new Error('Could not find input name for connection'); + } + const oldState = connection.getShadowState(true); + // Fired before the change, so that undo restores the shadow state after + // any blocks moved by the same action have been put back. + Blockly.Events.fire( + new ShadowStateChange(block, inputName, oldState, newState), + ); + connection.setShadowState(newState); +} From 1b79eb34b148bf3994d3612807b07dc56535f097 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:43:22 -0500 Subject: [PATCH 05/10] fix: Make block state changes undo-able --- .../src/block_state_change.ts | 198 ++++++++++++++++++ .../lesson-authoring/src/block_state_menu.ts | 119 ++++++----- .../src/shadow_state_change.ts | 6 +- 3 files changed, 268 insertions(+), 55 deletions(-) create mode 100644 packages/plugins/lesson-authoring/src/block_state_change.ts diff --git a/packages/plugins/lesson-authoring/src/block_state_change.ts b/packages/plugins/lesson-authoring/src/block_state_change.ts new file mode 100644 index 00000000000..0905c19e569 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/block_state_change.ts @@ -0,0 +1,198 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview An event for changes to a block's deletable, editable or + * movable state, which core does not fire one for, so that those changes can + * be undone. + */ + +import * as Blockly from 'blockly/core'; + +const BLOCK_STATE_CHANGE = 'lesson_block_state_change'; + +/** A boolean block state that core changes without firing an event. */ +type BlockStateName = 'deletable' | 'editable' | 'movable'; + +interface BlockStateChangeJson extends Blockly.Events.BlockBaseJson { + element: BlockStateName; + oldValue: boolean; + newValue: boolean; +} + +/** + * Returns the value of one of a block's own boolean states. + * + * @param block The block to read. + * @param state The state to read. + * @returns The block's own value for the state. + */ +function getBlockState(block: Blockly.Block, state: BlockStateName): boolean { + switch (state) { + case 'deletable': + return block.isOwnDeletable(); + case 'editable': + return block.isOwnEditable(); + case 'movable': + return block.isOwnMovable(); + } +} + +/** + * Applies a value to one of a block's boolean states, without firing an event. + * + * @param block The block to change. + * @param state The state to change. + * @param value The new value of the state. + */ +function applyBlockState( + block: Blockly.Block, + state: BlockStateName, + value: boolean, +) { + switch (state) { + case 'deletable': + block.setDeletable(value); + break; + case 'editable': + block.setEditable(value); + break; + case 'movable': + block.setMovable(value); + break; + } +} + +/** + * Notifies listeners that a block's deletable, editable or movable state has + * changed. + */ +class BlockStateChange extends Blockly.Events.BlockBase { + override type = BLOCK_STATE_CHANGE; + + /** The state that changed. Undefined for a blank event. */ + element?: BlockStateName; + + /** The value before the change. */ + oldValue: boolean; + + /** The value after the change. */ + newValue: boolean; + + /** + * @param block The changed block. Undefined for a blank event. + * @param element The state that changed. + * @param oldValue The value before the change. + * @param newValue The value after the change. + */ + constructor( + block?: Blockly.Block, + element?: BlockStateName, + oldValue = false, + newValue = false, + ) { + super(block); + this.element = element; + this.oldValue = oldValue; + this.newValue = newValue; + } + + /** + * Encodes this event as JSON. + * + * @returns JSON representation. + */ + override toJson(): BlockStateChangeJson { + if (!this.element) { + throw new Error( + 'The changed element is undefined. Either pass an element to the ' + + 'constructor, or call fromJson', + ); + } + const json = super.toJson() as BlockStateChangeJson; + json.element = this.element; + json.oldValue = this.oldValue; + json.newValue = this.newValue; + return json; + } + + /** + * Deserializes the JSON event. + * + * @param json The JSON representation of the event. + * @param workspace The workspace the event belongs to. + * @param event The event to populate, if any. + * @returns The deserialized event. + */ + static fromJson( + json: BlockStateChangeJson, + workspace: Blockly.Workspace, + event?: BlockStateChange, + ): BlockStateChange { + const newEvent = super.fromJson( + json, + workspace, + event ?? new BlockStateChange(), + ) as BlockStateChange; + newEvent.element = json.element; + newEvent.oldValue = json.oldValue; + newEvent.newValue = json.newValue; + return newEvent; + } + + /** + * Does this event record any change of state? + * + * @returns False if something changed. + */ + override isNull(): boolean { + return this.oldValue === this.newValue; + } + + /** + * Applies the old or new value to the block. + * + * @param forward True to apply the new value, false to restore the old one. + */ + override run(forward: boolean) { + const block = this.blockId + ? this.getEventWorkspace_().getBlockById(this.blockId) + : null; + if (!block || !this.element) { + console.warn("Can't change state of non-existent block"); + return; + } + applyBlockState( + block, + this.element, + forward ? this.newValue : this.oldValue, + ); + } +} + +Blockly.registry.register( + Blockly.registry.Type.EVENT, + BLOCK_STATE_CHANGE, + BlockStateChange, +); + +/** + * Sets a block's deletable, editable or movable state, firing an event so it + * can be undone. + * + * @param block The block to change. + * @param state The state to set. + * @param value The new value of the state. + */ +export function setBlockState( + block: Blockly.Block, + state: BlockStateName, + value: boolean, +) { + Blockly.Events.fire( + new BlockStateChange(block, state, getBlockState(block, state), value), + ); + applyBlockState(block, state, value); +} diff --git a/packages/plugins/lesson-authoring/src/block_state_menu.ts b/packages/plugins/lesson-authoring/src/block_state_menu.ts index 6ff6c96523f..664ad524bc2 100644 --- a/packages/plugins/lesson-authoring/src/block_state_menu.ts +++ b/packages/plugins/lesson-authoring/src/block_state_menu.ts @@ -8,8 +8,25 @@ */ import * as Blockly from 'blockly/core'; +import {setBlockState} from './block_state_change'; import {setShadowState} from './shadow_state_change'; +/** + * Runs a callback with its events in one group, so they undo as one step. + * Joins the current group if there is one. + * + * @param callback The function whose events to group. + */ +function executeInEventGroup(callback: () => void) { + const existingGroup = Blockly.Events.getGroup(); + if (!existingGroup) Blockly.Events.setGroup(true); + try { + callback(); + } finally { + Blockly.Events.setGroup(existingGroup); + } +} + /** * Returns all blocks in the workspace that are not shadows. * @@ -46,7 +63,7 @@ function registerDeletable() { if (!block) { throw new Error('No block in scope for context menu item'); } - block.setDeletable(!block.isOwnDeletable()); + setBlockState(block, 'deletable', !block.isOwnDeletable()); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonBlockDeletable', @@ -88,13 +105,15 @@ function registerAllDeletable() { throw new Error('No workspace in scope for context menu item'); } const allBlocks = getNonShadowBlocks(workspace); - if (allBlocks.every((block) => !block.isOwnDeletable())) { - allBlocks.forEach((block) => block.setDeletable(true)); - } else { - allBlocks - .filter((block) => block.isOwnDeletable()) - .forEach((block) => block.setDeletable(false)); - } + executeInEventGroup(() => { + if (allBlocks.every((block) => !block.isOwnDeletable())) { + allBlocks.forEach((block) => setBlockState(block, 'deletable', true)); + } else { + allBlocks + .filter((block) => block.isOwnDeletable()) + .forEach((block) => setBlockState(block, 'deletable', false)); + } + }); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE, id: 'lessonAllBlocksDeletable', @@ -126,15 +145,19 @@ function registerEditable() { throw new Error('No block in scope for context menu item'); } const editable = !block.isOwnEditable(); - block.setEditable(editable); - block - .getChildren(false) - .filter((child) => child.isShadow()) - .forEach((shadow) => - shadow - .getDescendants(false) - .forEach((descendant) => descendant.setEditable(editable)), - ); + executeInEventGroup(() => { + setBlockState(block, 'editable', editable); + block + .getChildren(false) + .filter((child) => child.isShadow()) + .forEach((shadow) => + shadow + .getDescendants(false) + .forEach((descendant) => + setBlockState(descendant, 'editable', editable), + ), + ); + }); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonBlockEditable', @@ -175,13 +198,15 @@ function registerAllEditable() { } const allBlocks = workspace.getAllBlocks(); - if (allBlocks.every((block) => !block.isOwnEditable())) { - allBlocks.forEach((block) => block.setEditable(true)); - } else { - allBlocks - .filter((block) => block.isOwnEditable()) - .forEach((block) => block.setEditable(false)); - } + executeInEventGroup(() => { + if (allBlocks.every((block) => !block.isOwnEditable())) { + allBlocks.forEach((block) => setBlockState(block, 'editable', true)); + } else { + allBlocks + .filter((block) => block.isOwnEditable()) + .forEach((block) => setBlockState(block, 'editable', false)); + } + }); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE, id: 'lessonAllBlocksEditable', @@ -216,7 +241,7 @@ function registerMovable() { if (!block) { throw new Error('No block in scope for context menu item'); } - block.setMovable(!block.isOwnMovable()); + setBlockState(block, 'movable', !block.isOwnMovable()); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonBlockMovable', @@ -259,13 +284,15 @@ function registerAllMovable() { } const allBlocks = getNonShadowBlocks(workspace); - if (allBlocks.every((block) => !block.isOwnMovable())) { - allBlocks.forEach((block) => block.setMovable(true)); - } else { - allBlocks - .filter((block) => block.isOwnMovable()) - .forEach((block) => block.setMovable(false)); - } + executeInEventGroup(() => { + if (allBlocks.every((block) => !block.isOwnMovable())) { + allBlocks.forEach((block) => setBlockState(block, 'movable', true)); + } else { + allBlocks + .filter((block) => block.isOwnMovable()) + .forEach((block) => setBlockState(block, 'movable', false)); + } + }); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE, id: 'lessonAllBlocksMovable', @@ -337,15 +364,11 @@ function registerMakeShadow() { if (!state) { return; } - const existingGroup = Blockly.Events.getGroup(); - if (!existingGroup) Blockly.Events.setGroup(true); - try { + executeInEventGroup(() => { setShadowState(connection, state); // Unplugging the block respawns the shadow in its place. block.dispose(false); - } finally { - Blockly.Events.setGroup(existingGroup); - } + }); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonMakeShadow', @@ -382,9 +405,7 @@ function registerMakeShadowsReal() { if (!block) { return; } - const existingGroup = Blockly.Events.getGroup(); - if (!existingGroup) Blockly.Events.setGroup(true); - try { + executeInEventGroup(() => { for (const connection of getShadowInputConnections(block)) { const state = connection.getShadowState(true); if (!state) { @@ -408,9 +429,7 @@ function registerMakeShadowsReal() { // Move the unplugged block so it isn't hidden behind the new one. coveringBlock?.bumpNeighbours(); } - } finally { - Blockly.Events.setGroup(existingGroup); - } + }); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonMakeShadowsReal', @@ -447,16 +466,12 @@ function registerRemoveShadows() { if (!block) { return; } - const existingGroup = Blockly.Events.getGroup(); - if (!existingGroup) Blockly.Events.setGroup(true); - try { - // Disposes a visible shadow, or forgets a covered one. + // Disposes a visible shadow, or forgets a covered one. + executeInEventGroup(() => getShadowInputConnections(block).forEach((connection) => setShadowState(connection, null), - ); - } finally { - Blockly.Events.setGroup(existingGroup); - } + ), + ); }, scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK, id: 'lessonRemoveShadows', diff --git a/packages/plugins/lesson-authoring/src/shadow_state_change.ts b/packages/plugins/lesson-authoring/src/shadow_state_change.ts index b47b76fb4e7..6437c62558e 100644 --- a/packages/plugins/lesson-authoring/src/shadow_state_change.ts +++ b/packages/plugins/lesson-authoring/src/shadow_state_change.ts @@ -21,8 +21,8 @@ interface ShadowStateChangeJson extends Blockly.Events.BlockBaseJson { } /** - * Notifies listeners that the shadow state of one of a block's value - * inputs has changed. + * Notifies listeners that the shadow state of one of a block's value inputs + * has changed. */ class ShadowStateChange extends Blockly.Events.BlockBase { override type = SHADOW_STATE_CHANGE; @@ -128,7 +128,7 @@ Blockly.registry.register( /** * Sets a connection's shadow state, firing an event so it can be undone. * - * @param connection The connection to change. + * @param connection The value input connection to change. * @param newState The new shadow state, or null to remove the shadow. */ export function setShadowState( From 8e1fd218b9ce89c36cd34f1a18e1963c2082b30b Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:12:07 -0500 Subject: [PATCH 06/10] feat: block state glyphs icon --- .../src/block_state_change.ts | 5 +- .../src/block_state_glyphs.ts | 126 +++++++ .../lesson-authoring/src/block_state_icon.ts | 315 ++++++++++++++++++ .../lesson-authoring/src/colour_contrast.ts | 127 +++++++ .../plugins/lesson-authoring/src/index.ts | 2 + .../test/block_state_icon.mocha.js | 153 +++++++++ .../test/colour_contrast.mocha.js | 22 ++ 7 files changed, 749 insertions(+), 1 deletion(-) create mode 100644 packages/plugins/lesson-authoring/src/block_state_glyphs.ts create mode 100644 packages/plugins/lesson-authoring/src/block_state_icon.ts create mode 100644 packages/plugins/lesson-authoring/src/colour_contrast.ts create mode 100644 packages/plugins/lesson-authoring/test/block_state_icon.mocha.js create mode 100644 packages/plugins/lesson-authoring/test/colour_contrast.mocha.js diff --git a/packages/plugins/lesson-authoring/src/block_state_change.ts b/packages/plugins/lesson-authoring/src/block_state_change.ts index 0905c19e569..5a4fe7c2714 100644 --- a/packages/plugins/lesson-authoring/src/block_state_change.ts +++ b/packages/plugins/lesson-authoring/src/block_state_change.ts @@ -10,6 +10,7 @@ */ import * as Blockly from 'blockly/core'; +import {refreshBlockStateIcon} from './block_state_icon'; const BLOCK_STATE_CHANGE = 'lesson_block_state_change'; @@ -41,7 +42,8 @@ function getBlockState(block: Blockly.Block, state: BlockStateName): boolean { } /** - * Applies a value to one of a block's boolean states, without firing an event. + * Applies a value to one of a block's boolean states and updates the + * block's state icon. * * @param block The block to change. * @param state The state to change. @@ -63,6 +65,7 @@ function applyBlockState( block.setMovable(value); break; } + refreshBlockStateIcon(block); } /** diff --git a/packages/plugins/lesson-authoring/src/block_state_glyphs.ts b/packages/plugins/lesson-authoring/src/block_state_glyphs.ts new file mode 100644 index 00000000000..e78408c0064 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/block_state_glyphs.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview Claude-generated glyphs for a block's deletable, editable and + * movable states being turned off: a slashed trash can, a slashed pencil and + * a pin. + */ + +import * as Blockly from 'blockly/core'; + +/** A state that has been turned off on a block. */ +export type Restriction = 'deletable' | 'editable' | 'movable'; + +/** The width and height of each glyph, in workspace-scale units. */ +const GLYPH_SIZE = 16; + +/** The space between glyphs, in workspace-scale units. */ +const GLYPH_GAP = 2; + +/** Outlines of each glyph, drawn on a 16x16 grid. */ +const GLYPH_PATHS: Record = { + deletable: 'M2.5 4.5h11M6 4.5V3h4v1.5M4 4.5l.8 9h6.4l.8-9', // Trash can with slash + editable: 'M3 13l.8-3 6.7-6.7 2.2 2.2L6 12.2zM9.3 4.5l2.2 2.2', // Pencil with slash + movable: 'M5.5 2.5h5M6.5 2.5v3.8L4.5 9h7l-2-2.7V2.5M8 9v4.5', // Pin +}; + +// Glyphs are drawn in the current text colour, so whoever draws them picks the +// colour by setting `color` on an ancestor. +Blockly.Css.register(` +.lessonBlockStateGlyph { + fill: none; + stroke: currentColor; + stroke-width: 1.6px; + stroke-linecap: round; + stroke-linejoin: round; +} +.lessonBlockStateGap { + stroke: #000; + stroke-width: 2.4px; + stroke-linecap: round; +} +`); + +/** + * Gets the width of a row of glyphs. + * + * @param count The number of glyphs in the row. + * @returns The row's width, in workspace-scale units. + */ +export function getGlyphRowWidth(count: number): number { + return count * GLYPH_SIZE + Math.max(count - 1, 0) * GLYPH_GAP; +} + +/** + * Draws a row of glyphs, one for each restriction, starting at the left edge + * of their parent and centred vertically in the given height. + * + * @param parent The element to draw the glyphs in. + * @param restrictions The restrictions to draw glyphs for, in order. + * @param height The height of the row, in workspace-scale units. + */ +export function drawGlyphRow( + parent: SVGElement, + restrictions: Restriction[], + height: number, +) { + const top = (height - GLYPH_SIZE) / 2; + restrictions.forEach((restriction, i) => { + const glyph = Blockly.utils.dom.createSvgElement( + Blockly.utils.Svg.G, + {transform: `translate(${i * (GLYPH_SIZE + GLYPH_GAP)}, ${top})`}, + parent, + ); + const path = Blockly.utils.dom.createSvgElement( + Blockly.utils.Svg.PATH, + {class: 'lessonBlockStateGlyph', d: GLYPH_PATHS[restriction]}, + glyph, + ); + // The pin already means "can't move", so it is drawn without a slash. + if (restriction !== 'movable') drawSlash(glyph, path); + }); +} + +/** + * Draws a slash across a glyph, with a gap cut out of the glyph along the + * slash's upper side so that the two read as separate shapes. The gap is a + * mask rather than a stroke in the block's colour, so it stays correct when + * the block's colour or style changes. + * + * @param glyph The group to draw the slash in. + * @param path The glyph's outline, which the gap is cut from. + */ +function drawSlash(glyph: SVGGElement, path: SVGElement) { + const maskId = Blockly.utils.idGenerator.getNextUniqueId(); + const mask = Blockly.utils.dom.createSvgElement( + 'mask', + { + id: maskId, + maskUnits: 'userSpaceOnUse', + x: 0, + y: 0, + width: GLYPH_SIZE, + height: GLYPH_SIZE, + }, + glyph, + ); + Blockly.utils.dom.createSvgElement( + Blockly.utils.Svg.RECT, + {width: GLYPH_SIZE, height: GLYPH_SIZE, fill: '#fff'}, + mask, + ); + Blockly.utils.dom.createSvgElement( + Blockly.utils.Svg.LINE, + {class: 'lessonBlockStateGap', x1: 3.1, y1: 0.9, x2: 15.1, y2: 12.9}, + mask, + ); + path.setAttribute('mask', `url(#${maskId})`); + Blockly.utils.dom.createSvgElement( + Blockly.utils.Svg.LINE, + {class: 'lessonBlockStateGlyph', x1: 2, y1: 2, x2: 14, y2: 14}, + glyph, + ); +} diff --git a/packages/plugins/lesson-authoring/src/block_state_icon.ts b/packages/plugins/lesson-authoring/src/block_state_icon.ts new file mode 100644 index 00000000000..ec3ebf163d2 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/block_state_icon.ts @@ -0,0 +1,315 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview An icon showing which of a block's deletable, editable and + * movable states are turned off, and a per-workspace switch for it. + */ + +import * as Blockly from 'blockly/core'; +import {drawGlyphRow, getGlyphRowWidth} from './block_state_glyphs'; +import type {Restriction} from './block_state_glyphs'; +import {pickContrastingColour} from './colour_contrast'; + +/** The size of the icon in workspace-scale units. */ +const ICON_HEIGHT = 17; + +/** The space between the glyphs and the focus ring, in workspace units. */ +const FOCUS_RING_MARGIN = 3; + +/** + * The label for each restriction. Each is a complete phrase that is shown as + * written, so it can be translated without the code changing its case or + * combining it into a sentence. TODO: Translate these labels. + */ +const LABELS: Record = { + deletable: "Can't delete", + editable: "Can't edit", + movable: "Can't move", +}; + +// Core dims icons until they are hovered or focused, to show they can be +// clicked. This icon can't be clicked, so it is always shown at full opacity. +Blockly.Css.register(` +.blocklyIconGroup.lessonBlockStateIcon:not(:hover):not(:focus) { + opacity: 1; +} +.lessonBlockStateIcon > .blocklyIconShape { + fill: none; + stroke: none; +} +`); + +/** + * Returns the states that are turned off on a block, in display order. Shadow + * blocks can never be moved or deleted on their own, so only their editable + * state is shown. + * + * @param block The block to read. + * @returns The restrictions to show. + */ +function getRestrictions(block: Blockly.Block): Restriction[] { + const restrictions: Restriction[] = []; + if (!block.isShadow() && !block.isOwnDeletable()) { + restrictions.push('deletable'); + } + if (!block.isOwnEditable()) restrictions.push('editable'); + if (!block.isShadow() && !block.isOwnMovable()) restrictions.push('movable'); + return restrictions; +} + +/** + * An icon showing a glyph for each of a block's deletable, editable and + * movable states that is turned off. + */ +export class BlockStateIcon extends Blockly.icons.Icon { + /** The type of this icon. */ + static readonly TYPE = new Blockly.icons.IconType( + 'lesson_block_state', + ); + + /** Places this icon after core's mutator, warning and comment icons. */ + static readonly WEIGHT = 4; + + private restrictions: Restriction[]; + + /** + * @param sourceBlock The block this icon is attached to. + * @param restrictions The restrictions to show. + */ + constructor(sourceBlock: Blockly.Block, restrictions: Restriction[]) { + super(sourceBlock); + this.restrictions = restrictions; + this.updateTooltip(); + } + + override getType(): Blockly.icons.IconType { + return BlockStateIcon.TYPE; + } + + override getWeight(): number { + return BlockStateIcon.WEIGHT; + } + + override getSize(): Blockly.utils.Size { + return new Blockly.utils.Size( + getGlyphRowWidth(this.restrictions.length), + ICON_HEIGHT, + ); + } + + override initView(pointerdownListener: (e: PointerEvent) => void): void { + if (this.svgRoot) return; + super.initView(pointerdownListener); + this.getFocusableElement().classList.add('lessonBlockStateIcon'); + this.drawGlyphs(); + } + + override applyColour(): void { + this.updateGlyphColour(); + } + + /** + * Updates the glyph colour on every render, as well as when the block's + * colour is applied. A full-block field repaints the block after its icons' + * colours are applied, and again whenever its value changes, so the colour + * the icon sees in applyColour can be out of date. + * + * @param offset The icon's position relative to its block's top-start. + */ + override setOffsetInBlock(offset: Blockly.utils.Coordinate): void { + super.setOffsetInBlock(offset); + this.updateGlyphColour(); + } + + /** + * Draws the glyphs in white, like block text. If the block's is a full-block + * field, the glyphs sit on that field's background, so they use the block's + * colour, or black or white if that doesn't stand out against the block's fill. + */ + private updateGlyphColour() { + if (!this.svgRoot) return; + const block = this.sourceBlock as Blockly.BlockSvg; + const fields = [...block.getFields()]; + const isFullBlockField = + fields.length === 1 && fields[0].isFullBlockField(); + const background = block.pathObject.svgPath.getAttribute('fill') ?? ''; + this.svgRoot.style.color = isFullBlockField + ? pickContrastingColour(block.getColour(), background) + : '#fff'; + } + + /** + * Changes the restrictions this icon shows. + * + * @param restrictions The restrictions to show. + */ + setRestrictions(restrictions: Restriction[]) { + const sizeChanged = restrictions.length !== this.restrictions.length; + this.restrictions = restrictions; + this.updateTooltip(); + if (!this.svgRoot) return; + this.drawGlyphs(); + this.recomputeAriaContext(); + if (sizeChanged) (this.sourceBlock as Blockly.BlockSvg).queueRender(); + } + + /** + * Lists the restrictions separated by commas, the way core joins the parts + * of its own ARIA labels. + */ + protected override getAriaLabel(): string { + return this.getLabels().join(', '); + } + + /** Sets the tooltip to list this icon's restrictions, one per line. */ + private updateTooltip() { + this.setTooltip(this.getLabels().join('\n')); + } + + /** + * Gets the label for each of this icon's restrictions, in display order. + * + * @returns The labels. + */ + private getLabels(): string[] { + return this.restrictions.map((restriction) => LABELS[restriction]); + } + + /** Replaces the icon's glyphs with ones for its current restrictions. */ + private drawGlyphs() { + const svgRoot = this.svgRoot; + if (!svgRoot) return; + svgRoot.replaceChildren(); + // Core draws an icon's focus ring on its first blocklyIconShape. This one + // is otherwise invisible, and sits just outside the glyphs. + const size = this.getSize(); + Blockly.utils.dom.createSvgElement( + Blockly.utils.Svg.RECT, + { + class: 'blocklyIconShape', + x: -FOCUS_RING_MARGIN, + y: -FOCUS_RING_MARGIN, + width: size.width + 2 * FOCUS_RING_MARGIN, + height: size.height + 2 * FOCUS_RING_MARGIN, + rx: FOCUS_RING_MARGIN, + }, + svgRoot, + ); + drawGlyphRow(svgRoot, this.restrictions, ICON_HEIGHT); + } +} + +/** The indicators switched on for each workspace. */ +const indicatorsByWorkspace = new WeakMap< + Blockly.Workspace, + BlockStateIndicators +>(); + +/** + * Adds, updates or removes a block's state icon to match its deletable, + * editable and movable states, if indicators are switched on for its + * workspace. + * + * @param block The block to update. + */ +export function refreshBlockStateIcon(block: Blockly.Block) { + if (!indicatorsByWorkspace.get(block.workspace)?.isEnabled()) return; + showBlockStateIcon(block); +} + +/** + * Adds, updates or removes a block's state icon to match its states. + * + * @param block The block to update. + */ +function showBlockStateIcon(block: Blockly.Block) { + if (block.isInFlyout || block.isInsertionMarker()) return; + const restrictions = getRestrictions(block); + const icon = block.getIcon(BlockStateIcon.TYPE) as BlockStateIcon | undefined; + if (!restrictions.length) { + block.removeIcon(BlockStateIcon.TYPE); + } else if (icon) { + icon.setRestrictions(restrictions); + } else { + block.addIcon(new BlockStateIcon(block, restrictions)); + } +} + +/** Options for {@link BlockStateIndicators}. */ +export interface BlockStateIndicatorsOptions { + /** Whether the indicators start switched on. Defaults to true. */ + enabled?: boolean; +} + +/** + * Shows icons on a workspace's blocks for any deletable, editable or movable + * state that is turned off, and keeps them up to date as blocks are created + * and as those states change through the lesson-authoring context menu or + * undo. + */ +export class BlockStateIndicators { + private enabled = false; + + /** + * Adds icons to blocks as they are loaded, pasted or restored. + * + * @param event The workspace event. + */ + private readonly onChange = (event: Blockly.Events.Abstract) => { + if (event.type !== Blockly.Events.BLOCK_CREATE) return; + for (const id of (event as Blockly.Events.BlockCreate).ids ?? []) { + const block = this.workspace.getBlockById(id); + if (block) showBlockStateIcon(block); + } + }; + + /** + * Blocks are found when the indicators are switched on and from their + * creation events afterwards, so blocks loaded with events disabled are only + * picked up if the indicators are created after loading. + * + * @param workspace The workspace to show indicators on. Replaces any + * indicators already created for it. + * @param options Options for the indicators. + */ + constructor( + private readonly workspace: Blockly.Workspace, + options: BlockStateIndicatorsOptions = {}, + ) { + indicatorsByWorkspace.get(workspace)?.setEnabled(false); + indicatorsByWorkspace.set(workspace, this); + this.setEnabled(options.enabled ?? true); + } + + /** + * Returns whether the indicators are switched on. + * + * @returns True if the indicators are shown. + */ + isEnabled(): boolean { + return this.enabled; + } + + /** + * Switches the indicators on or off, adding or removing icons on every + * block in the workspace. + * + * @param enabled True to show the indicators. + */ + setEnabled(enabled: boolean) { + if (enabled === this.enabled) return; + this.enabled = enabled; + if (enabled) { + this.workspace.addChangeListener(this.onChange); + this.workspace.getAllBlocks(false).forEach(showBlockStateIcon); + } else { + this.workspace.removeChangeListener(this.onChange); + this.workspace + .getAllBlocks(false) + .forEach((block) => block.removeIcon(BlockStateIcon.TYPE)); + } + } +} diff --git a/packages/plugins/lesson-authoring/src/colour_contrast.ts b/packages/plugins/lesson-authoring/src/colour_contrast.ts new file mode 100644 index 00000000000..1f074fdf705 --- /dev/null +++ b/packages/plugins/lesson-authoring/src/colour_contrast.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * @fileoverview Picks colours that stand out against a background, using the + * WCAG definition of contrast. + */ + +import * as Blockly from 'blockly/core'; + +// The constants below come from the WCAG 2.2 definition of relative luminance: +// https://www.w3.org/TR/WCAG22/#dfn-relative-luminance + +/** How much red contributes to perceived brightness. */ +const RED_WEIGHT = 0.2126; + +/** How much green contributes to perceived brightness. */ +const GREEN_WEIGHT = 0.7152; + +/** How much blue contributes to perceived brightness. */ +const BLUE_WEIGHT = 0.0722; + +/** At or below this sRGB value, the sRGB curve is a straight line. */ +const SRGB_LINEAR_THRESHOLD = 0.04045; + +/** The slope of the straight part of the sRGB curve. */ +const SRGB_LINEAR_SLOPE = 12.92; + +/** The offset applied before the curved part of the sRGB curve. */ +const SRGB_CURVE_OFFSET = 0.055; + +/** The scale applied before the curved part of the sRGB curve. */ +const SRGB_CURVE_SCALE = 1.055; + +/** The exponent of the curved part of the sRGB curve. */ +const SRGB_CURVE_EXPONENT = 2.4; + +/** + * Added to both luminances in a contrast ratio, to account for light + * reflecting off the screen. From the WCAG 2.2 definition of contrast ratio: + * https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio + */ +const SCREEN_FLARE = 0.05; + +/** + * The contrast ratio to enforce between graphical objects and their backgrounds. + * WCAG asks for a minimum contrast of 3:1. + */ +const MIN_CONTRAST = 3; + +const BLACK = '#000000'; +const WHITE = '#ffffff'; + +/** + * Converts a red, green or blue channel value to the amount of light the + * screen gives off for it. + * + * @param channel The channel value, between 0 and 255. + * @returns The amount of light, between 0 and 1. + */ +function channelToLight(channel: number): number { + const value = channel / 255; + if (value <= SRGB_LINEAR_THRESHOLD) { + return value / SRGB_LINEAR_SLOPE; + } + const shifted = (value + SRGB_CURVE_OFFSET) / SRGB_CURVE_SCALE; + return shifted ** SRGB_CURVE_EXPONENT; +} + +/** + * Gets how bright a colour looks, as defined by WCAG. + * + * @param hex The colour, as a hex string. + * @returns The relative luminance, from 0 for black to 1 for white. + */ +function getLuminance(hex: string): number { + const [red, green, blue] = Blockly.utils.colour + .hexToRgb(hex) + .map(channelToLight); + return RED_WEIGHT * red + GREEN_WEIGHT * green + BLUE_WEIGHT * blue; +} + +/** + * Gets the contrast ratio between two colours, as defined by WCAG. + * + * @param hex1 A colour, as a hex string. The order of the two colours doesn't + * matter. + * @param hex2 Another colour, as a hex string. + * @returns The contrast ratio, from 1 for identical colours to 21 for black + * and white. + */ +function getContrast(hex1: string, hex2: string): number { + const luminance1 = getLuminance(hex1); + const luminance2 = getLuminance(hex2); + const lighter = Math.max(luminance1, luminance2); + const darker = Math.min(luminance1, luminance2); + return (lighter + SCREEN_FLARE) / (darker + SCREEN_FLARE); +} + +/** + * Picks a colour for graphics drawn on a background: the preferred colour if + * it has the contrast WCAG asks for, otherwise whichever of black or white + * contrasts more. + * + * @param preferred The colour to use if it stands out enough, in any format + * `Blockly.utils.colour.parse` accepts. + * @param background The background colour, in any format + * `Blockly.utils.colour.parse` accepts. + * @returns The colour to use, as a hex string. White if either colour can't + * be parsed. + */ +export function pickContrastingColour( + preferred: string, + background: string, +): string { + const preferredHex = Blockly.utils.colour.parse(preferred); + const backgroundHex = Blockly.utils.colour.parse(background); + if (!preferredHex || !backgroundHex) return WHITE; + if (getContrast(preferredHex, backgroundHex) >= MIN_CONTRAST) { + return preferredHex; + } + return getContrast(BLACK, backgroundHex) > getContrast(WHITE, backgroundHex) + ? BLACK + : WHITE; +} diff --git a/packages/plugins/lesson-authoring/src/index.ts b/packages/plugins/lesson-authoring/src/index.ts index 59e7579f8f2..6d09979910d 100644 --- a/packages/plugins/lesson-authoring/src/index.ts +++ b/packages/plugins/lesson-authoring/src/index.ts @@ -10,3 +10,5 @@ export * from './artifact_types'; export * from './requirements'; export * from './block_state_menu'; +export {BlockStateIndicators} from './block_state_icon'; +export type {BlockStateIndicatorsOptions} from './block_state_icon'; diff --git a/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js b/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js new file mode 100644 index 00000000000..f26919d9a39 --- /dev/null +++ b/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js @@ -0,0 +1,153 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +import {assert} from 'chai'; +import * as Blockly from 'blockly'; +import {BlockStateIndicators} from '../src/index'; +import {BlockStateIcon} from '../src/block_state_icon'; +import {setBlockState} from '../src/block_state_change'; + +/** + * Waits for queued events to be fired to listeners and the undo stack. + * @returns {!Promise} Resolves once events have fired. + */ +function flushEvents() { + return new Promise((resolve) => setTimeout(resolve)); +} + +/** + * Returns the number of glyphs a block's state icon shows, or 0 if it has no + * icon. Each glyph is 16 units wide, with a 2 unit gap between them. + * @param {!Blockly.Block} block The block to read. + * @returns {number} The number of glyphs. + */ +function glyphCount(block) { + const icon = block.getIcon(BlockStateIcon.TYPE); + return icon ? (icon.getSize().width + 2) / 18 : 0; +} + +// State set before the indicators are created uses core's setters, which don't +// update icons, so only the indicators' initial sweep can add them. State +// changed afterwards uses setBlockState, which is how the plugin keeps icons up +// to date. +suite('Block state indicators', function () { + setup(function () { + this.workspace = new Blockly.Workspace(); + }); + + teardown(function () { + this.workspace.dispose(); + }); + + test('adds icons to existing restricted blocks', function () { + const block = this.workspace.newBlock('math_number'); + block.setMovable(false); + block.setDeletable(false); + new BlockStateIndicators(this.workspace); + assert.equal(glyphCount(block), 2); + }); + + test("doesn't add icons to blocks without restrictions", function () { + const block = this.workspace.newBlock('math_number'); + new BlockStateIndicators(this.workspace); + assert.isFalse(block.hasIcon(BlockStateIcon.TYPE)); + }); + + test('starts turned off when asked', function () { + const block = this.workspace.newBlock('math_number'); + block.setMovable(false); + new BlockStateIndicators(this.workspace, {enabled: false}); + assert.isFalse(block.hasIcon(BlockStateIcon.TYPE)); + }); + + test('removes icons when turned off', function () { + const block = this.workspace.newBlock('math_number'); + block.setEditable(false); + const indicators = new BlockStateIndicators(this.workspace); + indicators.setEnabled(false); + assert.isFalse(block.hasIcon(BlockStateIcon.TYPE)); + }); + + test('loaded blocks get icons', async function () { + new BlockStateIndicators(this.workspace); + Blockly.serialization.workspaces.load( + { + blocks: { + languageVersion: 0, + blocks: [{type: 'math_number', id: 'loaded', deletable: false}], + }, + }, + this.workspace, + ); + await flushEvents(); + assert.equal(glyphCount(this.workspace.getBlockById('loaded')), 1); + }); + + test('shadow blocks only show the editable restriction', function () { + const block = this.workspace.newBlock('math_number'); + block.setShadow(true); + block.setMovable(false); + block.setDeletable(false); + new BlockStateIndicators(this.workspace); + assert.isFalse(block.hasIcon(BlockStateIcon.TYPE)); + + setBlockState(block, 'editable', false); + assert.equal(glyphCount(block), 1); + }); + + suite('state changes', function () { + setup(function () { + this.block = this.workspace.newBlock('math_number'); + new BlockStateIndicators(this.workspace); + }); + + test('adding a restriction adds the icon', function () { + setBlockState(this.block, 'movable', false); + assert.equal(glyphCount(this.block), 1); + }); + + test('adding more restrictions widens the icon', function () { + setBlockState(this.block, 'movable', false); + setBlockState(this.block, 'editable', false); + setBlockState(this.block, 'deletable', false); + assert.equal(glyphCount(this.block), 3); + }); + + test('restrictions are shown in the tooltip', function () { + setBlockState(this.block, 'movable', false); + setBlockState(this.block, 'editable', false); + setBlockState(this.block, 'deletable', false); + assert.equal( + this.block.getIcon(BlockStateIcon.TYPE).getTooltip(), + "Can't delete\nCan't edit\nCan't move", + ); + }); + + test('removing the last restriction removes the icon', function () { + setBlockState(this.block, 'movable', false); + setBlockState(this.block, 'movable', true); + assert.isFalse(this.block.hasIcon(BlockStateIcon.TYPE)); + }); + + test('undo and redo update the icon', async function () { + setBlockState(this.block, 'deletable', false); + await flushEvents(); + + this.workspace.undo(false); + assert.isFalse(this.block.hasIcon(BlockStateIcon.TYPE)); + + this.workspace.undo(true); + assert.equal(glyphCount(this.block), 1); + }); + }); + + test('state changes are ignored while turned off', function () { + const block = this.workspace.newBlock('math_number'); + new BlockStateIndicators(this.workspace, {enabled: false}); + setBlockState(block, 'movable', false); + assert.isFalse(block.hasIcon(BlockStateIcon.TYPE)); + }); +}); diff --git a/packages/plugins/lesson-authoring/test/colour_contrast.mocha.js b/packages/plugins/lesson-authoring/test/colour_contrast.mocha.js new file mode 100644 index 00000000000..da0dd4572ff --- /dev/null +++ b/packages/plugins/lesson-authoring/test/colour_contrast.mocha.js @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +import {assert} from 'chai'; +import {pickContrastingColour} from '../src/colour_contrast'; + +suite('pickContrastingColour', function () { + test('keeps the preferred colour when it contrasts enough', function () { + assert.equal(pickContrastingColour('#ff0000', '#ffffff'), '#ff0000'); + }); + + test('uses black on light backgrounds', function () { + assert.equal(pickContrastingColour('#eeee00', '#ffff00'), '#000000'); + }); + + test('uses white on dark backgrounds', function () { + assert.equal(pickContrastingColour('#330033', '#440044'), '#ffffff'); + }); +}); From 0982e3ece643333603711328b9d4e28fb46cd0b9 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:44:26 -0500 Subject: [PATCH 07/10] chore: use fake timers in tests --- package-lock.json | 1 + .../plugins/lesson-authoring/package.json | 1 + .../test/block_state_icon.mocha.js | 20 ++++++++----------- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/package-lock.json b/package-lock.json index 24d4fd24d23..dcb7778cd12 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32698,6 +32698,7 @@ "devDependencies": { "@blockly/dev-scripts": "^13.4.0", "@blockly/dev-tools": "^13.4.0", + "sinon": "^22.1.0", "typescript": "^6.0.3" }, "peerDependencies": { diff --git a/packages/plugins/lesson-authoring/package.json b/packages/plugins/lesson-authoring/package.json index a56212671aa..36822e93125 100644 --- a/packages/plugins/lesson-authoring/package.json +++ b/packages/plugins/lesson-authoring/package.json @@ -42,6 +42,7 @@ "devDependencies": { "@blockly/dev-scripts": "^13.4.0", "@blockly/dev-tools": "^13.4.0", + "sinon": "^22.1.0", "typescript": "^6.0.3" }, "peerDependencies": { diff --git a/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js b/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js index f26919d9a39..e67bc9dac02 100644 --- a/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js +++ b/packages/plugins/lesson-authoring/test/block_state_icon.mocha.js @@ -6,18 +6,11 @@ import {assert} from 'chai'; import * as Blockly from 'blockly'; +import sinon from 'sinon'; import {BlockStateIndicators} from '../src/index'; import {BlockStateIcon} from '../src/block_state_icon'; import {setBlockState} from '../src/block_state_change'; -/** - * Waits for queued events to be fired to listeners and the undo stack. - * @returns {!Promise} Resolves once events have fired. - */ -function flushEvents() { - return new Promise((resolve) => setTimeout(resolve)); -} - /** * Returns the number of glyphs a block's state icon shows, or 0 if it has no * icon. Each glyph is 16 units wide, with a 2 unit gap between them. @@ -35,11 +28,14 @@ function glyphCount(block) { // to date. suite('Block state indicators', function () { setup(function () { + this.clock = sinon.useFakeTimers(); this.workspace = new Blockly.Workspace(); }); teardown(function () { this.workspace.dispose(); + this.clock.runAll(); + this.clock.restore(); }); test('adds icons to existing restricted blocks', function () { @@ -71,7 +67,7 @@ suite('Block state indicators', function () { assert.isFalse(block.hasIcon(BlockStateIcon.TYPE)); }); - test('loaded blocks get icons', async function () { + test('loaded blocks get icons', function () { new BlockStateIndicators(this.workspace); Blockly.serialization.workspaces.load( { @@ -82,7 +78,7 @@ suite('Block state indicators', function () { }, this.workspace, ); - await flushEvents(); + this.clock.runAll(); assert.equal(glyphCount(this.workspace.getBlockById('loaded')), 1); }); @@ -132,9 +128,9 @@ suite('Block state indicators', function () { assert.isFalse(this.block.hasIcon(BlockStateIcon.TYPE)); }); - test('undo and redo update the icon', async function () { + test('undo and redo update the icon', function () { setBlockState(this.block, 'deletable', false); - await flushEvents(); + this.clock.runAll(); this.workspace.undo(false); assert.isFalse(this.block.hasIcon(BlockStateIcon.TYPE)); From 18d8a1a226ddba42bf81bee0b119ec0bdde081b3 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:20:45 -0500 Subject: [PATCH 08/10] chore: rename type and add tests --- .../src/block_state_change.ts | 93 ++--- .../src/block_state_glyphs.ts | 8 +- .../lesson-authoring/src/block_state_icon.ts | 14 +- .../lesson-authoring/src/block_state_menu.ts | 25 ++ .../src/shadow_state_change.ts | 4 +- .../test/block_state_menu.mocha.js | 353 ++++++++++++++++++ 6 files changed, 422 insertions(+), 75 deletions(-) create mode 100644 packages/plugins/lesson-authoring/test/block_state_menu.mocha.js diff --git a/packages/plugins/lesson-authoring/src/block_state_change.ts b/packages/plugins/lesson-authoring/src/block_state_change.ts index 5a4fe7c2714..3bc8cc373ff 100644 --- a/packages/plugins/lesson-authoring/src/block_state_change.ts +++ b/packages/plugins/lesson-authoring/src/block_state_change.ts @@ -14,60 +14,18 @@ import {refreshBlockStateIcon} from './block_state_icon'; const BLOCK_STATE_CHANGE = 'lesson_block_state_change'; -/** A boolean block state that core changes without firing an event. */ -type BlockStateName = 'deletable' | 'editable' | 'movable'; +/** + * Something a block allows, which core turns on and off without firing an + * event. + */ +export type BlockPermission = 'deletable' | 'editable' | 'movable'; interface BlockStateChangeJson extends Blockly.Events.BlockBaseJson { - element: BlockStateName; + element: BlockPermission; oldValue: boolean; newValue: boolean; } -/** - * Returns the value of one of a block's own boolean states. - * - * @param block The block to read. - * @param state The state to read. - * @returns The block's own value for the state. - */ -function getBlockState(block: Blockly.Block, state: BlockStateName): boolean { - switch (state) { - case 'deletable': - return block.isOwnDeletable(); - case 'editable': - return block.isOwnEditable(); - case 'movable': - return block.isOwnMovable(); - } -} - -/** - * Applies a value to one of a block's boolean states and updates the - * block's state icon. - * - * @param block The block to change. - * @param state The state to change. - * @param value The new value of the state. - */ -function applyBlockState( - block: Blockly.Block, - state: BlockStateName, - value: boolean, -) { - switch (state) { - case 'deletable': - block.setDeletable(value); - break; - case 'editable': - block.setEditable(value); - break; - case 'movable': - block.setMovable(value); - break; - } - refreshBlockStateIcon(block); -} - /** * Notifies listeners that a block's deletable, editable or movable state has * changed. @@ -76,7 +34,7 @@ class BlockStateChange extends Blockly.Events.BlockBase { override type = BLOCK_STATE_CHANGE; /** The state that changed. Undefined for a blank event. */ - element?: BlockStateName; + element?: BlockPermission; /** The value before the change. */ oldValue: boolean; @@ -92,7 +50,7 @@ class BlockStateChange extends Blockly.Events.BlockBase { */ constructor( block?: Blockly.Block, - element?: BlockStateName, + element?: BlockPermission, oldValue = false, newValue = false, ) { @@ -167,11 +125,9 @@ class BlockStateChange extends Blockly.Events.BlockBase { console.warn("Can't change state of non-existent block"); return; } - applyBlockState( - block, - this.element, - forward ? this.newValue : this.oldValue, - ); + // Fires a new event, as core's events do when run, so that listeners + // hear about undo and redo. Undo isn't recorded while undoing. + setBlockState(block, this.element, forward ? this.newValue : this.oldValue); } } @@ -182,8 +138,8 @@ Blockly.registry.register( ); /** - * Sets a block's deletable, editable or movable state, firing an event so it - * can be undone. + * Sets a block's deletable, editable or movable state and updates its state + * icon, firing an event so the change can be undone. * * @param block The block to change. * @param state The state to set. @@ -191,11 +147,24 @@ Blockly.registry.register( */ export function setBlockState( block: Blockly.Block, - state: BlockStateName, + state: BlockPermission, value: boolean, ) { - Blockly.Events.fire( - new BlockStateChange(block, state, getBlockState(block, state), value), - ); - applyBlockState(block, state, value); + let oldValue: boolean; + switch (state) { + case 'deletable': + oldValue = block.isOwnDeletable(); + block.setDeletable(value); + break; + case 'editable': + oldValue = block.isOwnEditable(); + block.setEditable(value); + break; + case 'movable': + oldValue = block.isOwnMovable(); + block.setMovable(value); + break; + } + Blockly.Events.fire(new BlockStateChange(block, state, oldValue, value)); + refreshBlockStateIcon(block); } diff --git a/packages/plugins/lesson-authoring/src/block_state_glyphs.ts b/packages/plugins/lesson-authoring/src/block_state_glyphs.ts index e78408c0064..a301e9c2d3a 100644 --- a/packages/plugins/lesson-authoring/src/block_state_glyphs.ts +++ b/packages/plugins/lesson-authoring/src/block_state_glyphs.ts @@ -10,9 +10,7 @@ */ import * as Blockly from 'blockly/core'; - -/** A state that has been turned off on a block. */ -export type Restriction = 'deletable' | 'editable' | 'movable'; +import type {BlockPermission} from './block_state_change'; /** The width and height of each glyph, in workspace-scale units. */ const GLYPH_SIZE = 16; @@ -21,7 +19,7 @@ const GLYPH_SIZE = 16; const GLYPH_GAP = 2; /** Outlines of each glyph, drawn on a 16x16 grid. */ -const GLYPH_PATHS: Record = { +const GLYPH_PATHS: Record = { deletable: 'M2.5 4.5h11M6 4.5V3h4v1.5M4 4.5l.8 9h6.4l.8-9', // Trash can with slash editable: 'M3 13l.8-3 6.7-6.7 2.2 2.2L6 12.2zM9.3 4.5l2.2 2.2', // Pencil with slash movable: 'M5.5 2.5h5M6.5 2.5v3.8L4.5 9h7l-2-2.7V2.5M8 9v4.5', // Pin @@ -64,7 +62,7 @@ export function getGlyphRowWidth(count: number): number { */ export function drawGlyphRow( parent: SVGElement, - restrictions: Restriction[], + restrictions: BlockPermission[], height: number, ) { const top = (height - GLYPH_SIZE) / 2; diff --git a/packages/plugins/lesson-authoring/src/block_state_icon.ts b/packages/plugins/lesson-authoring/src/block_state_icon.ts index ec3ebf163d2..568821f7163 100644 --- a/packages/plugins/lesson-authoring/src/block_state_icon.ts +++ b/packages/plugins/lesson-authoring/src/block_state_icon.ts @@ -10,7 +10,7 @@ import * as Blockly from 'blockly/core'; import {drawGlyphRow, getGlyphRowWidth} from './block_state_glyphs'; -import type {Restriction} from './block_state_glyphs'; +import type {BlockPermission} from './block_state_change'; import {pickContrastingColour} from './colour_contrast'; /** The size of the icon in workspace-scale units. */ @@ -24,7 +24,7 @@ const FOCUS_RING_MARGIN = 3; * written, so it can be translated without the code changing its case or * combining it into a sentence. TODO: Translate these labels. */ -const LABELS: Record = { +const LABELS: Record = { deletable: "Can't delete", editable: "Can't edit", movable: "Can't move", @@ -50,8 +50,8 @@ Blockly.Css.register(` * @param block The block to read. * @returns The restrictions to show. */ -function getRestrictions(block: Blockly.Block): Restriction[] { - const restrictions: Restriction[] = []; +function getRestrictions(block: Blockly.Block): BlockPermission[] { + const restrictions: BlockPermission[] = []; if (!block.isShadow() && !block.isOwnDeletable()) { restrictions.push('deletable'); } @@ -73,13 +73,13 @@ export class BlockStateIcon extends Blockly.icons.Icon { /** Places this icon after core's mutator, warning and comment icons. */ static readonly WEIGHT = 4; - private restrictions: Restriction[]; + private restrictions: BlockPermission[]; /** * @param sourceBlock The block this icon is attached to. * @param restrictions The restrictions to show. */ - constructor(sourceBlock: Blockly.Block, restrictions: Restriction[]) { + constructor(sourceBlock: Blockly.Block, restrictions: BlockPermission[]) { super(sourceBlock); this.restrictions = restrictions; this.updateTooltip(); @@ -146,7 +146,7 @@ export class BlockStateIcon extends Blockly.icons.Icon { * * @param restrictions The restrictions to show. */ - setRestrictions(restrictions: Restriction[]) { + setRestrictions(restrictions: BlockPermission[]) { const sizeChanged = restrictions.length !== this.restrictions.length; this.restrictions = restrictions; this.updateTooltip(); diff --git a/packages/plugins/lesson-authoring/src/block_state_menu.ts b/packages/plugins/lesson-authoring/src/block_state_menu.ts index 664ad524bc2..c4e82316d7e 100644 --- a/packages/plugins/lesson-authoring/src/block_state_menu.ts +++ b/packages/plugins/lesson-authoring/src/block_state_menu.ts @@ -494,3 +494,28 @@ export function registerLessonAuthoringContextMenuOptions() { registerMakeShadowsReal(); registerRemoveShadows(); } + +/** The IDs of every option that registerLessonAuthoringContextMenuOptions adds. */ +const MENU_ITEM_IDS = [ + 'lessonBlockDeletable', + 'lessonAllBlocksDeletable', + 'lessonBlockEditable', + 'lessonAllBlocksEditable', + 'lessonBlockMovable', + 'lessonAllBlocksMovable', + 'lessonMakeShadow', + 'lessonMakeShadowsReal', + 'lessonRemoveShadows', +]; + +/** + * Unregisters the lesson-authoring context menu options. Options that aren't + * registered are skipped, so this is safe to call more than once. + */ +export function unregisterLessonAuthoringContextMenuOptions() { + for (const id of MENU_ITEM_IDS) { + if (Blockly.ContextMenuRegistry.registry.getItem(id)) { + Blockly.ContextMenuRegistry.registry.unregister(id); + } + } +} diff --git a/packages/plugins/lesson-authoring/src/shadow_state_change.ts b/packages/plugins/lesson-authoring/src/shadow_state_change.ts index 6437c62558e..66e85498d3d 100644 --- a/packages/plugins/lesson-authoring/src/shadow_state_change.ts +++ b/packages/plugins/lesson-authoring/src/shadow_state_change.ts @@ -115,7 +115,9 @@ class ShadowStateChange extends Blockly.Events.BlockBase { console.warn("Can't set shadow state of non-existent connection"); return; } - connection.setShadowState(forward ? this.newState : this.oldState); + // Fires a new event, as core's events do when run, so that listeners + // hear about undo and redo. Undo isn't recorded while undoing. + setShadowState(connection, forward ? this.newState : this.oldState); } } diff --git a/packages/plugins/lesson-authoring/test/block_state_menu.mocha.js b/packages/plugins/lesson-authoring/test/block_state_menu.mocha.js new file mode 100644 index 00000000000..734d5fb0425 --- /dev/null +++ b/packages/plugins/lesson-authoring/test/block_state_menu.mocha.js @@ -0,0 +1,353 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +import {assert} from 'chai'; +import * as Blockly from 'blockly'; +import sinon from 'sinon'; +import { + registerLessonAuthoringContextMenuOptions, + unregisterLessonAuthoringContextMenuOptions, +} from '../src/index'; +import {setBlockState} from '../src/block_state_change'; + +/** + * Gets a registered context menu item. + * @param {string} id The item's ID. + * @returns {!Blockly.ContextMenuRegistry.RegistryItem} The item. + */ +function getItem(id) { + return Blockly.ContextMenuRegistry.registry.getItem(id); +} + +/** + * Gets an item's precondition result for a block. + * @param {string} id The item's ID. + * @param {!Blockly.Block} block The block the menu is opened on. + * @returns {string} 'enabled', 'disabled' or 'hidden'. + */ +function precondition(id, block) { + return getItem(id).preconditionFn({block}); +} + +// Event listeners and the undo stack are updated on a timer, so the tests run +// timers before reading events or undoing. +suite('Lesson authoring context menu', function () { + setup(function () { + this.clock = sinon.useFakeTimers(); + registerLessonAuthoringContextMenuOptions(); + this.workspace = new Blockly.Workspace(); + /** + * Runs an item's callback, then lets the events it fired reach the undo + * stack. + * @param {string} id The item's ID. + * @param {!Blockly.ContextMenuRegistry.Scope} scope The menu's scope. + */ + this.runItem = (id, scope) => { + getItem(id).callback(scope); + this.clock.runAll(); + }; + /** + * Loads a top-level block from its state. + * @param {!Object} state The block's state. + * @returns {!Blockly.Block} The block. + */ + this.append = (state) => { + const block = Blockly.serialization.blocks.append(state, this.workspace); + this.clock.runAll(); + // Loading isn't something to undo. + this.workspace.clearUndo(); + return block; + }; + }); + + teardown(function () { + this.workspace.dispose(); + unregisterLessonAuthoringContextMenuOptions(); + this.clock.runAll(); + this.clock.restore(); + }); + + suite('block toggles', function () { + const toggles = [ + ['lessonBlockDeletable', 'isOwnDeletable'], + ['lessonBlockEditable', 'isOwnEditable'], + ['lessonBlockMovable', 'isOwnMovable'], + ]; + for (const [id, getter] of toggles) { + test(`${id} toggles the state and can be undone`, function () { + const block = this.append({type: 'math_number'}); + this.runItem(id, {block}); + assert.isFalse(block[getter]()); + + this.workspace.undo(false); + assert.isTrue(block[getter]()); + }); + } + + test('labels describe what the toggle will do', function () { + const block = this.append({type: 'math_number'}); + const item = getItem('lessonBlockMovable'); + assert.equal(item.displayText({block}), 'Make block immovable'); + this.runItem('lessonBlockMovable', {block}); + assert.equal(item.displayText({block}), 'Make block movable'); + }); + + test('editable cascades into shadow children', function () { + const block = this.append({ + type: 'text_print', + inputs: {TEXT: {shadow: {type: 'text'}}}, + }); + const shadow = block.getInputTargetBlock('TEXT'); + this.runItem('lessonBlockEditable', {block}); + assert.isFalse(block.isOwnEditable()); + assert.isFalse(shadow.isOwnEditable()); + + // The block and its shadow undo together. + this.workspace.undo(false); + assert.isTrue(block.isOwnEditable()); + assert.isTrue(shadow.isOwnEditable()); + }); + + test('movable and deletable are hidden in a flyout, editable is not', function () { + const block = this.append({type: 'math_number'}); + block.isInFlyout = true; + assert.equal(precondition('lessonBlockMovable', block), 'hidden'); + assert.equal(precondition('lessonBlockDeletable', block), 'hidden'); + assert.equal(precondition('lessonBlockEditable', block), 'enabled'); + }); + }); + + suite('workspace toggles', function () { + setup(function () { + this.first = this.append({type: 'math_number'}); + this.second = this.append({ + type: 'text_print', + inputs: {TEXT: {shadow: {type: 'text'}}}, + }); + this.shadow = this.second.getInputTargetBlock('TEXT'); + this.scope = {workspace: this.workspace}; + }); + + test('locks every block when any is unlocked, as one undo step', function () { + setBlockState(this.first, 'movable', false); + this.clock.runAll(); + this.workspace.clearUndo(); + + const item = getItem('lessonAllBlocksMovable'); + assert.equal(item.displayText(this.scope), 'Make ALL blocks immovable'); + this.runItem('lessonAllBlocksMovable', this.scope); + assert.isFalse(this.first.isOwnMovable()); + assert.isFalse(this.second.isOwnMovable()); + + this.workspace.undo(false); + assert.isFalse(this.first.isOwnMovable(), 'was already locked'); + assert.isTrue(this.second.isOwnMovable()); + }); + + test('unlocks every block when all are locked', function () { + this.runItem('lessonAllBlocksDeletable', this.scope); + const item = getItem('lessonAllBlocksDeletable'); + assert.equal(item.displayText(this.scope), 'Make ALL blocks deletable'); + + this.runItem('lessonAllBlocksDeletable', this.scope); + assert.isTrue(this.first.isOwnDeletable()); + assert.isTrue(this.second.isOwnDeletable()); + }); + + test('movable and deletable skip shadows, editable includes them', function () { + this.runItem('lessonAllBlocksMovable', this.scope); + this.runItem('lessonAllBlocksDeletable', this.scope); + assert.isTrue(this.shadow.isOwnMovable()); + assert.isTrue(this.shadow.isOwnDeletable()); + + this.runItem('lessonAllBlocksEditable', this.scope); + assert.isFalse(this.shadow.isOwnEditable()); + }); + }); + + suite('make shadow', function () { + test('is hidden for blocks that cannot be shadows', function () { + const topLevel = this.append({type: 'math_number'}); + const withRealChild = this.append({ + type: 'text_print', + inputs: { + TEXT: { + block: { + type: 'text_length', + inputs: {VALUE: {block: {type: 'text'}}}, + }, + }, + }, + }).getInputTargetBlock('TEXT'); + const withVariable = this.append({ + type: 'text_print', + inputs: { + TEXT: {block: {type: 'variables_get', fields: {VAR: {name: 'x'}}}}, + }, + }).getInputTargetBlock('TEXT'); + + assert.equal(precondition('lessonMakeShadow', topLevel), 'hidden'); + assert.equal(precondition('lessonMakeShadow', withRealChild), 'hidden'); + assert.equal(precondition('lessonMakeShadow', withVariable), 'hidden'); + }); + + test('turns a connected block into a shadow, and can be undone', function () { + const parent = this.append({ + type: 'text_print', + inputs: {TEXT: {block: {type: 'text', fields: {TEXT: 'hi'}}}}, + }); + const block = parent.getInputTargetBlock('TEXT'); + assert.equal(precondition('lessonMakeShadow', block), 'enabled'); + + this.runItem('lessonMakeShadow', {block}); + const shadow = parent.getInputTargetBlock('TEXT'); + assert.isTrue(shadow.isShadow()); + assert.equal(shadow.getFieldValue('TEXT'), 'hi'); + + this.workspace.undo(false); + const restored = parent.getInputTargetBlock('TEXT'); + assert.isFalse(restored.isShadow()); + assert.equal(restored.getFieldValue('TEXT'), 'hi'); + assert.isNull(parent.getInput('TEXT').connection.getShadowState()); + + this.workspace.undo(true); + assert.isTrue(parent.getInputTargetBlock('TEXT').isShadow()); + }); + }); + + suite('make shadows real', function () { + test('replaces a visible shadow with a real block', function () { + const block = this.append({ + type: 'text_print', + inputs: {TEXT: {shadow: {type: 'text', fields: {TEXT: 'hi'}}}}, + }); + assert.equal( + getItem('lessonMakeShadowsReal').displayText({block}), + 'Make 1 shadow block real', + ); + + this.runItem('lessonMakeShadowsReal', {block}); + const child = block.getInputTargetBlock('TEXT'); + assert.isFalse(child.isShadow()); + assert.equal(child.getFieldValue('TEXT'), 'hi'); + assert.isNull(block.getInput('TEXT').connection.getShadowState()); + + this.workspace.undo(false); + assert.isTrue(block.getInputTargetBlock('TEXT').isShadow()); + }); + + test('unplugs a block covering the shadow', function () { + const block = this.append({ + type: 'text_print', + inputs: { + TEXT: { + shadow: {type: 'text', fields: {TEXT: 'hi'}}, + block: {type: 'text_length'}, + }, + }, + }); + const covering = block.getInputTargetBlock('TEXT'); + + this.runItem('lessonMakeShadowsReal', {block}); + assert.isNull(covering.getParent()); + const child = block.getInputTargetBlock('TEXT'); + assert.equal(child.type, 'text'); + assert.isFalse(child.isShadow()); + }); + }); + + suite('remove shadows', function () { + test('removes a visible shadow, and can be undone', function () { + const block = this.append({ + type: 'text_print', + inputs: {TEXT: {shadow: {type: 'text'}}}, + }); + + this.runItem('lessonRemoveShadows', {block}); + assert.isNull(block.getInputTargetBlock('TEXT')); + assert.isNull(block.getInput('TEXT').connection.getShadowState()); + + this.workspace.undo(false); + assert.isTrue(block.getInputTargetBlock('TEXT').isShadow()); + }); + + test('forgets a covered shadow but keeps the covering block', function () { + const block = this.append({ + type: 'text_print', + inputs: { + TEXT: {shadow: {type: 'text'}, block: {type: 'text_length'}}, + }, + }); + + this.runItem('lessonRemoveShadows', {block}); + assert.equal(block.getInputTargetBlock('TEXT').type, 'text_length'); + assert.isNull(block.getInput('TEXT').connection.getShadowState()); + }); + }); + + suite('events', function () { + setup(function () { + this.events = []; + this.workspace.addChangeListener((event) => this.events.push(event)); + }); + + test('block state changes survive a JSON round trip', function () { + const block = this.append({type: 'math_number'}); + setBlockState(block, 'movable', false); + this.clock.runAll(); + const event = this.events.find( + (e) => e.type === 'lesson_block_state_change', + ); + assert.isFalse(event.isNull()); + + const copy = Blockly.Events.fromJson(event.toJson(), this.workspace); + assert.equal(copy.blockId, block.id); + assert.equal(copy.element, 'movable'); + assert.isTrue(copy.oldValue); + assert.isFalse(copy.newValue); + }); + + test('shadow state changes survive a JSON round trip', function () { + const block = this.append({ + type: 'text_print', + inputs: {TEXT: {shadow: {type: 'text', fields: {TEXT: 'hi'}}}}, + }); + this.runItem('lessonRemoveShadows', {block}); + const event = this.events.find( + (e) => e.type === 'lesson_shadow_state_change', + ); + assert.isFalse(event.isNull()); + + const copy = Blockly.Events.fromJson(event.toJson(), this.workspace); + assert.equal(copy.blockId, block.id); + assert.equal(copy.inputName, 'TEXT'); + assert.equal(copy.oldState.fields.TEXT, 'hi'); + assert.isNull(copy.newState); + }); + + // Listeners such as autosave learn about undo and redo from the events + // that running the undone event fires. + test('undoing notifies listeners', function () { + const block = this.append({ + type: 'text_print', + inputs: { + TEXT: {shadow: {type: 'text'}, block: {type: 'text_length'}}, + }, + }); + this.runItem('lessonBlockMovable', {block}); + // The shadow is covered, so removing it creates and deletes no blocks. + this.runItem('lessonRemoveShadows', {block}); + this.events.length = 0; + + this.workspace.undo(false); + this.workspace.undo(false); + this.clock.runAll(); + const types = this.events.map((e) => e.type); + assert.include(types, 'lesson_shadow_state_change'); + assert.include(types, 'lesson_block_state_change'); + }); + }); +}); From cd5c94d18db8ebd59de079c11df1085edcc398d8 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:46:46 -0500 Subject: [PATCH 09/10] chore: use blocklyFocusRing for permissions icon --- .../plugins/lesson-authoring/src/block_state_icon.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/plugins/lesson-authoring/src/block_state_icon.ts b/packages/plugins/lesson-authoring/src/block_state_icon.ts index 568821f7163..2830492807e 100644 --- a/packages/plugins/lesson-authoring/src/block_state_icon.ts +++ b/packages/plugins/lesson-authoring/src/block_state_icon.ts @@ -36,10 +36,6 @@ Blockly.Css.register(` .blocklyIconGroup.lessonBlockStateIcon:not(:hover):not(:focus) { opacity: 1; } -.lessonBlockStateIcon > .blocklyIconShape { - fill: none; - stroke: none; -} `); /** @@ -183,13 +179,15 @@ export class BlockStateIcon extends Blockly.icons.Icon { const svgRoot = this.svgRoot; if (!svgRoot) return; svgRoot.replaceChildren(); - // Core draws an icon's focus ring on its first blocklyIconShape. This one - // is otherwise invisible, and sits just outside the glyphs. + // Core strokes a focused element's blocklyFocusRing child, as it does for + // the trashcan and zoom controls. Unfilled, so it shows only when focused, + // just outside the glyphs. const size = this.getSize(); Blockly.utils.dom.createSvgElement( Blockly.utils.Svg.RECT, { - class: 'blocklyIconShape', + class: 'blocklyFocusRing', + fill: 'none', x: -FOCUS_RING_MARGIN, y: -FOCUS_RING_MARGIN, width: size.width + 2 * FOCUS_RING_MARGIN, From 44216bcedbba476726a56c2c7741466f523cc791 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:33:55 -0500 Subject: [PATCH 10/10] chore: update comment --- packages/plugins/lesson-authoring/src/block_state_menu.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/plugins/lesson-authoring/src/block_state_menu.ts b/packages/plugins/lesson-authoring/src/block_state_menu.ts index c4e82316d7e..921c2593871 100644 --- a/packages/plugins/lesson-authoring/src/block_state_menu.ts +++ b/packages/plugins/lesson-authoring/src/block_state_menu.ts @@ -355,8 +355,6 @@ function registerMakeShadow() { if (!block || !connection) { return; } - // Without saveIds, the temporary shadow that setShadowState builds - // cannot collide with the IDs of the still-attached block. const state = Blockly.serialization.blocks.save(block, { addCoordinates: false, saveIds: false,