Skip to content

fix: add switch foreground color based on user color #1785 #1787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 25, 2025
Merged
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
35 changes: 33 additions & 2 deletions packages/core/src/extensions/Collaboration/CursorPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,27 @@ export class CursorPlugin extends BlockNoteExtension {
this.provider.awareness.setLocalStateField("user", user);
};

/**
* Determine whether the foreground color should be white or black based on a provided background color
* Inspired by: https://stackoverflow.com/a/3943023
*
*/
public static isDarkColor(bgColor: string): boolean {
const color = bgColor.charAt(0) === "#" ? bgColor.substring(1, 7) : bgColor;
const r = parseInt(color.substring(0, 2), 16); // hexToR
const g = parseInt(color.substring(2, 4), 16); // hexToG
const b = parseInt(color.substring(4, 6), 16); // hexToB
const uicolors = [r / 255, g / 255, b / 255];
const c = uicolors.map((col) => {
if (col <= 0.03928) {
return col / 12.92;
}
return Math.pow((col + 0.055) / 1.055, 2.4);
});
const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
return L <= 0.179;
}

public static defaultCursorRender = (user: CollaborationUser) => {
const cursorElement = document.createElement("span");

Expand All @@ -139,12 +160,22 @@ export class CursorPlugin extends BlockNoteExtension {
const caretElement = document.createElement("span");
caretElement.setAttribute("contentedEditable", "false");
caretElement.classList.add("bn-collaboration-cursor__caret");
caretElement.setAttribute("style", `background-color: ${user.color}`);
caretElement.setAttribute(
"style",
`background-color: ${user.color}; color: ${
CursorPlugin.isDarkColor(user.color) ? "white" : "black"
}`,
);

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

labelElement.classList.add("bn-collaboration-cursor__label");
labelElement.setAttribute("style", `background-color: ${user.color}`);
labelElement.setAttribute(
"style",
`background-color: ${user.color}; color: ${
CursorPlugin.isDarkColor(user.color) ? "white" : "black"
}`,
);
labelElement.insertBefore(document.createTextNode(user.name), null);

caretElement.insertBefore(labelElement, null);
Expand Down
Loading