30 lines
1.2 KiB
TypeScript
30 lines
1.2 KiB
TypeScript
/**
|
|
* Flattens the Markdown users write into one line of plain text, where a
|
|
* quote of it can't render markup: the chat's reply previews, the digest
|
|
* email's quotes of a comment or a note, and the line of a description on a
|
|
* playlist's card and on a user in the search results.
|
|
*
|
|
* @module
|
|
*/
|
|
|
|
/**
|
|
* Returns the Markdown `md` as one line of plain text. Images become their alt
|
|
* text, or `imageLabel` without one, and links their text. It also takes a
|
|
* body cut short, possibly inside a link, as the server cuts a chat message's
|
|
* `replyToBody`: the unfinished link then shows as its text, without half a
|
|
* URL.
|
|
*/
|
|
export function markdownToPlainText(md: string, imageLabel: string): string {
|
|
return md
|
|
// An image or link cut short at the end loses its unfinished target.
|
|
.replace(/!\[([^\]]*)\]\([^)]*$/, (_, alt: string) => alt || imageLabel)
|
|
.replace(/(^|[^!])\[([^\]]*)\]\([^)]*$/, "$1$2")
|
|
.replace(/!\[[^\]]*$/, "")
|
|
.replace(/!\[([^\]]*)\]\([^)]*\)/g, (_, alt: string) => alt || imageLabel)
|
|
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
|
|
.replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "")
|
|
.replace(/```\w*|\*\*|__|~~|[*`]/g, "")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
}
|