| 1 |
const SOCIAL_SERVICES = ['facebook', 'instagram', 'x', 'tiktok']; |
| 2 |
|
| 3 |
const SOCIAL_LINK_RE = /<!--\s*wp:social-link\s+(\{[^}]*\})\s*\/-->/g; |
| 4 |
const SOCIAL_LINKS_BLOCK_RE = |
| 5 |
/<!--\s*wp:social-links\b[^>]*>[\s\S]*?<!--\s*\/wp:social-links\s*-->/g; |
| 6 |
|
| 7 |
const hasScrapedSocial = (profiles) => |
| 8 |
!!profiles && SOCIAL_SERVICES.some((key) => profiles[key]); |
| 9 |
|
| 10 |
export const applySocialProfiles = (code, profiles) => { |
| 11 |
if (!code || !hasScrapedSocial(profiles)) return code; |
| 12 |
|
| 13 |
return code.replace(SOCIAL_LINKS_BLOCK_RE, (block) => { |
| 14 |
let keepCount = 0; |
| 15 |
const updated = block.replace(SOCIAL_LINK_RE, (match, attrs) => { |
| 16 |
const service = attrs.match(/"service":"([^"]+)"/)?.[1]; |
| 17 |
const url = SOCIAL_SERVICES.includes(service) ? profiles[service] : null; |
| 18 |
if (!url) return ''; |
| 19 |
keepCount++; |
| 20 |
const newAttrs = attrs.replace( |
| 21 |
/"url":"[^"]*"/, |
| 22 |
`"url":${JSON.stringify(url)}`, |
| 23 |
); |
| 24 |
return match.replace(attrs, newAttrs); |
| 25 |
}); |
| 26 |
return keepCount === 0 ? '' : updated; |
| 27 |
}); |
| 28 |
}; |
| 29 |
|