Skip to content

Commit

Permalink
記事の本文からmeta descriptionを生成する
Browse files Browse the repository at this point in the history
  • Loading branch information
nagutabby committed Feb 22, 2025
1 parent b246cd2 commit 565ad71
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 7 deletions.
26 changes: 23 additions & 3 deletions src/lib/components/OpenGraph.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,30 @@
type Props = {
title: string;
description: string;
body: string;
url: string;
}
const { title, description, url }: Props = $props()
};
const { title, body, url }: Props = $props();
const generateDescriptionFromText = (body: string) => {
const hasHTMLTags = /<[a-z][\s\S]*>/i.test(body);
const plainText: string = hasHTMLTags ? body.replace(/<[^>]+>/g, "") : body;
const normalizedText = plainText.replace(/\s+/g, " ").trim();
let description = normalizedText.slice(0, 100);
if (normalizedText.length > 100) {
const lastChar = description.slice(-1);
if (!/[。、.,!!??]/.test(lastChar)) {
description += "";
}
}
return description;
};
let description = $derived(generateDescriptionFromText(body));
</script>

<svelte:head>
Expand Down
2 changes: 1 addition & 1 deletion src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<OpenGraph
url={page.data.image.url}
title={page.data.title}
description={page.data.description}
body={page.data.body}
></OpenGraph>

<Header url={page.data.image.url} title={page.data.title}></Header>
Expand Down
2 changes: 1 addition & 1 deletion src/routes/+page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const load: PageLoad = async ({ url }) => {
url: "https://images.microcms-assets.io/assets/99c53a99ae2b4682938f6c435d83e3d9/ca63de19468e45b2833ebf325dbfd56c/Microsoft-Fluentui-Emoji-3d-Cat-3d.1024.png"
},
title: "nagutabbyの考え事",
description: "学んだことをまとめるブログ"
body: "学んだことをまとめるブログ"
};
const data = {
...articleData,
Expand Down
2 changes: 1 addition & 1 deletion src/routes/search/+page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const load: PageLoad = async ({ url }) => {
url: "https://images.microcms-assets.io/assets/99c53a99ae2b4682938f6c435d83e3d9/ca63de19468e45b2833ebf325dbfd56c/Microsoft-Fluentui-Emoji-3d-Cat-3d.1024.png"
},
title: `「${query}」を含む記事`,
description: ""
body: `「${query}」を含む記事の検索結果を表示しています`
};
const data = {
...articleData,
Expand Down
2 changes: 1 addition & 1 deletion src/routes/slides/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<OpenGraph
{url}
{title}
{description}
body={description}
></OpenGraph>

<Header
Expand Down

0 comments on commit 565ad71

Please sign in to comment.