fix truncating of text to avoid cutting into link

This commit is contained in:
Julie Lenaerts 2023-11-21 09:20:21 +01:00
parent 502894ecea
commit ed271bed31

View File

@ -58,14 +58,41 @@ const shouldTruncate = (content: string, maxLength = 100): boolean => {
const truncateContent = (content: string, maxLength = 100): string => {
if (shouldTruncate(content, maxLength)) {
const lastSpaceIndex = content.lastIndexOf(' ', maxLength);
console.log(lastSpaceIndex)
let truncatedContent = content.slice(0, maxLength);
let linkDepth = 0;
let linkStartIndex = -1;
if (lastSpaceIndex !== -1) {
return content.slice(0, lastSpaceIndex) + '...';
} else {
return content.slice(0, maxLength) + '...';
for (let i = 0; i < truncatedContent.length; i++) {
const char = truncatedContent[i];
if (char === '[') {
linkDepth++;
if (linkDepth === 1) {
linkStartIndex = i;
}
} else if (char === ']') {
linkDepth = Math.max(0, linkDepth - 1);
} else if (char === '(' && linkDepth === 0) {
truncatedContent = truncatedContent.slice(0, i);
break;
}
}
while (linkDepth > 0) {
truncatedContent += ']';
linkDepth--;
}
// If a link was found, append the URL inside the parentheses
if (linkStartIndex !== -1) {
const linkEndIndex = content.indexOf(')', linkStartIndex);
const url = content.slice(linkStartIndex + 1, linkEndIndex);
truncatedContent = truncatedContent.slice(0, linkStartIndex) + `(${url})`;
}
truncatedContent += '...';
return truncatedContent;
} else {
return content;
}
@ -76,9 +103,9 @@ const convertMarkdownToHtml = (markdown: string): string => {
return DOMPurify.sanitize(rawHtml)
};
const prepareContent = (content: string, maxLength = 100): string => {
const truncatedContent = truncateContent(content, maxLength);
return convertMarkdownToHtml(truncatedContent);
const prepareContent = (content: string, maxLength = 200): string => {
const htmlContent = convertMarkdownToHtml(content);
return truncateContent(htmlContent, maxLength);
};
const formatDate = (datetime: DateTime): string|null => {