1+ /**
2+ * External dependencies
3+ */
4+ import { v4 as createId } from 'uuid' ;
5+
16/**
27 * WordPress dependencies
38 */
@@ -24,14 +29,29 @@ export function updateFootnotesFromMeta( blocks, meta ) {
2429
2530 if ( currentOrder . join ( '' ) === newOrder . join ( '' ) ) return output ;
2631
27- const newFootnotes = newOrder . map (
28- ( fnId ) =>
29- footnotes . find ( ( fn ) => fn . id === fnId ) ||
30- oldFootnotes [ fnId ] || {
31- id : fnId ,
32- content : '' ,
32+ const newFootnotes = newOrder
33+ . map (
34+ ( fnId ) =>
35+ footnotes . find ( ( fn ) => fn . id === fnId ) ||
36+ oldFootnotes [ fnId ] || {
37+ id : fnId ,
38+ content : '' ,
39+ }
40+ )
41+ . reduce ( ( acc , fn ) => {
42+ if ( acc . map ( ( { id } ) => id ) . includes ( fn . id ) ) {
43+ acc . push ( { ...fn , id : createId ( ) } ) ;
44+ } else {
45+ acc . push ( fn ) ;
3346 }
34- ) ;
47+ return acc ;
48+ } , [ ] ) ;
49+
50+ const idMap = newOrder . map ( ( currentValue , i ) => ( {
51+ currentValue,
52+ newValue : newFootnotes [ i ] . id ,
53+ used : false ,
54+ } ) ) ;
3555
3656 function updateAttributes ( attributes ) {
3757 // Only attempt to update attributes, if attributes is an object.
@@ -69,10 +89,18 @@ export function updateFootnotesFromMeta( blocks, meta ) {
6989 richTextValue . replacements . forEach ( ( replacement ) => {
7090 if ( replacement . type === 'core/footnote' ) {
7191 const id = replacement . attributes [ 'data-fn' ] ;
72- const index = newOrder . indexOf ( id ) ;
92+ const index = idMap . findIndex (
93+ ( { currentValue, used } ) => {
94+ return currentValue === id && ! used ;
95+ }
96+ ) ;
97+ idMap [ index ] . used = true ;
7398 // The innerHTML contains the count wrapped in a link.
7499 const countValue = create ( {
75- html : replacement . innerHTML ,
100+ html : replacement . innerHTML . replace (
101+ idMap [ index ] . currentValue ,
102+ idMap [ index ] . newValue
103+ ) ,
76104 } ) ;
77105 countValue . text = String ( index + 1 ) ;
78106 countValue . formats = Array . from (
@@ -83,9 +111,14 @@ export function updateFootnotesFromMeta( blocks, meta ) {
83111 { length : countValue . text . length } ,
84112 ( ) => countValue . replacements [ 0 ]
85113 ) ;
114+ replacement . attributes [ 'data-fn' ] =
115+ idMap [ index ] . newValue ;
86116 replacement . innerHTML = toHTMLString ( {
87117 value : countValue ,
88- } ) ;
118+ } ) . replace (
119+ idMap [ index ] . currentValue ,
120+ idMap [ index ] . newValue
121+ ) ;
89122 }
90123 } ) ;
91124
0 commit comments