From 392a99efa50ad703b9727edbe017654a980bbe8a Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:54:55 -0500 Subject: [PATCH 1/5] feat: support minimum contrast ratios for block text --- packages/blockly/core/block_svg.ts | 53 ++++ packages/blockly/core/config.ts | 22 ++ packages/blockly/core/field_dropdown.ts | 9 +- .../core/renderers/common/constants.ts | 7 +- .../blockly/core/renderers/zelos/constants.ts | 4 +- packages/blockly/core/utils/accessibility.ts | 17 ++ packages/blockly/core/utils/colour.ts | 113 ++++++++ .../tests/mocha/block_foreground_test.ts | 258 ++++++++++++++++++ packages/blockly/tests/mocha/utils_test.ts | 80 ++++++ 9 files changed, 558 insertions(+), 5 deletions(-) create mode 100644 packages/blockly/tests/mocha/block_foreground_test.ts diff --git a/packages/blockly/core/block_svg.ts b/packages/blockly/core/block_svg.ts index 3f0bce5f80d..14efcdf1c80 100644 --- a/packages/blockly/core/block_svg.ts +++ b/packages/blockly/core/block_svg.ts @@ -61,7 +61,9 @@ import * as blocks from './serialization/blocks.js'; import type {BlockStyle} from './theme.js'; import * as Tooltip from './tooltip.js'; import {idGenerator} from './utils.js'; +import * as accessibility from './utils/accessibility.js'; import * as aria from './utils/aria.js'; +import * as colour from './utils/colour.js'; import {Coordinate} from './utils/coordinate.js'; import * as dom from './utils/dom.js'; import {Rect} from './utils/rect.js'; @@ -1025,6 +1027,57 @@ export class BlockSvg for (const field of this.getFields()) { field.applyColour(); } + + // This has to come last, because a field that fills the whole block + // repaints the block in its own applyColour. + this.updateForegroundColour(); + } + + /** + * Picks white text, or black if the block is too light for white, and sets + * it as the `--blockly-block-foreground` CSS property for the block's text + * to use. + */ + private updateForegroundColour() { + let background; + if (!this.isEnabled() || this.getInheritedDisabled()) { + // CSS draws the disabled pattern over the fill set on the path. + background = this.workspace + .getRenderer() + .getConstants().DISABLED_PATTERN_COLOUR; + } else { + // Read back the fill rather than the style, because a field that fills + // the whole block repaints the block in its own colour. + background = + colour.parse(this.pathObject.svgPath.getAttribute('fill') ?? '') ?? + this.getColour(); + } + this.svgGroup.style.setProperty( + '--blockly-block-foreground', + this.getTextColour(background), + ); + } + + /** + * Returns the colour for text drawn on this block over the given + * background: white, or black if white would have less contrast than + * `config.textContrast`, or than `config.increasedTextContrast` for users + * who prefer more contrast. + * + * @param background The colour behind the text. + * @param increased Whether the user prefers more contrast. Defaults to their + * operating system setting. + * @returns White ('#ffffff') or black ('#000000'). + * @internal + */ + getTextColour( + background: string, + increased = accessibility.shouldIncreaseContrast(), + ): string { + const minWhiteContrast = increased + ? Math.max(config.textContrast, config.increasedTextContrast) + : config.textContrast; + return colour.getReadableTextColour(background, minWhiteContrast); } /** diff --git a/packages/blockly/core/config.ts b/packages/blockly/core/config.ts index e835dfa762f..ef2dca2c21f 100644 --- a/packages/blockly/core/config.ts +++ b/packages/blockly/core/config.ts @@ -17,6 +17,8 @@ interface Config { currentConnectionPreference: number; bumpDelay: number; connectingSnapRadius: number; + textContrast: number; + increasedTextContrast: number; } /** Default snap radius. */ @@ -65,4 +67,24 @@ export const config = { * */ bumpDelay: 250, + /** + * The lowest contrast ratio at which text on a block stays white. On blocks + * where white text would have less contrast than this, the text is black. + * + * The default of 1 keeps text white on every block. WCAG asks for at least + * 3 for large text and graphics, and 4.5 for normal text. Raising this + * makes text easier to read on light blocks, but changes the text colour + * on more of the default block colours. + * + * Users who ask their operating system for more contrast get at least + * `increasedTextContrast`. + */ + textContrast: 1, + /** + * The lowest contrast ratio at which text on a block stays white, for users + * who ask their operating system for more contrast. + * + * The default of 4.5 is the WCAG minimum for normal text. + */ + increasedTextContrast: 4.5, } satisfies Config; diff --git a/packages/blockly/core/field_dropdown.ts b/packages/blockly/core/field_dropdown.ts index c3914c00026..d805e5dc45d 100644 --- a/packages/blockly/core/field_dropdown.ts +++ b/packages/blockly/core/field_dropdown.ts @@ -514,9 +514,16 @@ export class FieldDropdown extends Field { if (this.borderRect_) { this.borderRect_.setAttribute('stroke', sourceBlock.getColourTertiary()); if (this.menu_) { - this.borderRect_.setAttribute('fill', sourceBlock.getColourTertiary()); + const background = sourceBlock.getColourTertiary(); + this.borderRect_.setAttribute('fill', background); + // The text sits on this rect, not the block, while the menu is open. + this.fieldGroup_?.style.setProperty( + '--blockly-block-foreground', + sourceBlock.getTextColour(background), + ); } else { this.borderRect_.setAttribute('fill', 'transparent'); + this.fieldGroup_?.style.removeProperty('--blockly-block-foreground'); } } // Update arrow's colour. diff --git a/packages/blockly/core/renderers/common/constants.ts b/packages/blockly/core/renderers/common/constants.ts index d824886c6a8..4532304633a 100644 --- a/packages/blockly/core/renderers/common/constants.ts +++ b/packages/blockly/core/renderers/common/constants.ts @@ -317,6 +317,9 @@ export class ConstantProvider { */ disabledPatternId = ''; + /** The background colour of the pattern drawn over disabled blocks. */ + DISABLED_PATTERN_COLOUR = '#aaa'; + /** * The element to use for disabled blocks, or null if not set. */ @@ -1035,7 +1038,7 @@ export class ConstantProvider { ); dom.createSvgElement( Svg.RECT, - {'width': 10, 'height': 10, 'fill': '#aaa'}, + {'width': 10, 'height': 10, 'fill': this.DISABLED_PATTERN_COLOUR}, disabledPattern, ); dom.createSvgElement( @@ -1173,7 +1176,7 @@ export class ConstantProvider { // Fields. `${selector} .blocklyText {`, - `fill: #fff;`, + `fill: var(--blockly-block-foreground, #fff);`, `}`, `${selector} .blocklyNonEditableField>rect,`, `${selector} .blocklyEditableField>rect {`, diff --git a/packages/blockly/core/renderers/zelos/constants.ts b/packages/blockly/core/renderers/zelos/constants.ts index b0bf264f91e..a5660143658 100644 --- a/packages/blockly/core/renderers/zelos/constants.ts +++ b/packages/blockly/core/renderers/zelos/constants.ts @@ -735,7 +735,7 @@ export class ConstantProvider extends BaseConstantProvider { // Fields. `${selector} .blocklyText {`, - `fill: #fff;`, + `fill: var(--blockly-block-foreground, #fff);`, `}`, `${selector} .blocklyNonEditableField>rect:not(.blocklyDropdownRect),`, `${selector} .blocklyEditableField>rect:not(.blocklyDropdownRect) {`, @@ -776,7 +776,7 @@ export class ConstantProvider extends BaseConstantProvider { // Dropdown field. `${selector} .blocklyDropdownText {`, - `fill: #fff !important;`, + `fill: var(--blockly-block-foreground, #fff) !important;`, `}`, // Widget and Dropdown Div diff --git a/packages/blockly/core/utils/accessibility.ts b/packages/blockly/core/utils/accessibility.ts index aaa3f822075..cd035ab6b5e 100644 --- a/packages/blockly/core/utils/accessibility.ts +++ b/packages/blockly/core/utils/accessibility.ts @@ -21,3 +21,20 @@ export function shouldReduceMotion(): boolean { } return reduceMotion.matches; } + +let increaseContrast: MediaQueryList | undefined = undefined; + +/** + * Returns true if the user has asked their operating system for more contrast. + */ +export function shouldIncreaseContrast(): boolean { + if (increaseContrast === undefined) { + if (typeof window === 'undefined' || !('matchMedia' in window)) { + // Nothing is drawn if there's no window, i.e. we're running under Node. + return false; + } + + increaseContrast = window.matchMedia('(prefers-contrast: more)'); + } + return increaseContrast.matches; +} diff --git a/packages/blockly/core/utils/colour.ts b/packages/blockly/core/utils/colour.ts index a36191e9001..4fb2de6a2fd 100644 --- a/packages/blockly/core/utils/colour.ts +++ b/packages/blockly/core/utils/colour.ts @@ -263,3 +263,116 @@ export const names: {[key: string]: string} = { export function hueToHex(hue: number): string { return hsvToHex(hue, hsvSaturation, hsvValue * 255); } + +// 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 largest value of a red, green or blue channel. */ +const MAX_CHANNEL_VALUE = 255; + +/** + * 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 / MAX_CHANNEL_VALUE; + 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 colour Colour in any format `parse` accepts ('#ff0000', 'red', etc). + * @returns The relative luminance, from 0 for black to 1 for white. + * @throws If the colour can't be parsed. + * @internal + */ +export function getLuminance(colour: string): number { + const hex = parse(colour); + if (!hex) { + throw new Error(`Can't get the luminance of invalid colour "${colour}".`); + } + const [red, green, blue] = 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. WCAG asks + * for at least 4.5 for normal text and 3 for graphics. + * + * @param colour1 Colour in any format `parse` accepts. The order of the two + * colours doesn't matter. + * @param colour2 Colour in any format `parse` accepts. + * @returns The contrast ratio, from 1 for identical colours to 21 for black + * and white. + * @throws If either colour can't be parsed. + * @internal + */ +export function getContrastRatio(colour1: string, colour2: string): number { + const luminance1 = getLuminance(colour1); + const luminance2 = getLuminance(colour2); + const lighter = Math.max(luminance1, luminance2); + const darker = Math.min(luminance1, luminance2); + return (lighter + SCREEN_FLARE) / (darker + SCREEN_FLARE); +} + +/** + * Gets the colour for text drawn on a background: white, or black if white + * would have less contrast than the given minimum. + * + * @param background Colour in any format `parse` accepts. + * @param minWhiteContrast The lowest contrast ratio at which the text stays + * white. WCAG asks for at least 4.5 for normal text and 3 for large text + * and graphics. + * @returns White ('#ffffff') or black ('#000000'). + * @throws If the background can't be parsed. + * @internal + */ +export function getReadableTextColour( + background: string, + minWhiteContrast: number, +): string { + const white = names['white']; + const black = names['black']; + return getContrastRatio(background, white) >= minWhiteContrast + ? white + : black; +} diff --git a/packages/blockly/tests/mocha/block_foreground_test.ts b/packages/blockly/tests/mocha/block_foreground_test.ts new file mode 100644 index 00000000000..e0865372a87 --- /dev/null +++ b/packages/blockly/tests/mocha/block_foreground_test.ts @@ -0,0 +1,258 @@ +/** + * @license + * Copyright 2026 Raspberry Pi Foundation + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as Blockly from '#core/blockly.js'; +import {assert} from 'chai'; +import { + sharedTestSetup, + sharedTestTeardown, +} from './test_helpers/setup_teardown.js'; + +const BLACK = '#000000'; +const WHITE = '#ffffff'; +const LIGHT_GRAY = '#eeeeee'; +const DARK_GRAY = '#333333'; + +/** + * Block styles for the tests. Shadow blocks are painted in the secondary + * colour, so some styles pair a light block with a dark shadow and the other + * way around. + */ +const TEST_THEME = new Blockly.Theme('block_foreground_test', { + 'dark': { + 'colourPrimary': DARK_GRAY, + 'colourSecondary': DARK_GRAY, + 'colourTertiary': DARK_GRAY, + }, + 'light': { + 'colourPrimary': LIGHT_GRAY, + 'colourSecondary': LIGHT_GRAY, + 'colourTertiary': LIGHT_GRAY, + }, + 'light_with_dark_shadow': { + 'colourPrimary': LIGHT_GRAY, + 'colourSecondary': DARK_GRAY, + 'colourTertiary': DARK_GRAY, + }, + 'dark_with_light_shadow': { + 'colourPrimary': DARK_GRAY, + 'colourSecondary': LIGHT_GRAY, + 'colourTertiary': DARK_GRAY, + }, +}); + +/** + * Creates a rendered block of the given type and style. + * + * @param workspace The workspace to create the block on. + * @param type The block type. + * @param style The name of a block style in `TEST_THEME`. + * @returns The new block. + */ +function createBlock( + workspace: Blockly.WorkspaceSvg, + type: string, + style: string, +): Blockly.BlockSvg { + const block = workspace.newBlock(type); + block.setStyle(style); + block.initSvg(); + block.render(); + return block; +} + +/** + * Returns the colour a block or field's text is drawn in. + * + * @param owner The block or field to read. + * @returns The value of the `--blockly-block-foreground` property on the + * owner's SVG root. + */ +function getForeground( + owner: Blockly.BlockSvg | Blockly.Field, +): string | undefined { + return owner + .getSvgRoot() + ?.style.getPropertyValue('--blockly-block-foreground'); +} + +suite('Block foreground colour', function () { + let workspace: Blockly.WorkspaceSvg; + const defaultConfig = {...Blockly.config}; + + setup(function (this: Mocha.Context) { + sharedTestSetup.call(this); + // Use the WCAG minimum for large text, so that light blocks get black + // text. Lowering the minimum for users who prefer more contrast means the + // tests give the same results whatever the machine running them is set to. + Blockly.config.textContrast = 3; + Blockly.config.increasedTextContrast = 1; + }); + + teardown(function (this: Mocha.Context) { + sharedTestTeardown.call(this, workspace); + Object.assign(Blockly.config, defaultConfig); + }); + + suite('getTextColour', function () { + let block: Blockly.BlockSvg; + + setup(function () { + workspace = Blockly.inject('blocklyDiv', {theme: TEST_THEME}); + block = createBlock(workspace, 'text_print', 'dark'); + Object.assign(Blockly.config, defaultConfig); + }); + + test('by default, text is always white', function () { + assert.equal(block.getTextColour(LIGHT_GRAY, false), WHITE); + }); + + test('by default, users who prefer more contrast get at least 4.5', function () { + // The default logic block colour. White has a contrast of 4.1 on it. + assert.equal(block.getTextColour('#5b80a5', true), BLACK); + }); + + test('the minimum for users who prefer more contrast can be changed', function () { + Blockly.config.increasedTextContrast = 3; + assert.equal(block.getTextColour('#5b80a5', true), WHITE); + }); + + test('preferring more contrast does not lower a higher setting', function () { + Blockly.config.textContrast = 7; + // The default math block colour. White has a contrast of 5.4 on it. + assert.equal(block.getTextColour('#5b67a5', true), BLACK); + }); + }); + + suite('Thrasos', function () { + setup(function () { + workspace = Blockly.inject('blocklyDiv', { + renderer: 'thrasos', + theme: TEST_THEME, + }); + }); + + test('dark blocks get white text', function () { + const block = createBlock(workspace, 'text_print', 'dark'); + assert.equal(getForeground(block), WHITE); + }); + + test('light blocks get black text', function () { + const block = createBlock(workspace, 'text_print', 'light'); + assert.equal(getForeground(block), BLACK); + }); + + test('mid-tone blocks keep white text', function () { + // The default logic block colour. White has a contrast of 4.1 on it. + const block = createBlock(workspace, 'text_print', 'dark'); + block.setColour('#5b80a5'); + assert.equal(getForeground(block), WHITE); + }); + + test('blocks where white is below 3:1 get black text', function () { + // The default text block colour. White has a contrast of 2.9 on it. + const block = createBlock(workspace, 'text_print', 'dark'); + block.setColour('#5ba58c'); + assert.equal(getForeground(block), BLACK); + }); + + test('changing the colour updates the text colour', function () { + const block = createBlock(workspace, 'text_print', 'dark'); + block.setColour(LIGHT_GRAY); + assert.equal(getForeground(block), BLACK); + }); + + test('shadow blocks use the shadow colour', function () { + const block = createBlock( + workspace, + 'math_number', + 'light_with_dark_shadow', + ); + block.setShadow(true); + assert.equal(getForeground(block), WHITE); + }); + + test('changing the theme updates the text colour', function () { + const block = createBlock(workspace, 'text_print', 'dark'); + // A theme that redefines the block's 'dark' style as light. + const newTheme = new Blockly.Theme('new_theme', { + 'dark': { + 'colourPrimary': LIGHT_GRAY, + 'colourSecondary': LIGHT_GRAY, + 'colourTertiary': LIGHT_GRAY, + }, + }); + workspace.setTheme(newTheme); + assert.equal(getForeground(block), BLACK); + }); + + test('disabled blocks use the disabled pattern colour', function () { + // White has a contrast of 2.3 on the disabled pattern. + const block = createBlock(workspace, 'text_print', 'dark'); + block.setDisabledReason(true, 'test'); + assert.equal(getForeground(block), BLACK); + }); + + test('re-enabled blocks use the block colour again', function () { + const block = createBlock(workspace, 'text_print', 'dark'); + block.setDisabledReason(true, 'test'); + block.setDisabledReason(false, 'test'); + assert.equal(getForeground(block), WHITE); + }); + }); + + suite('Zelos', function () { + setup(function () { + workspace = Blockly.inject('blocklyDiv', { + renderer: 'zelos', + theme: TEST_THEME, + }); + }); + + test('number blocks get black text, because the field paints the block white', function () { + const block = createBlock(workspace, 'math_number', 'dark'); + assert.equal(getForeground(block), BLACK); + }); + + test('dropdown shadows use the shadow colour', function () { + const block = createBlock( + workspace, + 'logic_boolean', + 'dark_with_light_shadow', + ); + block.setShadow(true); + assert.equal(getForeground(block), BLACK); + }); + + suite('Open dropdown', function () { + let block: Blockly.BlockSvg; + let field: Blockly.Field; + + setup(function () { + // The dropdown is filled with the dark tertiary colour while it's open. + block = createBlock( + workspace, + 'logic_boolean', + 'light_with_dark_shadow', + ); + const boolField = block.getField('BOOL'); + assert.exists(boolField); + field = boolField; + field.showEditor(); + }); + + test('the dropdown text uses the dropdown colour', function () { + assert.equal(getForeground(block), BLACK); + assert.equal(getForeground(field), WHITE); + }); + + test('closing the dropdown goes back to the block colour', function () { + workspace.hideChaff(); + assert.equal(getForeground(field), ''); + }); + }); + }); +}); diff --git a/packages/blockly/tests/mocha/utils_test.ts b/packages/blockly/tests/mocha/utils_test.ts index 3605b8af741..a873749588d 100644 --- a/packages/blockly/tests/mocha/utils_test.ts +++ b/packages/blockly/tests/mocha/utils_test.ts @@ -584,6 +584,86 @@ suite('Utils', function () { }); }); + suite('Colour', function () { + suite('getLuminance', function () { + test('black is 0', function () { + assert.equal(Blockly.utils.colour.getLuminance('#000000'), 0); + }); + + test('white is 1', function () { + assert.equal(Blockly.utils.colour.getLuminance('#ffffff'), 1); + }); + + test('mid gray is about 0.184', function () { + assert.closeTo( + Blockly.utils.colour.getLuminance('#777777'), + 0.184, + 0.001, + ); + }); + + test('accepts named colours and short hex', function () { + assert.equal( + Blockly.utils.colour.getLuminance('red'), + Blockly.utils.colour.getLuminance('#f00'), + ); + }); + + test('throws for an invalid colour', function () { + assert.throws(() => Blockly.utils.colour.getLuminance('not a colour')); + }); + }); + + suite('getContrastRatio', function () { + test('black and white is 21', function () { + assert.equal( + Blockly.utils.colour.getContrastRatio('#000000', '#ffffff'), + 21, + ); + }); + + test('a colour against itself is 1', function () { + assert.equal( + Blockly.utils.colour.getContrastRatio('#5b80a5', '#5b80a5'), + 1, + ); + }); + + test('the order of the colours does not matter', function () { + assert.equal( + Blockly.utils.colour.getContrastRatio('#5b80a5', '#ffffff'), + Blockly.utils.colour.getContrastRatio('#ffffff', '#5b80a5'), + ); + }); + }); + + suite('getReadableTextColour', function () { + // White has a contrast of 4.1 on this blue. + const MID_BLUE = '#5b80a5'; + + test('white when it meets the minimum', function () { + assert.equal( + Blockly.utils.colour.getReadableTextColour(MID_BLUE, 3), + '#ffffff', + ); + }); + + test('black when white is below the minimum', function () { + assert.equal( + Blockly.utils.colour.getReadableTextColour(MID_BLUE, 4.5), + '#000000', + ); + }); + + test('a minimum of 1 always gives white', function () { + assert.equal( + Blockly.utils.colour.getReadableTextColour('#ffffff', 1), + '#ffffff', + ); + }); + }); + }); + suite('deepMerge', function () { test('Merges two objects', function () { const target = {a: 1, b: '2', shared: 'this should be overwritten'}; From facca22146f487e80974bfa93f1355733fe23eec Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:24:08 -0500 Subject: [PATCH 2/5] fix: apply icon colour later too --- packages/blockly/core/block_svg.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/blockly/core/block_svg.ts b/packages/blockly/core/block_svg.ts index 14efcdf1c80..17d3cd19beb 100644 --- a/packages/blockly/core/block_svg.ts +++ b/packages/blockly/core/block_svg.ts @@ -1019,18 +1019,16 @@ export class BlockSvg applyColour() { this.pathObject.applyColour?.(this); - const icons = this.getIcons(); - for (let i = 0; i < icons.length; i++) { - icons[i].applyColour(); - } - for (const field of this.getFields()) { field.applyColour(); } - // This has to come last, because a field that fills the whole block - // repaints the block in its own applyColour. + // These have to come after the fields, because a field that fills the + // whole block repaints the block in its own applyColour. this.updateForegroundColour(); + for (const icon of this.getIcons()) { + icon.applyColour(); + } } /** From dfd1378e96cc69d4b199ea2443aeac3430a130ec Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:26:15 -0500 Subject: [PATCH 3/5] chore: move getReadableTextColour to utils --- packages/blockly/core/block_svg.ts | 29 ++++-------------- packages/blockly/core/field_dropdown.ts | 8 ++++- packages/blockly/core/utils/colour.ts | 22 +++++++++----- .../tests/mocha/block_foreground_test.ts | 30 ------------------- packages/blockly/tests/mocha/utils_test.ts | 11 ++++--- 5 files changed, 33 insertions(+), 67 deletions(-) diff --git a/packages/blockly/core/block_svg.ts b/packages/blockly/core/block_svg.ts index 17d3cd19beb..e7686e1c156 100644 --- a/packages/blockly/core/block_svg.ts +++ b/packages/blockly/core/block_svg.ts @@ -61,7 +61,6 @@ import * as blocks from './serialization/blocks.js'; import type {BlockStyle} from './theme.js'; import * as Tooltip from './tooltip.js'; import {idGenerator} from './utils.js'; -import * as accessibility from './utils/accessibility.js'; import * as aria from './utils/aria.js'; import * as colour from './utils/colour.js'; import {Coordinate} from './utils/coordinate.js'; @@ -1052,32 +1051,14 @@ export class BlockSvg } this.svgGroup.style.setProperty( '--blockly-block-foreground', - this.getTextColour(background), + colour.getReadableTextColour( + background, + config.textContrast, + config.increasedTextContrast, + ), ); } - /** - * Returns the colour for text drawn on this block over the given - * background: white, or black if white would have less contrast than - * `config.textContrast`, or than `config.increasedTextContrast` for users - * who prefer more contrast. - * - * @param background The colour behind the text. - * @param increased Whether the user prefers more contrast. Defaults to their - * operating system setting. - * @returns White ('#ffffff') or black ('#000000'). - * @internal - */ - getTextColour( - background: string, - increased = accessibility.shouldIncreaseContrast(), - ): string { - const minWhiteContrast = increased - ? Math.max(config.textContrast, config.increasedTextContrast) - : config.textContrast; - return colour.getReadableTextColour(background, minWhiteContrast); - } - /** * Updates the colour of the block (and children) to match the current * disabled state. diff --git a/packages/blockly/core/field_dropdown.ts b/packages/blockly/core/field_dropdown.ts index d805e5dc45d..5ae278f6139 100644 --- a/packages/blockly/core/field_dropdown.ts +++ b/packages/blockly/core/field_dropdown.ts @@ -14,6 +14,7 @@ // Former goog.module ID: Blockly.FieldDropdown import type {BlockSvg} from './block_svg.js'; +import {config} from './config.js'; import * as dropDownDiv from './dropdowndiv.js'; import type {FieldConfig, FieldValidator} from './field.js'; import {Field, UnattachedFieldError} from './field.js'; @@ -23,6 +24,7 @@ import {MenuSeparator} from './menu_separator.js'; import {MenuItem} from './menuitem.js'; import {Msg} from './msg.js'; import * as aria from './utils/aria.js'; +import * as colour from './utils/colour.js'; import {Coordinate} from './utils/coordinate.js'; import * as dom from './utils/dom.js'; import * as parsing from './utils/parsing.js'; @@ -519,7 +521,11 @@ export class FieldDropdown extends Field { // The text sits on this rect, not the block, while the menu is open. this.fieldGroup_?.style.setProperty( '--blockly-block-foreground', - sourceBlock.getTextColour(background), + colour.getReadableTextColour( + background, + config.textContrast, + config.increasedTextContrast, + ), ); } else { this.borderRect_.setAttribute('fill', 'transparent'); diff --git a/packages/blockly/core/utils/colour.ts b/packages/blockly/core/utils/colour.ts index 4fb2de6a2fd..5f04a509a81 100644 --- a/packages/blockly/core/utils/colour.ts +++ b/packages/blockly/core/utils/colour.ts @@ -6,6 +6,8 @@ // Former goog.module ID: Blockly.utils.colour +import * as accessibility from './accessibility.js'; + /** * The richness of block colours, regardless of the hue. * Must be in the range of 0 (inclusive) to 1 (exclusive). @@ -356,23 +358,27 @@ export function getContrastRatio(colour1: string, colour2: string): number { /** * Gets the colour for text drawn on a background: white, or black if white - * would have less contrast than the given minimum. + * would have less contrast than the minimum. WCAG asks for at least 4.5 for + * normal text and 3 for large text and graphics. * * @param background Colour in any format `parse` accepts. - * @param minWhiteContrast The lowest contrast ratio at which the text stays - * white. WCAG asks for at least 4.5 for normal text and 3 for large text - * and graphics. + * @param contrast The lowest contrast ratio at which the text stays white. + * @param increasedContrast The lowest contrast ratio at which the text stays + * white for users who ask their operating system for more contrast. It + * never lowers `contrast`. * @returns White ('#ffffff') or black ('#000000'). * @throws If the background can't be parsed. * @internal */ export function getReadableTextColour( background: string, - minWhiteContrast: number, + contrast: number, + increasedContrast = contrast, ): string { + const minContrast = accessibility.shouldIncreaseContrast() + ? Math.max(contrast, increasedContrast) + : contrast; const white = names['white']; const black = names['black']; - return getContrastRatio(background, white) >= minWhiteContrast - ? white - : black; + return getContrastRatio(background, white) >= minContrast ? white : black; } diff --git a/packages/blockly/tests/mocha/block_foreground_test.ts b/packages/blockly/tests/mocha/block_foreground_test.ts index e0865372a87..2605ca4e2a5 100644 --- a/packages/blockly/tests/mocha/block_foreground_test.ts +++ b/packages/blockly/tests/mocha/block_foreground_test.ts @@ -97,36 +97,6 @@ suite('Block foreground colour', function () { Object.assign(Blockly.config, defaultConfig); }); - suite('getTextColour', function () { - let block: Blockly.BlockSvg; - - setup(function () { - workspace = Blockly.inject('blocklyDiv', {theme: TEST_THEME}); - block = createBlock(workspace, 'text_print', 'dark'); - Object.assign(Blockly.config, defaultConfig); - }); - - test('by default, text is always white', function () { - assert.equal(block.getTextColour(LIGHT_GRAY, false), WHITE); - }); - - test('by default, users who prefer more contrast get at least 4.5', function () { - // The default logic block colour. White has a contrast of 4.1 on it. - assert.equal(block.getTextColour('#5b80a5', true), BLACK); - }); - - test('the minimum for users who prefer more contrast can be changed', function () { - Blockly.config.increasedTextContrast = 3; - assert.equal(block.getTextColour('#5b80a5', true), WHITE); - }); - - test('preferring more contrast does not lower a higher setting', function () { - Blockly.config.textContrast = 7; - // The default math block colour. White has a contrast of 5.4 on it. - assert.equal(block.getTextColour('#5b67a5', true), BLACK); - }); - }); - suite('Thrasos', function () { setup(function () { workspace = Blockly.inject('blocklyDiv', { diff --git a/packages/blockly/tests/mocha/utils_test.ts b/packages/blockly/tests/mocha/utils_test.ts index a873749588d..c7ccbac9ce6 100644 --- a/packages/blockly/tests/mocha/utils_test.ts +++ b/packages/blockly/tests/mocha/utils_test.ts @@ -608,10 +608,6 @@ suite('Utils', function () { Blockly.utils.colour.getLuminance('#f00'), ); }); - - test('throws for an invalid colour', function () { - assert.throws(() => Blockly.utils.colour.getLuminance('not a colour')); - }); }); suite('getContrastRatio', function () { @@ -661,6 +657,13 @@ suite('Utils', function () { '#ffffff', ); }); + + test('the increased minimum never lowers the minimum', function () { + assert.equal( + Blockly.utils.colour.getReadableTextColour(MID_BLUE, 4.5, 3), + '#000000', + ); + }); }); }); From 949afee4a9e9ddef64f0936fa9e6b8f7db7a8b0e Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:23:35 -0500 Subject: [PATCH 4/5] feat: add contrast sliders to Advanced Playground --- .../tests/playgrounds/advanced_playground.html | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/blockly/tests/playgrounds/advanced_playground.html b/packages/blockly/tests/playgrounds/advanced_playground.html index afe59a1b78c..49a193f8126 100644 --- a/packages/blockly/tests/playgrounds/advanced_playground.html +++ b/packages/blockly/tests/playgrounds/advanced_playground.html @@ -49,6 +49,18 @@ // Refresh theme. ws.setTheme(ws.getTheme()); }); + + // Minimum contrast for white block text. + var contrastFolder = gui.addFolder('Contrast'); + for (const key of ['textContrast', 'increasedTextContrast']) { + contrastFolder + .add(Blockly.config, key, 1, 21, 0.1) + .onChange(function () { + var ws = playground.getWorkspace(); + // Refresh theme and recolour all blocks. + ws.setTheme(ws.getTheme()); + }); + } } function initPlayground() { From 3c13d6cbcd53df233fac8cc8f6dfdeec8b1ac704 Mon Sep 17 00:00:00 2001 From: Mike Harvey <43474485+mikeharv@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:29:01 -0500 Subject: [PATCH 5/5] chore: remove some silly tests --- .../tests/mocha/block_foreground_test.ts | 53 ++----------------- 1 file changed, 3 insertions(+), 50 deletions(-) diff --git a/packages/blockly/tests/mocha/block_foreground_test.ts b/packages/blockly/tests/mocha/block_foreground_test.ts index 2605ca4e2a5..0393ce8bccc 100644 --- a/packages/blockly/tests/mocha/block_foreground_test.ts +++ b/packages/blockly/tests/mocha/block_foreground_test.ts @@ -129,38 +129,7 @@ suite('Block foreground colour', function () { assert.equal(getForeground(block), BLACK); }); - test('changing the colour updates the text colour', function () { - const block = createBlock(workspace, 'text_print', 'dark'); - block.setColour(LIGHT_GRAY); - assert.equal(getForeground(block), BLACK); - }); - - test('shadow blocks use the shadow colour', function () { - const block = createBlock( - workspace, - 'math_number', - 'light_with_dark_shadow', - ); - block.setShadow(true); - assert.equal(getForeground(block), WHITE); - }); - - test('changing the theme updates the text colour', function () { - const block = createBlock(workspace, 'text_print', 'dark'); - // A theme that redefines the block's 'dark' style as light. - const newTheme = new Blockly.Theme('new_theme', { - 'dark': { - 'colourPrimary': LIGHT_GRAY, - 'colourSecondary': LIGHT_GRAY, - 'colourTertiary': LIGHT_GRAY, - }, - }); - workspace.setTheme(newTheme); - assert.equal(getForeground(block), BLACK); - }); - test('disabled blocks use the disabled pattern colour', function () { - // White has a contrast of 2.3 on the disabled pattern. const block = createBlock(workspace, 'text_print', 'dark'); block.setDisabledReason(true, 'test'); assert.equal(getForeground(block), BLACK); @@ -182,11 +151,6 @@ suite('Block foreground colour', function () { }); }); - test('number blocks get black text, because the field paints the block white', function () { - const block = createBlock(workspace, 'math_number', 'dark'); - assert.equal(getForeground(block), BLACK); - }); - test('dropdown shadows use the shadow colour', function () { const block = createBlock( workspace, @@ -198,31 +162,20 @@ suite('Block foreground colour', function () { }); suite('Open dropdown', function () { - let block: Blockly.BlockSvg; - let field: Blockly.Field; - - setup(function () { + test('the dropdown text uses the dropdown colour', function () { // The dropdown is filled with the dark tertiary colour while it's open. - block = createBlock( + const block = createBlock( workspace, 'logic_boolean', 'light_with_dark_shadow', ); const boolField = block.getField('BOOL'); assert.exists(boolField); - field = boolField; + const field = boolField; field.showEditor(); - }); - - test('the dropdown text uses the dropdown colour', function () { assert.equal(getForeground(block), BLACK); assert.equal(getForeground(field), WHITE); }); - - test('closing the dropdown goes back to the block colour', function () { - workspace.hideChaff(); - assert.equal(getForeground(field), ''); - }); }); }); });