| 1 |
import apiFetch from '@wordpress/api-fetch'; |
| 2 |
import { __, _n, sprintf } from '@wordpress/i18n'; |
| 3 |
import { addQueryArgs } from '@wordpress/url'; |
| 4 |
|
| 5 |
// A composite id names another post, so saving reaches every page rendering it. |
| 6 |
const COMPOSITE_ID_RX = /^(?:part:[^:]+:)?(?:block|navigation):\d+:\d+$/; |
| 7 |
|
| 8 |
export const isSharedBlockId = (blockId) => |
| 9 |
COMPOSITE_ID_RX.test(String(blockId ?? '')); |
| 10 |
|
| 11 |
export const fetchSharedBlockUsage = async (blockId) => { |
| 12 |
if (!isSharedBlockId(blockId)) return null; |
| 13 |
const response = await apiFetch({ |
| 14 |
path: addQueryArgs('/extendify/v1/agent/shared-block-usage', { |
| 15 |
blockId: String(blockId).replace(/^part:[^:]+:/, ''), |
| 16 |
}), |
| 17 |
}); |
| 18 |
if (!response?.scope || response.scope === 'block') return null; |
| 19 |
return response; |
| 20 |
}; |
| 21 |
|
| 22 |
// The current page is already on screen, so naming it tells the user nothing. |
| 23 |
const otherPages = (pages) => { |
| 24 |
const current = Number(window.extAgentData?.context?.postId || 0); |
| 25 |
return (Array.isArray(pages) ? pages : []).filter(({ id }) => id !== current); |
| 26 |
}; |
| 27 |
|
| 28 |
export const sharedBlockNotice = (usage) => { |
| 29 |
if (!usage) return null; |
| 30 |
if (usage.scope === 'site') { |
| 31 |
return __( |
| 32 |
'This content is shared across your site, so saving changes it on every page.', |
| 33 |
'extendify-local', |
| 34 |
); |
| 35 |
} |
| 36 |
|
| 37 |
const pages = otherPages(usage.pages); |
| 38 |
if (!pages.length) return null; |
| 39 |
|
| 40 |
if (pages.length === 1) { |
| 41 |
return sprintf( |
| 42 |
// translators: %s is the name of another page that shows the same content. |
| 43 |
__('Saving also changes this content on %s.', 'extendify-local'), |
| 44 |
pages[0].title, |
| 45 |
); |
| 46 |
} |
| 47 |
|
| 48 |
return sprintf( |
| 49 |
// translators: %d is how many other pages show the same content. |
| 50 |
_n( |
| 51 |
'Saving also changes this content on %d other page.', |
| 52 |
'Saving also changes this content on %d other pages.', |
| 53 |
pages.length, |
| 54 |
'extendify-local', |
| 55 |
), |
| 56 |
pages.length, |
| 57 |
); |
| 58 |
}; |
| 59 |
|