From bc5e0cc1954117087890ed7a2e93b41d5e847107 Mon Sep 17 00:00:00 2001 From: Riccardo Date: Fri, 23 Feb 2024 19:23:08 +0100 Subject: [PATCH] fix: avoid truncating links with story cutoff length --- components/emails/newsletter.tsx | 3 ++- utils/textTruncate.ts | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 utils/textTruncate.ts diff --git a/components/emails/newsletter.tsx b/components/emails/newsletter.tsx index d2ef464..1e84cdf 100644 --- a/components/emails/newsletter.tsx +++ b/components/emails/newsletter.tsx @@ -1,5 +1,6 @@ import { z } from 'zod'; import { NewsSchema } from '../../utils/schemas'; +import { textTruncate } from '../../utils/textTruncate'; import { sayings } from './helpers/sayings'; import Template from './template'; @@ -58,7 +59,7 @@ export default function NewsletterTemplate( dangerouslySetInnerHTML={{ __html: story.text.length > 500 - ? story.text.substring(0, 500) + '...' + ? textTruncate(story.text, 500) + '...' : story.text }} /> diff --git a/utils/textTruncate.ts b/utils/textTruncate.ts new file mode 100644 index 0000000..2e6c632 --- /dev/null +++ b/utils/textTruncate.ts @@ -0,0 +1,14 @@ +export function textTruncate(text: string, length: number) { + let truncatedText = text.substring(0, length); + const lastSpaceIndex = truncatedText.lastIndexOf(' '); + + const urlPattern = /(https?:\/\/[^\s]+)/g; + const lastWord = truncatedText.substring(lastSpaceIndex).trim(); + if (urlPattern.test(lastWord)) { + truncatedText = truncatedText.substring(0, lastSpaceIndex); + } + + truncatedText += '...'; + + return truncatedText; +}