feat(markdown): implement callout
This commit is contained in:
+17
-5
@@ -7,10 +7,11 @@
|
||||
"scripts": {
|
||||
"build": "pnpm db-generate && next build",
|
||||
"dev": "next",
|
||||
"test-unit": "uvu src .test.ts -r esbuild-register",
|
||||
"test-e2e": "playwright test",
|
||||
"db-generate": "prisma generate",
|
||||
"start": "next start --port $PORT",
|
||||
"db-seed": "node -r sucrase/register prisma/seed.ts"
|
||||
"db-seed": "node -r esbuild-register prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "^0.20.0",
|
||||
@@ -36,10 +37,11 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"form-data": "^4.0.0",
|
||||
"mailgun.js": "^5.2.2",
|
||||
"markdown-it": "^13.0.0",
|
||||
"mdast-util-to-string": "^3.1.0",
|
||||
"nanoid": "^3.3.3",
|
||||
"next": "^12.1.6",
|
||||
"pica": "^9.0.1",
|
||||
"posthtml": "^0.16.6",
|
||||
"prismjs": "^1.28.0",
|
||||
"react": "^18.1.0",
|
||||
"react-avatar-editor": "^12.0.0",
|
||||
@@ -48,8 +50,17 @@
|
||||
"react-hot-toast": "^2.2.0",
|
||||
"react-query": "^3.39.0",
|
||||
"react-sortablejs": "^6.1.1",
|
||||
"rehype-prism-plus": "^1.4.0",
|
||||
"rehype-raw": "^6.1.1",
|
||||
"rehype-sanitize": "^5.0.1",
|
||||
"rehype-stringify": "^9.0.3",
|
||||
"remark-gfm": "^3.0.1",
|
||||
"remark-parse": "^10.0.1",
|
||||
"remark-rehype": "^10.1.0",
|
||||
"sortablejs": "^1.15.0",
|
||||
"ua-parser-js": "^1.0.2",
|
||||
"unified": "^10.1.2",
|
||||
"unist-util-visit": "^4.1.0",
|
||||
"use-onclickoutside": "^0.4.0",
|
||||
"uuid": "^8.3.2",
|
||||
"zod": "^3.15.1",
|
||||
@@ -60,7 +71,6 @@
|
||||
"@types/async-busboy": "^1.1.1",
|
||||
"@types/busboy": "^1.5.0",
|
||||
"@types/cookie": "^0.5.1",
|
||||
"@types/markdown-it": "^12.2.3",
|
||||
"@types/mjml": "^4.7.0",
|
||||
"@types/node": "^17.0.31",
|
||||
"@types/pica": "^9.0.0",
|
||||
@@ -72,13 +82,15 @@
|
||||
"@types/ua-parser-js": "^0.7.36",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"autoprefixer": "^10.4.7",
|
||||
"esbuild": "^0.14.39",
|
||||
"esbuild-register": "^3.3.2",
|
||||
"eslint": "^8.15.0",
|
||||
"eslint-config-next": "^12.1.6",
|
||||
"postcss-import": "^14.1.0",
|
||||
"prisma": "^3.14.0",
|
||||
"sucrase": "^3.21.0",
|
||||
"tailwindcss": "^3.0.24",
|
||||
"typescript": "^4.5.5"
|
||||
"typescript": "^4.5.5",
|
||||
"uvu": "^0.5.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
|
||||
Generated
+1168
-101
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,4 +1,4 @@
|
||||
.code pre {
|
||||
pre {
|
||||
@apply -mx-5 md:-mx-8;
|
||||
@apply md:rounded-xl;
|
||||
@apply my-7;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** based on prism tomorror */
|
||||
|
||||
.code {
|
||||
pre {
|
||||
--lang-color: #8d8c8c;
|
||||
--code-bg: rgb(18, 18, 38);
|
||||
--code-fg: #fff;
|
||||
|
||||
+20
-3
@@ -90,10 +90,27 @@
|
||||
@apply bg-zinc-100;
|
||||
}
|
||||
|
||||
.prose .task-list {
|
||||
.prose .task-list-item {
|
||||
@apply list-none;
|
||||
}
|
||||
|
||||
.prose > .task-list {
|
||||
@apply pl-0;
|
||||
.prose > ul > .task-list-item {
|
||||
@apply -ml-5;
|
||||
}
|
||||
|
||||
.prose .callout {
|
||||
@apply border border-indigo-100 bg-indigo-50 text-indigo-700 rounded-xl p-5 md:p-8 font-normal;
|
||||
@apply -mx-5 md:-mx-8 my-10;
|
||||
}
|
||||
|
||||
.prose .callout-warn {
|
||||
@apply border-orange-200 bg-orange-100 text-orange-700;
|
||||
}
|
||||
|
||||
.prose .callout-success {
|
||||
@apply border-green-200 bg-green-100 text-green-700;
|
||||
}
|
||||
|
||||
.prose .callout-danger {
|
||||
@apply border-red-200 bg-red-100 text-red-700;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { test } from "uvu"
|
||||
import assert from "uvu/assert"
|
||||
import { renderPageContent } from "./index"
|
||||
|
||||
test("simple", async () => {
|
||||
const { contentHTML, excerpt } = await renderPageContent(`
|
||||
# Hello
|
||||
|
||||
This is the **excerpt**
|
||||
|
||||
> Hello Blockquote <sup>foo</sup>
|
||||
|
||||
- [ ] task list
|
||||
- [x] done
|
||||
|
||||
<script>alert('xss')</script>
|
||||
|
||||
<img src="foo.png" alt="my image" onerror="console.log(1)" />
|
||||
|
||||
<figcaption><a href="https://example.com">my caption</a></figcaption>
|
||||
|
||||
<img src />
|
||||
|
||||
\`\`\`js
|
||||
function foo() {}
|
||||
|
||||
<script>alert('xss')</script>
|
||||
\`\`\`
|
||||
|
||||
\`\`\`
|
||||
<script>alert('xss')</script>
|
||||
\`\`\`
|
||||
`)
|
||||
|
||||
assert.not.match(contentHTML, /<script>/)
|
||||
assert.equal(excerpt, `This is the excerpt`)
|
||||
})
|
||||
|
||||
test("wrap table", async () => {
|
||||
const { contentHTML } = await renderPageContent(`
|
||||
|a|b|
|
||||
|---|---|
|
||||
|c|d|
|
||||
`)
|
||||
assert.match(contentHTML, `<div class="table-wrapper">`)
|
||||
})
|
||||
|
||||
test("callout", async () => {
|
||||
const { contentHTML } = await renderPageContent(`
|
||||
> TIP:
|
||||
> Some tip!
|
||||
|
||||
> WARN:
|
||||
>
|
||||
> Some warning!
|
||||
`)
|
||||
console.log(contentHTML)
|
||||
})
|
||||
|
||||
test.run()
|
||||
+35
-18
@@ -1,9 +1,15 @@
|
||||
import Markdown from "markdown-it"
|
||||
import { pluginCodeBlock } from "./plugin-code-block"
|
||||
import { pluginExcerpt } from "./plugin-excerpt"
|
||||
import { pluginImage } from "./plugin-image"
|
||||
import { pluginTable } from "./plugin-table"
|
||||
import { pluginTaskList } from "./plugin-task-list"
|
||||
import { unified } from "unified"
|
||||
import remarkParse from "remark-parse"
|
||||
import remarkRehype from "remark-rehype"
|
||||
import rehypeStringify from "rehype-stringify"
|
||||
import remarkGfm from "remark-gfm"
|
||||
import rehypeSanitize, { defaultSchema } from "rehype-sanitize"
|
||||
import rehypeRaw from "rehype-raw"
|
||||
import rehypePrism from "rehype-prism-plus"
|
||||
import { rehypeImage } from "./rehype-image"
|
||||
import { remarkExcerpt } from "./remark-excerpt"
|
||||
import { rehypeTable } from "./rehype-table"
|
||||
import { allowedBlockquoteAttrs, remarkCallout } from "./remark-callout"
|
||||
|
||||
export type MarkdownEnv = {
|
||||
excerpt: string
|
||||
@@ -16,19 +22,30 @@ export type Rendered = {
|
||||
}
|
||||
|
||||
export const renderPageContent = async (content: string): Promise<Rendered> => {
|
||||
const md = new Markdown({
|
||||
html: false,
|
||||
linkify: true,
|
||||
})
|
||||
|
||||
md.use(pluginImage)
|
||||
md.use(pluginCodeBlock)
|
||||
md.use(pluginExcerpt)
|
||||
md.use(pluginTable)
|
||||
md.use(pluginTaskList)
|
||||
|
||||
const env: MarkdownEnv = { excerpt: "", __internal: {} }
|
||||
const contentHTML = md.render(content, env)
|
||||
|
||||
const result = await unified()
|
||||
.use(remarkParse)
|
||||
.use(remarkGfm, {})
|
||||
.use(remarkExcerpt, { env })
|
||||
.use(remarkCallout)
|
||||
.use(remarkRehype, { allowDangerousHtml: true })
|
||||
.use(rehypeRaw)
|
||||
.use(rehypeImage)
|
||||
.use(rehypeSanitize, {
|
||||
...defaultSchema,
|
||||
attributes: {
|
||||
...defaultSchema.attributes,
|
||||
code: [["className"]],
|
||||
blockquote: allowedBlockquoteAttrs,
|
||||
},
|
||||
})
|
||||
.use(rehypePrism)
|
||||
.use(rehypeTable)
|
||||
.use(rehypeStringify)
|
||||
.process(content)
|
||||
|
||||
const contentHTML = result.toString()
|
||||
|
||||
return { contentHTML, excerpt: env.excerpt }
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import Markdown from "markdown-it"
|
||||
import Prism from "prismjs"
|
||||
import loadLanguages from "prismjs/components/index"
|
||||
|
||||
export const pluginCodeBlock = (md: Markdown) => {
|
||||
const highlight = (code: string, lang: string) => {
|
||||
if (lang === "vue" || lang === "svelte") {
|
||||
lang = "html"
|
||||
}
|
||||
loadLanguages(lang)
|
||||
const grammer = Prism.languages[lang]
|
||||
const html = grammer
|
||||
? `<pre><code>${Prism.highlight(code, grammer, lang)}</code></pre>`
|
||||
: `<pre><code>${md.utils.escapeHtml(code)}</code></pre>`
|
||||
|
||||
return html
|
||||
}
|
||||
|
||||
md.renderer.rules.fence = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx]
|
||||
const code = highlight(token.content, token.info)
|
||||
return `<div class="code" data-lang="${token.info}">${code}</div>`
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import MarkdownIt from "markdown-it"
|
||||
import { stripHTML } from "~/lib/utils"
|
||||
import { MarkdownEnv } from "."
|
||||
|
||||
export const pluginExcerpt = (md: MarkdownIt) => {
|
||||
md.renderer.rules.paragraph_close = (
|
||||
tokens,
|
||||
idx,
|
||||
options,
|
||||
env: MarkdownEnv,
|
||||
self
|
||||
) => {
|
||||
if (!env.__internal.excerpted) {
|
||||
env.__internal.excerpted = true
|
||||
let startIndex = 0
|
||||
for (const [index, token] of tokens.entries()) {
|
||||
if (token.type === "paragraph_open") {
|
||||
startIndex = index
|
||||
break
|
||||
}
|
||||
}
|
||||
env.excerpt = stripHTML(
|
||||
self.render(tokens.slice(startIndex, idx + 1), options, env)
|
||||
)
|
||||
}
|
||||
|
||||
return self.renderToken(tokens, idx, options)
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import Markdown from "markdown-it"
|
||||
import { getUserContentsUrl } from "~/lib/user-contents"
|
||||
|
||||
const isExternLink = (url: string) => /^https?:\/\//.test(url)
|
||||
|
||||
export const pluginImage = (md: Markdown) => {
|
||||
const imageRule = md.renderer.rules.image!
|
||||
md.renderer.rules.image = (tokens, idx, options, env, self) => {
|
||||
const token = tokens[idx]
|
||||
const url = token.attrGet("src")
|
||||
|
||||
if (!url) {
|
||||
return ""
|
||||
}
|
||||
|
||||
if (isExternLink(url)) {
|
||||
if (!url.startsWith("https:")) {
|
||||
throw new Error(`External image url must start with https`)
|
||||
}
|
||||
return imageRule(tokens, idx, options, env, self)
|
||||
}
|
||||
|
||||
token.attrSet("src", getUserContentsUrl(url))
|
||||
return imageRule(tokens, idx, options, env, self)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import MarkdownIt from "markdown-it"
|
||||
|
||||
export const pluginTable = (md: MarkdownIt) => {
|
||||
md.renderer.rules.table_open = (tokens, idx, options, env, self) => {
|
||||
return `<div class="table-wrapper">${self.renderToken(
|
||||
tokens,
|
||||
idx,
|
||||
options
|
||||
)}`
|
||||
}
|
||||
md.renderer.rules.table_close = (tokens, idx, options, env, self) => {
|
||||
return `${self.renderToken(tokens, idx, options)}</div>`
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import MarkdownIt from "markdown-it"
|
||||
import Token from "markdown-it/lib/token"
|
||||
|
||||
export const pluginTaskList = (md: MarkdownIt, options?: any) => {
|
||||
options = Object.assign(
|
||||
{
|
||||
disabled: true,
|
||||
divWrap: false,
|
||||
divClass: "checkbox",
|
||||
idPrefix: "cbx_",
|
||||
ulClass: "task-list",
|
||||
liClass: "task-list-item",
|
||||
},
|
||||
options,
|
||||
)
|
||||
md.core.ruler.after("inline", "github-task-lists", (state) => {
|
||||
const { tokens } = state
|
||||
let lastId = 0
|
||||
for (let i = 2; i < tokens.length; i++) {
|
||||
if (isTodoItem(tokens, i)) {
|
||||
todoify(tokens[i], `${lastId}`, options, state.Token)
|
||||
lastId += 1
|
||||
const token = tokens[i - 2]
|
||||
token.attrSet("class", options.liClass)
|
||||
const parentTokenIndex = getParentTokenIndex(tokens, i - 2)
|
||||
const parentToken = tokens[parentTokenIndex]
|
||||
if (parentToken) {
|
||||
parentToken.attrSet("class", options.ulClass)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function getParentTokenIndex(tokens: Token[], index: number) {
|
||||
const targetLevel = tokens[index].level - 1
|
||||
for (let i = index - 1; i >= 0; i--) {
|
||||
if (tokens[i].level === targetLevel) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
return -1
|
||||
}
|
||||
|
||||
function isTodoItem(tokens: Token[], index: number) {
|
||||
return (
|
||||
isInline(tokens[index]) &&
|
||||
isParagraph(tokens[index - 1]) &&
|
||||
isListItem(tokens[index - 2]) &&
|
||||
startsWithTodoMarkdown(tokens[index])
|
||||
)
|
||||
}
|
||||
|
||||
function todoify(
|
||||
token: Token,
|
||||
lastId: string,
|
||||
options: any,
|
||||
TokenConstructor: typeof Token,
|
||||
) {
|
||||
const id = `${options.idPrefix}${lastId}`
|
||||
token.children![0].content = token.children![0].content.slice(3)
|
||||
// label
|
||||
token.children!.unshift(beginLabel(id, TokenConstructor))
|
||||
token.children!.push(endLabel(TokenConstructor))
|
||||
// checkbox
|
||||
token.children!.unshift(makeCheckbox(token, id, options, TokenConstructor))
|
||||
if (options.divWrap) {
|
||||
token.children!.unshift(beginWrap(options, TokenConstructor))
|
||||
token.children!.push(endWrap(TokenConstructor))
|
||||
}
|
||||
}
|
||||
|
||||
function makeCheckbox(
|
||||
token: Token,
|
||||
id: string,
|
||||
options: any,
|
||||
TokenConstructor: typeof Token,
|
||||
) {
|
||||
const checkbox = new TokenConstructor("checkbox_input", "input", 0)
|
||||
checkbox.attrs = [
|
||||
["type", "checkbox"],
|
||||
["id", id],
|
||||
]
|
||||
const checked = /^\[[xX]\][ \u00A0]/.test(token.content) // if token.content starts with '[x] ' or '[X] '
|
||||
if (checked === true) {
|
||||
checkbox.attrs.push(["checked", "true"])
|
||||
}
|
||||
|
||||
if (options.disabled === true) {
|
||||
checkbox.attrs.push(["disabled", "true"])
|
||||
}
|
||||
|
||||
return checkbox
|
||||
}
|
||||
|
||||
function beginLabel(id: string, TokenConstructor: typeof Token) {
|
||||
const label = new TokenConstructor("label_open", "label", 1)
|
||||
label.attrs = [["for", id]]
|
||||
return label
|
||||
}
|
||||
|
||||
function endLabel(TokenConstructor: typeof Token) {
|
||||
return new TokenConstructor("label_close", "label", -1)
|
||||
}
|
||||
|
||||
// these next two functions are kind of hacky; probably should really be a
|
||||
// true block-level token with .tag=='label'
|
||||
function beginWrap(options: any, TokenConstructor: typeof Token) {
|
||||
const token = new TokenConstructor("checkbox_open", "div", 0)
|
||||
token.attrs = [["class", options.divClass]]
|
||||
return token
|
||||
}
|
||||
|
||||
function endWrap(TokenConstructor: typeof Token) {
|
||||
const token = new TokenConstructor("checkbox_close", "div", -1)
|
||||
// token.content = '</label>';
|
||||
return token
|
||||
}
|
||||
|
||||
function isInline(token: Token) {
|
||||
return token.type === "inline"
|
||||
}
|
||||
|
||||
function isParagraph(token: Token) {
|
||||
return token.type === "paragraph_open"
|
||||
}
|
||||
|
||||
function isListItem(token: Token) {
|
||||
return token.type === "list_item_open"
|
||||
}
|
||||
|
||||
function startsWithTodoMarkdown(token: Token) {
|
||||
// The leading whitespace in a list item (token.content) is already trimmed off by markdown-it.
|
||||
// The regex below checks for '[ ] ' or '[x] ' or '[X] ' at the start of the string token.content,
|
||||
// where the space is either a normal space or a non-breaking space (character 160 = \u00A0).
|
||||
return /^\[[xX \u00A0]\][ \u00A0]/.test(token.content)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Root } from "rehype-raw"
|
||||
import { Plugin } from "unified"
|
||||
import { visit } from "unist-util-visit"
|
||||
import { getUserContentsUrl } from "~/lib/user-contents"
|
||||
|
||||
const isExternLink = (url: string) => /^https?:\/\//.test(url)
|
||||
|
||||
export const rehypeImage: Plugin<Array<void>, Root> = () => {
|
||||
return (tree) => {
|
||||
visit(tree, { tagName: "img" }, (node) => {
|
||||
if (!node.properties) return
|
||||
|
||||
const url = node.properties.src
|
||||
|
||||
if (!url || typeof url !== "string") {
|
||||
return
|
||||
}
|
||||
|
||||
if (isExternLink(url)) {
|
||||
if (!url.startsWith("https:")) {
|
||||
throw new Error(`External image url must start with https`)
|
||||
}
|
||||
}
|
||||
|
||||
node.properties.src = getUserContentsUrl(url)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Plugin } from "unified"
|
||||
import { Root } from "rehype-raw"
|
||||
import { visit } from "unist-util-visit"
|
||||
|
||||
export const rehypeTable: Plugin<Array<void>, Root> = () => (tree) => {
|
||||
visit(tree, { tagName: "table" }, (node, i, parent) => {
|
||||
if (parent) {
|
||||
parent.children[i!] = {
|
||||
type: "element",
|
||||
tagName: "div",
|
||||
properties: { className: "table-wrapper" },
|
||||
children: [node],
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Plugin } from "unified"
|
||||
import { Root } from "remark-gfm"
|
||||
import { visit } from "unist-util-visit"
|
||||
|
||||
const CALLOUT_RE = /^(TIP|WARN|SUCCESS|DANGER):(\n|$)/
|
||||
|
||||
export const remarkCallout: Plugin<Array<void>, Root> = () => (tree) => {
|
||||
visit(tree, { type: "blockquote" }, (node, index, parent) => {
|
||||
if (node.type !== "blockquote") return
|
||||
|
||||
const firstChild = node.children[0]
|
||||
if (firstChild.type === "paragraph") {
|
||||
const paragraphFirstChild = firstChild.children[0]
|
||||
if (
|
||||
paragraphFirstChild.type === "text" &&
|
||||
CALLOUT_RE.test(paragraphFirstChild.value)
|
||||
) {
|
||||
const type = paragraphFirstChild.value.match(CALLOUT_RE)![1]
|
||||
const newValue = paragraphFirstChild.value.replace(CALLOUT_RE, "")
|
||||
// In the following case `newValue` will be empty empty
|
||||
// We should remove the paragraph
|
||||
// > TIP:
|
||||
// >
|
||||
// > some tip
|
||||
if (!newValue) {
|
||||
node.children.splice(0, 1)
|
||||
}
|
||||
paragraphFirstChild.value = newValue
|
||||
const className = `callout callout-${type.toLowerCase()}`
|
||||
node.data = {
|
||||
...node.data,
|
||||
hProperties: {
|
||||
class: className,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const allowedBlockquoteAttrs: Array<[string, ...string[]]> = [
|
||||
[
|
||||
"className",
|
||||
"callout",
|
||||
"callout-tip",
|
||||
"callout-warn",
|
||||
"callout-success",
|
||||
"callout-danger",
|
||||
],
|
||||
]
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Plugin } from "unified"
|
||||
import { MarkdownEnv } from "."
|
||||
import { Root } from "remark-gfm"
|
||||
import { toString as mdAstToString } from "mdast-util-to-string"
|
||||
|
||||
export const remarkExcerpt: Plugin<Array<{ env: MarkdownEnv }>, Root> =
|
||||
({ env }) =>
|
||||
(tree) => {
|
||||
for (const node of tree.children) {
|
||||
if (node.type === "paragraph") {
|
||||
env.excerpt = mdAstToString(node)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user