| 1 |
import { healBlockMarkup } from '@agent/lib/heal-blocks'; |
| 2 |
import { ensureCoreBlocksRegistered } from '@agent/lib/register-blocks'; |
| 3 |
import apiFetch from '@wordpress/api-fetch'; |
| 4 |
|
| 5 |
// TODO: check for post_lock and error that someone is editing |
| 6 |
export default async ({ previousContent, newContent }) => { |
| 7 |
await ensureCoreBlocksRegistered(); |
| 8 |
const { postType, postId } = window.extAgentData.context; |
| 9 |
|
| 10 |
const type = await apiFetch({ |
| 11 |
path: `/wp/v2/types/${encodeURIComponent(postType)}`, |
| 12 |
}); |
| 13 |
const base = type?.rest_base || `${postType}s`; |
| 14 |
|
| 15 |
const response = await apiFetch({ |
| 16 |
path: `/wp/v2/${base}/${postId}?context=edit`, |
| 17 |
}); |
| 18 |
|
| 19 |
const content = response.content.raw.replace( |
| 20 |
previousContent, |
| 21 |
healBlockMarkup(newContent), |
| 22 |
); |
| 23 |
|
| 24 |
// A string-replace that matched nothing writes the post back unchanged; |
| 25 |
// refuse so the user sees a retry prompt instead of a false success. |
| 26 |
if (content === response.content.raw) { |
| 27 |
return { refused: true, reason: 'no-op' }; |
| 28 |
} |
| 29 |
|
| 30 |
await apiFetch({ |
| 31 |
path: `/wp/v2/${base}/${postId}`, |
| 32 |
method: 'POST', |
| 33 |
data: { content }, |
| 34 |
}); |
| 35 |
}; |
| 36 |
|