notes/quartz/plugins/transformers/description.ts

91 lines
2.8 KiB
TypeScript
Raw Permalink Normal View History

2023-07-22 17:27:41 -07:00
import { Root as HTMLRoot } from "hast"
2023-05-30 08:02:20 -07:00
import { toString } from "hast-util-to-string"
import { QuartzTransformerPlugin } from "../types"
2023-09-06 21:47:59 -07:00
import { escapeHTML } from "../../util/escape"
2023-05-30 08:02:20 -07:00
export interface Options {
descriptionLength: number
maxDescriptionLength: number
replaceExternalLinks: boolean
2023-05-30 08:02:20 -07:00
}
const defaultOptions: Options = {
2023-07-22 17:27:41 -07:00
descriptionLength: 150,
maxDescriptionLength: 300,
replaceExternalLinks: true,
2023-05-30 08:02:20 -07:00
}
const urlRegex = new RegExp(
/(https?:\/\/)?(?<domain>([\da-z\.-]+)\.([a-z\.]{2,6})(:\d+)?)(?<path>[\/\w\.-]*)(\?[\/\w\.=&;-]*)?/,
"g",
)
2024-08-08 18:28:13 -07:00
export const Description: QuartzTransformerPlugin<Partial<Options>> = (userOpts) => {
const opts = { ...defaultOptions, ...userOpts }
return {
name: "Description",
htmlPlugins() {
return [
() => {
return async (tree: HTMLRoot, file) => {
let frontMatterDescription = file.data.frontmatter?.description
let text = escapeHTML(toString(tree))
if (opts.replaceExternalLinks) {
frontMatterDescription = frontMatterDescription?.replace(
urlRegex,
"$<domain>" + "$<path>",
)
text = text.replace(urlRegex, "$<domain>" + "$<path>")
}
if (frontMatterDescription) {
file.data.description = frontMatterDescription
file.data.text = text
return
}
// otherwise, use the text content
const desc = text
const sentences = desc.replace(/\s+/g, " ").split(/\.\s/)
let finalDesc = ""
let sentenceIdx = 0
// Add full sentences until we exceed the guideline length
while (sentenceIdx < sentences.length) {
const sentence = sentences[sentenceIdx]
if (!sentence) break
const currentSentence = sentence.endsWith(".") ? sentence : sentence + "."
const nextLength = finalDesc.length + currentSentence.length + (finalDesc ? 1 : 0)
// Add the sentence if we're under the guideline length
// or if this is the first sentence (always include at least one)
if (nextLength <= opts.descriptionLength || sentenceIdx === 0) {
finalDesc += (finalDesc ? " " : "") + currentSentence
sentenceIdx++
} else {
break
}
}
// truncate to max length if necessary
file.data.description =
finalDesc.length > opts.maxDescriptionLength
? finalDesc.slice(0, opts.maxDescriptionLength) + "..."
: finalDesc
file.data.text = text
2023-05-30 08:02:20 -07:00
}
2023-07-22 17:27:41 -07:00
},
]
2023-07-22 17:27:41 -07:00
},
2023-05-30 08:02:20 -07:00
}
}
2023-07-22 17:27:41 -07:00
declare module "vfile" {
2023-05-30 08:02:20 -07:00
interface DataMap {
description: string
2023-06-07 22:27:32 -07:00
text: string
2023-05-30 08:02:20 -07:00
}
}