Skip to content

Commit 6418d47

Browse files
authored
fix: switch foreground color based on selected user color dynamically #1785 (#1787)
1 parent 545d3af commit 6418d47

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

packages/core/src/extensions/Collaboration/CursorPlugin.ts

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,27 @@ export class CursorPlugin extends BlockNoteExtension {
131131
this.provider.awareness.setLocalStateField("user", user);
132132
};
133133

134+
/**
135+
* Determine whether the foreground color should be white or black based on a provided background color
136+
* Inspired by: https://stackoverflow.com/a/3943023
137+
*
138+
*/
139+
public static isDarkColor(bgColor: string): boolean {
140+
const color = bgColor.charAt(0) === "#" ? bgColor.substring(1, 7) : bgColor;
141+
const r = parseInt(color.substring(0, 2), 16); // hexToR
142+
const g = parseInt(color.substring(2, 4), 16); // hexToG
143+
const b = parseInt(color.substring(4, 6), 16); // hexToB
144+
const uicolors = [r / 255, g / 255, b / 255];
145+
const c = uicolors.map((col) => {
146+
if (col <= 0.03928) {
147+
return col / 12.92;
148+
}
149+
return Math.pow((col + 0.055) / 1.055, 2.4);
150+
});
151+
const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
152+
return L <= 0.179;
153+
}
154+
134155
public static defaultCursorRender = (user: CollaborationUser) => {
135156
const cursorElement = document.createElement("span");
136157

@@ -139,12 +160,22 @@ export class CursorPlugin extends BlockNoteExtension {
139160
const caretElement = document.createElement("span");
140161
caretElement.setAttribute("contentedEditable", "false");
141162
caretElement.classList.add("bn-collaboration-cursor__caret");
142-
caretElement.setAttribute("style", `background-color: ${user.color}`);
163+
caretElement.setAttribute(
164+
"style",
165+
`background-color: ${user.color}; color: ${
166+
CursorPlugin.isDarkColor(user.color) ? "white" : "black"
167+
}`,
168+
);
143169

144170
const labelElement = document.createElement("span");
145171

146172
labelElement.classList.add("bn-collaboration-cursor__label");
147-
labelElement.setAttribute("style", `background-color: ${user.color}`);
173+
labelElement.setAttribute(
174+
"style",
175+
`background-color: ${user.color}; color: ${
176+
CursorPlugin.isDarkColor(user.color) ? "white" : "black"
177+
}`,
178+
);
148179
labelElement.insertBefore(document.createTextNode(user.name), null);
149180

150181
caretElement.insertBefore(labelElement, null);

0 commit comments

Comments
 (0)