Skip to content
Draft
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
9 changes: 9 additions & 0 deletions src/collaboration/awareness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,15 @@ export function renderCollaborationSelection(

/** Select black or white text using the WCAG relative-luminance threshold. */
export function contrastingTextColor(hexColor: string): '#000000' | '#ffffff' {
if (
typeof hexColor !== 'string' ||
!CURSOR_COLOR_PATTERN.test(hexColor)
) {
throw new RangeError(
'collaboration contrast color must be a six-digit hexadecimal color',
);
}

const red = Number.parseInt(hexColor.slice(1, 3), 16) / 255;
const green = Number.parseInt(hexColor.slice(3, 5), 16) / 255;
const blue = Number.parseInt(hexColor.slice(5, 7), 16) / 255;
Expand Down
29 changes: 29 additions & 0 deletions src/collaboration/awarenessContrastColor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';
import { contrastingTextColor } from './awareness.js';

const INVALID_CONTRAST_COLOR_ERROR = new RangeError(
'collaboration contrast color must be a six-digit hexadecimal color',
);

describe('public collaboration contrast-color contract', () => {
it.each(['#fff', '#zzzzzz', 'red', ''])(
'rejects malformed color token %j instead of returning a plausible contrast',
(color) => {
expect(() => contrastingTextColor(color)).toThrowError(
INVALID_CONTRAST_COLOR_ERROR,
);
},
);

it('rejects non-string runtime input without coercion', () => {
expect(() => contrastingTextColor(7 as never)).toThrowError(
INVALID_CONTRAST_COLOR_ERROR,
);
});

it('preserves valid uppercase and lowercase six-digit colors', () => {
expect(contrastingTextColor('#FFFFFF')).toBe('#000000');
expect(contrastingTextColor('#000000')).toBe('#ffffff');
expect(contrastingTextColor('#777777')).toBe('#000000');
});
});
Loading