@@ -131,6 +131,27 @@ export class CursorPlugin extends BlockNoteExtension {
131
131
this . provider . awareness . setLocalStateField ( "user" , user ) ;
132
132
} ;
133
133
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
+
134
155
public static defaultCursorRender = ( user : CollaborationUser ) => {
135
156
const cursorElement = document . createElement ( "span" ) ;
136
157
@@ -139,12 +160,22 @@ export class CursorPlugin extends BlockNoteExtension {
139
160
const caretElement = document . createElement ( "span" ) ;
140
161
caretElement . setAttribute ( "contentedEditable" , "false" ) ;
141
162
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
+ ) ;
143
169
144
170
const labelElement = document . createElement ( "span" ) ;
145
171
146
172
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
+ ) ;
148
179
labelElement . insertBefore ( document . createTextNode ( user . name ) , null ) ;
149
180
150
181
caretElement . insertBefore ( labelElement , null ) ;
0 commit comments