UNPKG

@wordpress/editor

Version:
8 lines (7 loc) 2.81 kB
{ "version": 3, "sources": ["../../../src/components/post-revisions-preview/preserve-client-ids.js"], "sourcesContent": ["/**\n * External dependencies\n */\nimport { diffArrays } from 'diff/lib/diff/array';\n\n/**\n * Preserves clientIds from previously rendered blocks to prevent flashing.\n * Uses LCS algorithm to match blocks by name.\n *\n * This compares the newly parsed blocks against the last rendered blocks\n * to maintain React key stability.\n *\n * @param {Array} newBlocks Newly parsed blocks with fresh clientIds.\n * @param {Array} prevBlocks Previously rendered blocks with stable clientIds.\n * @return {Array} Blocks with preserved clientIds where possible.\n */\nexport function preserveClientIds( newBlocks, prevBlocks ) {\n\tif ( ! prevBlocks?.length || ! newBlocks?.length ) {\n\t\treturn newBlocks;\n\t}\n\n\t// Create signatures for LCS matching using block name.\n\tconst newSigs = newBlocks.map( ( block ) => block.name );\n\tconst prevSigs = prevBlocks.map( ( block ) => block.name );\n\n\tconst diffResult = diffArrays( prevSigs, newSigs );\n\n\tlet newIndex = 0;\n\tlet prevIndex = 0;\n\tconst result = [];\n\n\tfor ( const chunk of diffResult ) {\n\t\tif ( chunk.removed ) {\n\t\t\t// Blocks only in prev render - skip them.\n\t\t\tprevIndex += chunk.count;\n\t\t} else if ( chunk.added ) {\n\t\t\t// Blocks only in new render - keep new clientIds.\n\t\t\tfor ( let i = 0; i < chunk.count; i++ ) {\n\t\t\t\tresult.push( newBlocks[ newIndex++ ] );\n\t\t\t}\n\t\t} else {\n\t\t\t// Matched blocks - preserve clientIds from prev render.\n\t\t\tfor ( let i = 0; i < chunk.count; i++ ) {\n\t\t\t\tconst newBlock = newBlocks[ newIndex++ ];\n\t\t\t\tconst prevBlock = prevBlocks[ prevIndex++ ];\n\t\t\t\tresult.push( {\n\t\t\t\t\t...newBlock,\n\t\t\t\t\tclientId: prevBlock.clientId,\n\t\t\t\t\tinnerBlocks: preserveClientIds(\n\t\t\t\t\t\tnewBlock.innerBlocks,\n\t\t\t\t\t\tprevBlock.innerBlocks\n\t\t\t\t\t),\n\t\t\t\t} );\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result;\n}\n"], "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAA2B;AAapB,SAAS,kBAAmB,WAAW,YAAa;AAC1D,MAAK,CAAE,YAAY,UAAU,CAAE,WAAW,QAAS;AAClD,WAAO;AAAA,EACR;AAGA,QAAM,UAAU,UAAU,IAAK,CAAE,UAAW,MAAM,IAAK;AACvD,QAAM,WAAW,WAAW,IAAK,CAAE,UAAW,MAAM,IAAK;AAEzD,QAAM,iBAAa,yBAAY,UAAU,OAAQ;AAEjD,MAAI,WAAW;AACf,MAAI,YAAY;AAChB,QAAM,SAAS,CAAC;AAEhB,aAAY,SAAS,YAAa;AACjC,QAAK,MAAM,SAAU;AAEpB,mBAAa,MAAM;AAAA,IACpB,WAAY,MAAM,OAAQ;AAEzB,eAAU,IAAI,GAAG,IAAI,MAAM,OAAO,KAAM;AACvC,eAAO,KAAM,UAAW,UAAW,CAAE;AAAA,MACtC;AAAA,IACD,OAAO;AAEN,eAAU,IAAI,GAAG,IAAI,MAAM,OAAO,KAAM;AACvC,cAAM,WAAW,UAAW,UAAW;AACvC,cAAM,YAAY,WAAY,WAAY;AAC1C,eAAO,KAAM;AAAA,UACZ,GAAG;AAAA,UACH,UAAU,UAAU;AAAA,UACpB,aAAa;AAAA,YACZ,SAAS;AAAA,YACT,UAAU;AAAA,UACX;AAAA,QACD,CAAE;AAAA,MACH;AAAA,IACD;AAAA,EACD;AAEA,SAAO;AACR;", "names": [] }