fix(description): calculate description properly when first sentence is longer than max

This commit is contained in:
Jacky Zhao 2025-03-13 14:22:11 -07:00
parent b579950ae5
commit e26658f4ed

View file

@ -5,11 +5,13 @@ import { escapeHTML } from "../../util/escape"
export interface Options { export interface Options {
descriptionLength: number descriptionLength: number
maxDescriptionLength: number
replaceExternalLinks: boolean replaceExternalLinks: boolean
} }
const defaultOptions: Options = { const defaultOptions: Options = {
descriptionLength: 150, descriptionLength: 150,
maxDescriptionLength: 300,
replaceExternalLinks: true, replaceExternalLinks: true,
} }
@ -37,35 +39,41 @@ export const Description: QuartzTransformerPlugin<Partial<Options>> = (userOpts)
text = text.replace(urlRegex, "$<domain>" + "$<path>") text = text.replace(urlRegex, "$<domain>" + "$<path>")
} }
const desc = frontMatterDescription ?? text if (frontMatterDescription) {
const sentences = desc.replace(/\s+/g, " ").split(/\.\s/) file.data.description = frontMatterDescription
const finalDesc: string[] = [] file.data.text = text
const len = opts.descriptionLength return
let sentenceIdx = 0 }
let currentDescriptionLength = 0
if (sentences[0] !== undefined && sentences[0].length >= len) { // otherwise, use the text content
const firstSentence = sentences[0].split(" ") const desc = text
while (currentDescriptionLength < len) { const sentences = desc.replace(/\s+/g, " ").split(/\.\s/)
const sentence = firstSentence[sentenceIdx] let finalDesc = ""
if (!sentence) break let sentenceIdx = 0
finalDesc.push(sentence)
currentDescriptionLength += sentence.length // Add full sentences until we exceed the guideline length
sentenceIdx++ while (sentenceIdx < sentences.length) {
} const sentence = sentences[sentenceIdx]
finalDesc.push("...") if (!sentence) break
} else {
while (currentDescriptionLength < len) { const currentSentence = sentence.endsWith(".") ? sentence : sentence + "."
const sentence = sentences[sentenceIdx] const nextLength = finalDesc.length + currentSentence.length + (finalDesc ? 1 : 0)
if (!sentence) break
const currentSentence = sentence.endsWith(".") ? sentence : sentence + "." // Add the sentence if we're under the guideline length
finalDesc.push(currentSentence) // or if this is the first sentence (always include at least one)
currentDescriptionLength += currentSentence.length if (nextLength <= opts.descriptionLength || sentenceIdx === 0) {
finalDesc += (finalDesc ? " " : "") + currentSentence
sentenceIdx++ sentenceIdx++
} else {
break
} }
} }
file.data.description = finalDesc.join(" ") // truncate to max length if necessary
file.data.description =
finalDesc.length > opts.maxDescriptionLength
? finalDesc.slice(0, opts.maxDescriptionLength) + "..."
: finalDesc
file.data.text = text file.data.text = text
} }
}, },