11import { EditorState , SelectionState , Modifier } from "draft-js" ;
22
3+ const STYLES = [ "BOLD" , "ITALIC" , "CODE" , "STRIKETHROUGH" ] ;
4+
35const changeCurrentInlineStyle = ( editorState , matchArr , style , character ) => {
46 const currentContent = editorState . getCurrentContent ( ) ;
57 const selection = editorState . getSelection ( ) ;
@@ -10,26 +12,63 @@ const changeCurrentInlineStyle = (editorState, matchArr, style, character) => {
1012 const currentInlineStyle = block . getInlineStyleAt ( index ) . merge ( ) ;
1113 const newStyle = currentInlineStyle . merge ( [ style ] ) ;
1214 const focusOffset = index + matchArr [ 0 ] . length ;
15+
1316 const wordSelection = SelectionState . createEmpty ( key ) . merge ( {
1417 anchorOffset : index ,
1518 focusOffset,
1619 } ) ;
20+
21+ const inlineStyles = [ ] ;
22+
23+ STYLES . forEach ( _style =>
24+ block . findStyleRanges (
25+ styles => styles . getStyle ( ) . includes ( _style ) ,
26+ ( start , end ) => {
27+ if ( focusOffset > start && index <= end ) {
28+ inlineStyles . push ( {
29+ style : _style ,
30+ start : start >= index ? start : index ,
31+ end : end > focusOffset ? end : focusOffset ,
32+ } ) ;
33+ }
34+ }
35+ )
36+ ) ;
37+
38+ console . log ( "yo inline styles" , inlineStyles ) ;
39+
1740 let newContentState = Modifier . replaceText (
1841 currentContent ,
1942 wordSelection ,
2043 matchArr [ 1 ] ,
2144 newStyle
2245 ) ;
46+
47+ const afterSelection = newContentState . getSelectionAfter ( ) ;
48+
49+ // re-apply previous styles
50+ newContentState = inlineStyles . reduce (
51+ ( content , { style : _style , start, end } ) =>
52+ Modifier . applyInlineStyle (
53+ content ,
54+ wordSelection . merge ( { anchorOffset : start , focusOffset : end } ) ,
55+ _style
56+ ) ,
57+ newContentState
58+ ) ;
59+
2360 newContentState = Modifier . insertText (
2461 newContentState ,
25- newContentState . getSelectionAfter ( ) ,
62+ afterSelection ,
2663 character || " "
2764 ) ;
65+
2866 const newEditorState = EditorState . push (
2967 editorState ,
3068 newContentState ,
3169 "change-inline-style"
3270 ) ;
71+
3372 return EditorState . forceSelection (
3473 newEditorState ,
3574 newContentState . getSelectionAfter ( )
0 commit comments