From e651f977d6b9f50fef25f6d736f8d4880c997305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ximo=20Mussini?= Date: Thu, 27 May 2021 05:13:18 -0300 Subject: [PATCH] feat: Render titles for social sharing and improve home page sharing (#263) --- src/node/build/render.ts | 50 +++++++++++++++++++++++++++------------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/src/node/build/render.ts b/src/node/build/render.ts index ab4d60f7..59d3bb36 100644 --- a/src/node/build/render.ts +++ b/src/node/build/render.ts @@ -38,7 +38,6 @@ export async function renderPage( pageServerJsFileName )) const pageData = JSON.parse(__pageData) - const frontmatterHead = pageData.frontmatter.head const preloadLinks = [ // resolve imports for index.js + page.md.js and inject script tags for @@ -57,22 +56,30 @@ export async function renderPage( ? `` : '' + const title: string = + pageData.title && pageData.title !== 'Home' + ? `${pageData.title} | ${siteData.title}` + : siteData.title + + const head = addSocialTags( + title, + ...siteData.head, + ...filterOutHeadDescription(pageData.frontmatter.head) + ) + const html = ` - - ${pageData.title ? pageData.title + ` | ` : ``}${siteData.title} - + ${title} ${stylesheetLink} ${preloadLinks} - ${renderHead(siteData.head)} - ${renderHead(frontmatterHead && filterOutHeadDescription(frontmatterHead))} + ${renderHead(head)}
${content}
@@ -112,9 +119,6 @@ function resolvePageImports( } function renderHead(head: HeadConfig[]) { - if (!head || !head.length) { - return '' - } return head .map(([tag, attrs = {}, innerHTML = '']) => { const openTag = `<${tag}${renderAttrs(attrs)}>` @@ -136,13 +140,27 @@ function renderAttrs(attrs: Record): string { } function isMetaDescription(headConfig: HeadConfig) { - return ( - headConfig[0] === 'meta' && - headConfig[1] && - headConfig[1].name === 'description' - ) + const [type, attrs] = headConfig + return type === 'meta' && attrs?.name === 'description' +} + +function filterOutHeadDescription(head: HeadConfig[] | undefined) { + return head ? head.filter((h) => !isMetaDescription(h)) : [] +} + +function hasTag(head: HeadConfig[], tag: HeadConfig) { + const [tagType, tagAttrs] = tag + const [attr, value] = Object.entries(tagAttrs)[0] // First key + return head.some(([type, attrs]) => type === tagType && attrs[attr] === value) } -function filterOutHeadDescription(head: HeadConfig[]) { - return head.filter((h) => !isMetaDescription(h)) +function addSocialTags(title: string, ...head: HeadConfig[]) { + const tags: HeadConfig[] = [ + ['meta', { name: 'twitter:title', content: title }], + ['meta', { property: 'og:title', content: title }] + ] + tags.filter((tagAttrs) => { + if (!hasTag(head, tagAttrs)) head.push(tagAttrs) + }) + return head }