@@ -23,14 +23,13 @@ const traverseElement = (
2323export const moveColorAttributes : MigrationRule = ( fragment , tr ) => {
2424 // Stores necessary info for all `blockContainer` nodes which still have
2525 // `textColor` or `backgroundColor` attributes that need to be moved.
26- const targetBlockContainers : Record <
26+ const targetBlockContainers : Map <
2727 string ,
2828 {
29- textColor ? : string ;
30- backgroundColor ? : string ;
29+ textColor : string | undefined ;
30+ backgroundColor : string | undefined ;
3131 }
32- > = { } ;
33-
32+ > = new Map ( ) ;
3433 // Finds all elements which still have `textColor` or `backgroundColor`
3534 // attributes in the current Yjs fragment.
3635 fragment . forEach ( ( element ) => {
@@ -40,39 +39,53 @@ export const moveColorAttributes: MigrationRule = (fragment, tr) => {
4039 element . nodeName === "blockContainer" &&
4140 element . hasAttribute ( "id" )
4241 ) {
42+ const textColor = element . getAttribute ( "textColor" ) ;
43+ const backgroundColor = element . getAttribute ( "backgroundColor" ) ;
44+
4345 const colors = {
44- textColor : element . getAttribute ( "textColor" ) ,
45- backgroundColor : element . getAttribute ( "backgroundColor" ) ,
46+ textColor :
47+ textColor === defaultProps . textColor . default
48+ ? undefined
49+ : textColor ,
50+ backgroundColor :
51+ backgroundColor === defaultProps . backgroundColor . default
52+ ? undefined
53+ : backgroundColor ,
4654 } ;
4755
48- if ( colors . textColor === defaultProps . textColor . default ) {
49- colors . textColor = undefined ;
50- }
51- if ( colors . backgroundColor === defaultProps . backgroundColor . default ) {
52- colors . backgroundColor = undefined ;
53- }
54-
5556 if ( colors . textColor || colors . backgroundColor ) {
56- targetBlockContainers [ element . getAttribute ( "id" ) ! ] = colors ;
57+ targetBlockContainers . set ( element . getAttribute ( "id" ) ! , colors ) ;
5758 }
5859 }
5960 } ) ;
6061 }
6162 } ) ;
6263
64+ if ( targetBlockContainers . size === 0 ) {
65+ return false ;
66+ }
67+
6368 // Appends transactions to add the `textColor` and `backgroundColor`
6469 // attributes found on each `blockContainer` node to move them to the child
6570 // `blockContent` node.
6671 tr . doc . descendants ( ( node , pos ) => {
6772 if (
6873 node . type . name === "blockContainer" &&
69- targetBlockContainers [ node . attrs . id ]
74+ targetBlockContainers . has ( node . attrs . id )
7075 ) {
71- tr = tr . setNodeMarkup (
72- pos + 1 ,
73- undefined ,
74- targetBlockContainers [ node . attrs . id ] ,
75- ) ;
76+ const el = tr . doc . nodeAt ( pos + 1 ) ;
77+ if ( ! el ) {
78+ throw new Error ( "No element found" ) ;
79+ }
80+
81+ tr . setNodeMarkup ( pos + 1 , undefined , {
82+ // preserve existing attributes
83+ ...el . attrs ,
84+ // add the textColor and backgroundColor attributes
85+ ...targetBlockContainers . get ( node . attrs . id ) ,
86+ } ) ;
7687 }
7788 } ) ;
89+
90+ return true ;
7891} ;
0 commit comments