diff --git a/packages/core/src/extensions/Collaboration/CursorPlugin.ts b/packages/core/src/extensions/Collaboration/CursorPlugin.ts index 50ae84b887..5e2a45d116 100644 --- a/packages/core/src/extensions/Collaboration/CursorPlugin.ts +++ b/packages/core/src/extensions/Collaboration/CursorPlugin.ts @@ -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"); @@ -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);