| 1 |
/** |
| 2 |
* Shared write-back: apply sanitized server values only if the user has not typed past them. |
| 3 |
*/ |
| 4 |
|
| 5 |
/** |
| 6 |
* @param {Object} opts |
| 7 |
* @param {Function} opts.getBlock |
| 8 |
* @param {Function} opts.updateBlockAttributes |
| 9 |
* @param {Function} [opts.markNonPersistent] |
| 10 |
* @returns {Function} `(clientId) => (sanitizedDiff, sentPatch) => void` |
| 11 |
*/ |
| 12 |
export function makeWriteBackHandler( { getBlock, updateBlockAttributes, markNonPersistent } ) { |
| 13 |
return ( clientId ) => ( sanitizedDiff, sentPatch ) => { |
| 14 |
const current = getBlock( clientId ); |
| 15 |
if ( ! current || ! current.attributes ) return; |
| 16 |
|
| 17 |
const safeUpdates = {}; |
| 18 |
for ( const k of Object.keys( sanitizedDiff ) ) { |
| 19 |
// Apply only if the block's value still equals what we sent — |
| 20 |
// protects in-progress typing. |
| 21 |
// When sentPatch doesn't include the key (server volunteered it, |
| 22 |
// e.g. auto-gen), we require the block's current value to still |
| 23 |
// be empty so we never clobber explicit input. |
| 24 |
if ( sentPatch[ k ] !== undefined ) { |
| 25 |
if ( current.attributes[ k ] === sentPatch[ k ] ) { |
| 26 |
safeUpdates[ k ] = sanitizedDiff[ k ]; |
| 27 |
} |
| 28 |
} else if ( ! current.attributes[ k ] ) { |
| 29 |
safeUpdates[ k ] = sanitizedDiff[ k ]; |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
if ( Object.keys( safeUpdates ).length === 0 ) return; |
| 34 |
|
| 35 |
if ( typeof markNonPersistent === 'function' ) markNonPersistent(); |
| 36 |
updateBlockAttributes( clientId, safeUpdates ); |
| 37 |
}; |
| 38 |
} |
| 39 |
|