diff --git a/packages/blockly/core/block_svg.ts b/packages/blockly/core/block_svg.ts index 3f0bce5f80d..e7686e1c156 100644 --- a/packages/blockly/core/block_svg.ts +++ b/packages/blockly/core/block_svg.ts @@ -62,6 +62,7 @@ import type {BlockStyle} from './theme.js'; import * as Tooltip from './tooltip.js'; import {idGenerator} from './utils.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'; @@ -1017,14 +1018,45 @@ 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(); } + + // 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(); + } + } + + /** + * 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', + colour.getReadableTextColour( + background, + config.textContrast, + config.increasedTextContrast, + ), + ); } /** 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..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'; @@ -514,9 +516,20 @@ 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', + colour.getReadableTextColour( + background, + config.textContrast, + config.increasedTextContrast, + ), + ); } 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..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). @@ -263,3 +265,120 @@ 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 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 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, + 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) >= minContrast ? 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..0393ce8bccc --- /dev/null +++ b/packages/blockly/tests/mocha/block_foreground_test.ts @@ -0,0 +1,181 @@ +/** + * @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('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('disabled blocks use the disabled pattern colour', function () { + 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('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 () { + test('the dropdown text uses the dropdown colour', function () { + // The dropdown is filled with the dark tertiary colour while it's open. + const block = createBlock( + workspace, + 'logic_boolean', + 'light_with_dark_shadow', + ); + const boolField = block.getField('BOOL'); + assert.exists(boolField); + const field = boolField; + field.showEditor(); + assert.equal(getForeground(block), BLACK); + assert.equal(getForeground(field), WHITE); + }); + }); + }); +}); diff --git a/packages/blockly/tests/mocha/utils_test.ts b/packages/blockly/tests/mocha/utils_test.ts index 577853bfc50..f9cafe7ecce 100644 --- a/packages/blockly/tests/mocha/utils_test.ts +++ b/packages/blockly/tests/mocha/utils_test.ts @@ -588,6 +588,89 @@ 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'), + ); + }); + }); + + 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', + ); + }); + + test('the increased minimum never lowers the minimum', function () { + assert.equal( + Blockly.utils.colour.getReadableTextColour(MID_BLUE, 4.5, 3), + '#000000', + ); + }); + }); + }); + suite('deepMerge', function () { test('Merges two objects', function () { const target = {a: 1, b: '2', shared: 'this should be overwritten'}; 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() {