Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 37 additions & 5 deletions packages/blockly/core/block_svg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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,
),
);
}

/**
Expand Down
22 changes: 22 additions & 0 deletions packages/blockly/core/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ interface Config {
currentConnectionPreference: number;
bumpDelay: number;
connectingSnapRadius: number;
textContrast: number;
increasedTextContrast: number;
}

/** Default snap radius. */
Expand Down Expand Up @@ -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;
15 changes: 14 additions & 1 deletion packages/blockly/core/field_dropdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -514,9 +516,20 @@ export class FieldDropdown extends Field<string> {
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.
Expand Down
7 changes: 5 additions & 2 deletions packages/blockly/core/renderers/common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,9 @@ export class ConstantProvider {
*/
disabledPatternId = '';

/** The background colour of the pattern drawn over disabled blocks. */
DISABLED_PATTERN_COLOUR = '#aaa';

/**
* The <pattern> element to use for disabled blocks, or null if not set.
*/
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -1173,7 +1176,7 @@ export class ConstantProvider {

// Fields.
`${selector} .blocklyText {`,
`fill: #fff;`,
`fill: var(--blockly-block-foreground, #fff);`,
`}`,
`${selector} .blocklyNonEditableField>rect,`,
`${selector} .blocklyEditableField>rect {`,
Expand Down
4 changes: 2 additions & 2 deletions packages/blockly/core/renderers/zelos/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {`,
Expand Down Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions packages/blockly/core/utils/accessibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
119 changes: 119 additions & 0 deletions packages/blockly/core/utils/colour.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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;
}
Loading
Loading