Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

fix(editor): keep unsupported markdown, raw HTML and special characters intact

Matt Roberts839c87333de9
diff --git a/public/components/common/form/CommentEditor.markdown.spec.ts b/public/components/common/form/CommentEditor.markdown.spec.ts
index d0f076c4e..dfc0ec12d 100644
--- a/public/components/common/form/CommentEditor.markdown.spec.ts
+++ b/public/components/common/form/CommentEditor.markdown.spec.ts
@@ -1,32 +1,71 @@
-import { Editor } from "@tiptap/core"
+import { Editor, JSONContent } from "@tiptap/core"
import StarterKit from "@tiptap/starter-kit"
import Link from "@tiptap/extension-link"
-import { Markdown } from "@tiptap/markdown"
import { CustomImage } from "./CustomImage"
import { CustomMention } from "./CustomMention"
+import { fiderMarkdown } from "./FiderMarkdown"
+import { RawMarkdown } from "./RawMarkdown"
+import * as markdown from "@fider/services/markdown"
+import { fiderAllowedSchemes } from "@fider/hooks"
-// Headless editor with the same extension set CommentEditor uses (minus UI-only bits).
-// This locks the markdown round-trip (markdown -> doc -> markdown) so the later engine
-// swap to @tiptap/markdown can be verified byte-for-byte against it.
-const makeEditor = () =>
+fiderAllowedSchemes.get = () => ""
+
+// Headless editor with the same markdown-relevant extensions CommentEditor uses (minus UI-only
+// bits like suggestions and placeholder). Locks the @tiptap/markdown round-trip
+// (markdown -> doc -> markdown): stored content must come back byte-for-byte, including
+// content the schema can't represent, raw HTML and special characters.
+const makeEditor = (imageOptions: Parameters<typeof CustomImage.configure>[0] = {}) =>
new Editor({
extensions: [
StarterKit.configure({ link: false, underline: false }),
Link.configure({ openOnClick: true, autolink: true, defaultProtocol: "https" }),
- Markdown.configure({ markedOptions: { breaks: true, gfm: true } }),
+ fiderMarkdown(),
+ RawMarkdown,
CustomMention.configure({ HTMLAttributes: { class: "mention" } }),
- CustomImage.configure({ allowBase64: true }),
+ CustomImage.configure({ allowBase64: true, ...imageOptions }),
],
})
+const load = (md: string, editor = makeEditor()): Editor => {
+ editor.commands.setContent(md, { emitUpdate: false, contentType: "markdown" })
+ return editor
+}
+
const roundTrip = (md: string): string => {
+ const editor = load(md)
+ const out = editor.getMarkdown().trim()
+ editor.destroy()
+ return out
+}
+
+// Serialize a document built directly (as if typed in rich-text mode)
+const serialize = (content: JSONContent[]): string => {
const editor = makeEditor()
- editor.commands.setContent(md, { emitUpdate: false, contentType: "markdown" })
+ editor.commands.setContent({ type: "doc", content }, { emitUpdate: false })
const out = editor.getMarkdown().trim()
editor.destroy()
return out
}
+const paragraph = (text: string): JSONContent => ({ type: "paragraph", content: [{ type: "text", text }] })
+
+const nodesOfType = (editor: Editor, type: string): JSONContent[] => {
+ const found: JSONContent[] = []
+ const walk = (node: JSONContent) => {
+ if (node.type === type) found.push(node)
+ ;(node.content || []).forEach(walk)
+ }
+ walk(editor.getJSON())
+ return found
+}
+
+// Parse editor HTML the way the browser would and list the elements it creates.
+const elementsIn = (html: string): string[] => {
+ const container = document.createElement("div")
+ container.innerHTML = html
+ return Array.from(container.querySelectorAll("*")).map((e) => e.tagName.toLowerCase())
+}
+
describe("CommentEditor markdown round-trip (@tiptap/markdown)", () => {
const cases: Array<[string, string]> = [
["mention", "@[Jane Doe]"],
@@ -35,6 +74,7 @@ describe("CommentEditor markdown round-trip (@tiptap/markdown)", () => {
["fider image", "![](fider-image:attachments/zy0hBtqrjQki7M56p26AuAXljRoaNUSwZO6MOky5gnYm2nW1rsMmrp3dwhjGk7ok-aden.jpeg)"],
["fider image in text", "look ![](fider-image:attachments/abc-x.jpeg) here"],
["plain image", "![](http://demo.dev.fider.io:3000/images/100/28)"],
+ ["plain image with alt and title", '![alt](http://demo.dev.fider.io:3000/images/100/28 "title")'],
["bold", "**bold**"],
["italic", "*italic*"],
["strike", "~~struck~~"],
@@ -53,6 +93,22 @@ describe("CommentEditor markdown round-trip (@tiptap/markdown)", () => {
// so existing stored content (bare \n) is unaffected.
["hard breaks", "line one \nline two \nline three"],
["heading then text", "## Title\n\nSome body text."],
+ // Content the schema has no node for must survive untouched (it used to be deleted)
+ ["gfm table", "| a | b |\n| --- | --- |\n| 1 | 2 |"],
+ ["table between paragraphs", "Before\n\n| a |\n| - |\n| 1 |\n\nAfter"],
+ ["task list", "- [ ] task\n- [x] done"],
+ ["mixed task list", "- a\n- [ ] b"],
+ ["nested task list", "- a\n - [ ] nested\n- c"],
+ // Raw HTML is literal text, never markup
+ ["inline html", "<b>hi</b> <img src=x onerror=alert(1)>"],
+ ["block html", "<div>hi</div>"],
+ ["html comment", "<!-- note -->"],
+ // Special characters are stored as typed, not as HTML entities
+ ["ampersand and angle brackets", "AT&T > x < y"],
+ ["code keeps entity-like text", "`&lt;b&gt; & <i>`"],
+ // Only safe fider-image references become inline images; anything else is kept as-is
+ ["fider image with caption", "![caption](fider-image:attachments/abc.png)"],
+ ["fider image path traversal", "![caption](fider-image:../../api/v1/admin/x?y)"],
]
cases.forEach(([name, md]) => {
@@ -61,3 +117,86 @@ describe("CommentEditor markdown round-trip (@tiptap/markdown)", () => {
})
})
})
+
+describe("CommentEditor raw HTML (html: false)", () => {
+ test("typed HTML is loaded as literal text", () => {
+ const editor = load("<b>hi</b> <img src=x onerror=alert(1)>\n\n<div>block</div>")
+ expect(elementsIn(editor.getHTML())).toEqual(["p", "p"])
+ expect(editor.getText()).toEqual("<b>hi</b> <img src=x onerror=alert(1)>\n\n<div>block</div>")
+ editor.destroy()
+ })
+})
+
+describe("CommentEditor unsupported markdown", () => {
+ test("a table is kept as literal text in the editor", () => {
+ const editor = load("| a | b |\n| --- | --- |\n| 1 | 2 |")
+ expect(editor.getText()).toContain("| 1 | 2 |")
+ editor.destroy()
+ })
+
+ test("task-list checkbox state is kept", () => {
+ const editor = load("- [ ] task\n- [x] done")
+ expect(editor.getText()).toContain("[x] done")
+ editor.destroy()
+ })
+})
+
+describe("CommentEditor markdown serialization", () => {
+ test("special characters typed in rich-text mode are stored as typed", () => {
+ expect(serialize([paragraph("AT&T <b>bold?</b> a > b")])).toEqual("AT&T <b>bold?</b> a > b")
+ })
+
+ test("text that looks like a blockquote stays a paragraph", () => {
+ const md = serialize([paragraph("> not a quote")])
+ const editor = load(md)
+ expect(nodesOfType(editor, "blockquote")).toEqual([])
+ expect(editor.getText()).toEqual("> not a quote")
+ editor.destroy()
+ })
+})
+
+describe("CommentEditor fider images", () => {
+ const unsafe = ["![](fider-image:../../api/v1/admin/x)", "![caption](fider-image:../../api/v1/admin/x?y)", "![](fider-image:attachments/../x.png)"]
+
+ unsafe.forEach((md) => {
+ test(`does not become a fider image: ${md}`, () => {
+ const editor = load(md)
+ const images = nodesOfType(editor, "customImage")
+ images.forEach((img) => {
+ expect(img.attrs?.bkey).toBeNull()
+ expect(img.attrs?.src).not.toContain("/static/images/")
+ })
+ editor.destroy()
+ })
+ })
+
+ test("a pending (unsaved) upload is shown from its cached data, not /static/images", () => {
+ const bkey = "attachments/pending-image.png"
+ const onGetImageSrc = (key: string) => (key === bkey ? "data:image/png;base64,AAAA" : "")
+ const editor = load(`look ![](fider-image:${bkey}) and ![](fider-image:attachments/saved.png)`, makeEditor({ onGetImageSrc }))
+
+ const html = editor.getHTML()
+ expect(html).toContain('src="data:image/png;base64,AAAA"')
+ expect(html).toContain('src="/static/images/attachments/saved.png"')
+ expect(editor.getMarkdown().trim()).toEqual(`look ![](fider-image:${bkey}) and ![](fider-image:attachments/saved.png)`)
+ editor.destroy()
+ })
+})
+
+describe("CommentEditor and renderer agree on mentions", () => {
+ const inputs = ["@[Jane Doe]", "@[] and @[Jane Doe]", "@[a]b] c", "x @[Jane] y @[John Smith] z", "@[unclosed and @[Jane]"]
+
+ inputs.forEach((md) => {
+ test(`same mentions: ${md}`, () => {
+ const editor = load(md)
+ const editorLabels = nodesOfType(editor, "mention").map((m) => `@${m.attrs?.label}`)
+ editor.destroy()
+
+ const container = document.createElement("div")
+ container.innerHTML = markdown.full(md)
+ const rendererLabels = Array.from(container.querySelectorAll(".mention")).map((e) => e.textContent)
+
+ expect(editorLabels).toEqual(rendererLabels)
+ })
+ })
+})
diff --git a/public/components/common/form/CommentEditor.scss b/public/components/common/form/CommentEditor.scss
index 1495a8d25..e68274319 100644
--- a/public/components/common/form/CommentEditor.scss
+++ b/public/components/common/form/CommentEditor.scss
@@ -153,6 +153,14 @@
cursor: pointer;
}
+ // Markdown the editor has no rich-text node for (tables, task lists), kept as raw text
+ .c-editor-raw-markdown {
+ font-family: $font-code;
+ font-size: 0.875em;
+ white-space: pre-wrap;
+ margin: 0.5em 0;
+ }
+
.fider-inline-image {
max-width: 100%;
height: auto;
diff --git a/public/components/common/form/CommentEditor.spec.tsx b/public/components/common/form/CommentEditor.spec.tsx
new file mode 100644
index 000000000..0e89d62ac
--- /dev/null
+++ b/public/components/common/form/CommentEditor.spec.tsx
@@ -0,0 +1,51 @@
+import React from "react"
+import { fireEvent, render, screen, waitFor } from "@testing-library/react"
+import { Fider, FiderContext } from "@fider/services"
+import CommentEditor from "./CommentEditor"
+
+const fider = Fider.initialize({
+ settings: { environment: "development", oauth: [] },
+ tenant: { allowedSchemes: "" },
+ user: undefined,
+})
+
+const renderEditor = (props: Partial<React.ComponentProps<typeof CommentEditor>> = {}) =>
+ render(
+ <FiderContext.Provider value={fider}>
+ <CommentEditor field="description" disabled={false} initialValue="" {...props} />
+ </FiderContext.Provider>
+ )
+
+const editorImages = (container: HTMLElement) => Array.from(container.querySelectorAll<HTMLImageElement>(".ProseMirror img:not(.ProseMirror-separator)"))
+
+describe("<CommentEditor /> unsaved images", () => {
+ test("shows an image from a restored draft using its cached data", async () => {
+ const onGetImageSrc = (bkey: string) => (bkey === "attachments/draft.png" ? "AAAA" : "")
+ const { container } = renderEditor({ initialValue: "![](fider-image:attachments/draft.png)", onGetImageSrc })
+
+ await waitFor(() => expect(editorImages(container)).toHaveLength(1))
+ expect(editorImages(container)[0].getAttribute("src")).toEqual("data:image/jpeg;base64,AAAA")
+ })
+
+ test("keeps showing an image attached in this session after switching to markdown and back", async () => {
+ const onImageUploaded = jest.fn()
+ const { container } = renderEditor({ onImageUploaded })
+
+ const fileInput = container.querySelector<HTMLInputElement>('input[type="file"]')
+ expect(fileInput).not.toBeNull()
+ const file = new File(["hello"], "pic.png", { type: "image/png" })
+ fireEvent.change(fileInput as HTMLInputElement, { target: { files: [file] } })
+
+ await waitFor(() => expect(editorImages(container)).toHaveLength(1))
+ const dataUrl = editorImages(container)[0].getAttribute("src")
+ expect(dataUrl).toMatch(/^data:image\/png;base64,/)
+
+ fireEvent.click(screen.getByTitle("Markdown Mode"))
+ const textarea = screen.getByTestId<HTMLTextAreaElement>("markdown-textarea")
+ expect(textarea.value).toMatch(/^!\[\]\(fider-image:attachments\/[a-zA-Z0-9]+-pic\.png\)$/)
+
+ fireEvent.click(screen.getByTitle("Rich Text Mode"))
+ await waitFor(() => expect(editorImages(container)).toHaveLength(1))
+ expect(editorImages(container)[0].getAttribute("src")).toEqual(dataUrl)
+ })
+})
diff --git a/public/components/common/form/CommentEditor.tsx b/public/components/common/form/CommentEditor.tsx
index 70a9e77e1..15a3a73d9 100644
--- a/public/components/common/form/CommentEditor.tsx
+++ b/public/components/common/form/CommentEditor.tsx
@@ -3,7 +3,6 @@ import StarterKit from "@tiptap/starter-kit"
import Link from "@tiptap/extension-link"
import React, { useState, useRef, useEffect } from "react"
import { EditorContent, useEditor } from "@tiptap/react"
-import { Markdown } from "@tiptap/markdown"
import { Placeholder } from "@tiptap/extensions"
import { i18n } from "@lingui/core"
import { useAllowedProtocols } from "@fider/hooks"
@@ -28,6 +27,8 @@ import { fileToBase64 } from "@fider/services"
import { generateBkey } from "@fider/services/bkey"
import { ImageUpload } from "@fider/models"
import { CustomImage } from "./CustomImage"
+import { fiderMarkdown } from "./FiderMarkdown"
+import { RawMarkdown } from "./RawMarkdown"
import suggestion from "./suggestion"
import { CustomMention } from "./CustomMention"
@@ -256,6 +257,11 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {
// This avoids the async state update issue and prevents unnecessary re-renders
const documentImagesRef = useRef<Map<string, boolean>>(new Map())
+ // data: URLs of images attached in this editor session that aren't saved yet, by bkey. The
+ // markdown only holds ![](fider-image:<bkey>), so when it's loaded again (switching back from
+ // markdown mode) these are needed to show the image; the server doesn't have it yet.
+ const pendingImageSrcRef = useRef<Map<string, string>>(new Map())
+
// Content the editor is created with. Captured once — the editor instance is created a
// single time (useEditor deps below are empty) and lives for the component's lifetime, so
// switching editor modes must update content via commands rather than by recreating it.
@@ -421,11 +427,13 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {
// doc object. If the doc reference is unchanged after the insert, the transaction was
// dropped (e.g. dispatched into a destroyed view) and the node did not land.
const docBefore = editor.state.doc
+ const dataUrl = `data:${file.type};base64,${base64}`
+ pendingImageSrcRef.current.set(bkey, dataUrl)
editor
.chain()
.focus()
.setImage({
- src: `data:${file.type};base64,${base64}`,
+ src: dataUrl,
alt: file.name,
...({ bkey } as any),
})
@@ -502,7 +510,8 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {
rel: "noopener nofollow",
},
}),
- Markdown.configure({ markedOptions: { breaks: true, gfm: true } }),
+ fiderMarkdown(),
+ RawMarkdown,
CustomMention.configure({
HTMLAttributes: {
class: "mention",
@@ -512,17 +521,13 @@ const Tiptap: React.FunctionComponent<CommentEditorProps> = (props) => {
CustomImage.configure({
HTMLAttributes: {},
allowBase64: true,
- onImageUpload: (upload) => {
- if (props.onImageUploaded) {
- // Initialize other required properties
- props.onImageUploaded(upload)
- }
- },
- onImageRemove: (id) => {
- // This is called when an image is removed from the editor
- handleImageRemove(id)
- },
onGetImageSrc: (bkey) => {
+ // Attached in this session...
+ const pendingSrc = pendingImageSrcRef.current.get(bkey)
+ if (pendingSrc) {
+ return pendingSrc
+ }
+ // ...or in a restored draft (the parent's cached attachments)
if (props.onGetImageSrc) {
const imageSrc = props.onGetImageSrc(bkey)
if (imageSrc) {
diff --git a/public/components/common/form/CustomImage.ts b/public/components/common/form/CustomImage.ts
index f8b1918d3..0ac3f9b90 100644
--- a/public/components/common/form/CustomImage.ts
+++ b/public/components/common/form/CustomImage.ts
@@ -1,12 +1,12 @@
-import { ImageUpload } from "@fider/models"
import Image from "@tiptap/extension-image"
-import { JSONContent } from "@tiptap/core"
+import { JSONContent, mergeAttributes } from "@tiptap/core"
+import { fiderImageBkey, fiderImageMarkdown } from "@fider/services/markdownSyntax"
export interface CustomImageOptions {
HTMLAttributes?: Record<string, any>
allowBase64?: boolean
- onImageUpload?: (upload: ImageUpload) => void
- onImageRemove?: (bkey: string) => void
+ // Returns the src (e.g. a data: URL) of an image that was attached but isn't saved yet, or ""
+ // when the bkey refers to a stored image (served from /static/images/<bkey>).
onGetImageSrc?: (bkey: string) => string
}
@@ -27,8 +27,6 @@ export const CustomImage = Image.extend<CustomImageOptions>({
...this.parent?.(),
HTMLAttributes: {},
allowBase64: true,
- onImageUpload: undefined,
- onImageRemove: undefined,
onGetImageSrc: undefined,
}
},
@@ -63,26 +61,42 @@ export const CustomImage = Image.extend<CustomImageOptions>({
}
},
+ // Unsaved uploads are referenced by bkey in the markdown but don't exist on the server yet,
+ // so resolve their src when rendering. (parseMarkdown can't do this: `this` there is not the
+ // extension, so options aren't available.) Also show safe fider-image references that aren't
+ // editor images (e.g. ![caption](fider-image:...), see parseMarkdown) the way the renderer does.
+ renderHTML({ node, HTMLAttributes }) {
+ const bkey: string | undefined = node.attrs.bkey || fiderImageBkey(node.attrs.src)
+ const pendingSrc = bkey && this.options.onGetImageSrc ? this.options.onGetImageSrc(bkey) : ""
+ let src = HTMLAttributes.src
+ if (pendingSrc) {
+ src = pendingSrc
+ } else if (bkey && !node.attrs.bkey) {
+ src = `/static/images/${bkey}`
+ }
+ return ["img", mergeAttributes(this.options.HTMLAttributes || {}, HTMLAttributes, { src })]
+ },
+
// --- @tiptap/markdown integration (marked engine) ---
// Handle the standard marked "image" token, detecting Fider's ![](fider-image:<bkey>) syntax.
markdownTokenName: "image",
parseMarkdown(token: ImageToken): JSONContent {
// Note: `this` inside parseMarkdown is NOT the extension (no this.name / this.options),
- // so use a literal node type. Parsed content is already-stored images, which resolve
- // via the static path (the same fallback the editor used before); live base64 uploads
- // arrive through the setImage command, not markdown parsing.
- const href = token.href || ""
- if (href.startsWith("fider-image:")) {
- const imageId = href.substring("fider-image:".length)
+ // so use a literal node type.
+ // Only the exact form the editor writes, ![](fider-image:<safe bkey>), becomes an editor
+ // image (tracked as an attachment and written back without alt text). Anything else stays
+ // a plain image with its original src/alt so it round-trips unchanged.
+ const bkey = token.text ? undefined : fiderImageBkey(token.href)
+ if (bkey) {
return {
type: "customImage",
- attrs: { src: `/static/images/${imageId}`, alt: "", id: imageId, bkey: imageId },
+ attrs: { src: `/static/images/${bkey}`, alt: "", id: bkey, bkey },
}
}
return {
type: "customImage",
- attrs: { src: href, alt: token.text || "", id: null, bkey: null },
+ attrs: { src: token.href || "", alt: token.text || "", title: token.title || null, id: null, bkey: null },
}
},
@@ -90,9 +104,10 @@ export const CustomImage = Image.extend<CustomImageOptions>({
const attrs = node.attrs || {}
if (attrs.bkey || attrs.id) {
// Fider inline-image syntax; use bkey if available, otherwise id.
- return `![](fider-image:${attrs.bkey || attrs.id})`
+ return fiderImageMarkdown(attrs.bkey || attrs.id)
}
- return `![${attrs.alt || ""}](${attrs.src || ""})`
+ const title = attrs.title ? ` "${String(attrs.title).replace(/"/g, '\\"')}"` : ""
+ return `![${attrs.alt || ""}](${attrs.src || ""}${title})`
},
// Override the addImage command to include our custom attributes and handle uploads
diff --git a/public/components/common/form/CustomMention.ts b/public/components/common/form/CustomMention.ts
index cf89e31b1..5e2ba2ba1 100644
--- a/public/components/common/form/CustomMention.ts
+++ b/public/components/common/form/CustomMention.ts
@@ -1,19 +1,21 @@
import Mention from "@tiptap/extension-mention"
import { JSONContent, MarkdownToken } from "@tiptap/core"
+import { MENTION_AT_START, MENTION_START } from "@fider/services/markdownSyntax"
export const CustomMention = Mention.extend({
name: "mention",
// --- @tiptap/markdown integration (marked engine) ---
- // @[name] is non-standard markdown, so register a custom marked tokenizer for it.
+ // @[name] is non-standard markdown, so register a custom marked tokenizer for it. The grammar
+ // is shared with the display renderer (services/markdown.ts).
markdownTokenizer: {
name: "mention",
level: "inline" as const,
start(src: string) {
- return src.indexOf("@[")
+ return src.indexOf(MENTION_START)
},
tokenize(src: string): MarkdownToken | undefined {
- const match = /^@\[(.+?)\]/.exec(src)
+ const match = MENTION_AT_START.exec(src)
if (!match) {
return undefined
}
diff --git a/public/components/common/form/FiderMarkdown.ts b/public/components/common/form/FiderMarkdown.ts
new file mode 100644
index 000000000..b56cfd862
--- /dev/null
+++ b/public/components/common/form/FiderMarkdown.ts
@@ -0,0 +1,49 @@
+import { JSONContent } from "@tiptap/core"
+import { Markdown, MarkdownExtensionOptions, MarkdownExtensionStorage } from "@tiptap/markdown"
+import { Marked, marked } from "marked"
+
+// A marked instance for one editor. @tiptap/markdown defaults to the global `marked` singleton
+// and registers extension tokenizers (e.g. mentions) on it for every editor created, so each
+// editor gets its own instance instead.
+const createEditorMarked = (): Marked => {
+ const instance = new Marked({ gfm: true, breaks: true })
+ // Equivalent of the old tiptap-markdown `html: false`: raw HTML is never tokenized, so tags
+ // typed in markdown mode stay literal text instead of becoming rich-text nodes.
+ instance.use({
+ tokenizer: {
+ html: () => undefined,
+ tag: () => undefined,
+ },
+ })
+ return instance
+}
+
+// MarkdownManager internals used below (private in its type declarations).
+interface MarkdownManagerInternals {
+ encodeTextForMarkdown(text: string, node: JSONContent, parentNode?: JSONContent): string
+ escapeMarkdownSyntax(text: string): string
+}
+
+const FiderMarkdownExtension = Markdown.extend<MarkdownExtensionOptions, MarkdownExtensionStorage>({
+ onBeforeCreate(event) {
+ this.parent?.(event)
+
+ const manager = this.editor.markdown as unknown as MarkdownManagerInternals | undefined
+ if (!manager) return
+
+ // @tiptap/markdown HTML-encodes text when serializing (AT&T -> AT&amp;T, a > b -> a &gt; b),
+ // which would change the stored markdown. Raw HTML is never parsed (see above) and text
+ // tokens are entity-decoded on load, so store special characters as typed, like the old
+ // serializer did. Markdown syntax characters are still backslash-escaped, and a leading ">"
+ // is escaped so the text can't turn into a blockquote when loaded again.
+ const encode = manager.encodeTextForMarkdown.bind(manager)
+ manager.encodeTextForMarkdown = (text, node, parentNode) => {
+ // Code text (and text with nothing to escape) comes back unchanged: keep it as is.
+ if (encode(text, node, parentNode) === text) return text
+ return manager.escapeMarkdownSyntax(text).replace(/^(\s{0,3})>/, "$1\\>")
+ }
+ },
+})
+
+// The Markdown extension as configured for Fider's comment editor. Call once per editor.
+export const fiderMarkdown = () => FiderMarkdownExtension.configure({ marked: createEditorMarked() as unknown as typeof marked })
diff --git a/public/components/common/form/RawMarkdown.ts b/public/components/common/form/RawMarkdown.ts
new file mode 100644
index 000000000..b05a9542d
--- /dev/null
+++ b/public/components/common/form/RawMarkdown.ts
@@ -0,0 +1,60 @@
+import { Extension, JSONContent, MarkdownToken, mergeAttributes, Node } from "@tiptap/core"
+
+// Markdown the editor schema has no node for (GFM tables and task lists) would otherwise be
+// dropped when loaded, losing it on the next save. It is kept verbatim in a plain-text block
+// instead: shown (and editable) as the original markdown, and written back unchanged.
+
+const rawMarkdownNode = (raw: string): JSONContent => {
+ const text = raw.replace(/\s+$/, "")
+ return { type: "rawMarkdown", content: text ? [{ type: "text", text }] : [] }
+}
+
+// marked tokenizes "- [ ] task" as a list token whose items are flagged as tasks.
+const RawMarkdownTaskList = Extension.create({
+ name: "rawMarkdownTaskList",
+ // Runs before the bullet/ordered list handlers for the same "list" token.
+ priority: 500,
+
+ markdownTokenName: "list",
+
+ parseMarkdown(token: MarkdownToken) {
+ const items = (token.items as Array<{ task?: boolean }> | undefined) || []
+ if (!items.some((item) => item.task)) {
+ return [] // a normal list: an empty result passes it on to BulletList / OrderedList
+ }
+ return rawMarkdownNode(token.raw || "")
+ },
+})
+
+export const RawMarkdown = Node.create({
+ name: "rawMarkdown",
+ group: "block",
+ content: "text*",
+ marks: "",
+ code: true,
+ defining: true,
+ whitespace: "pre",
+
+ addExtensions() {
+ return [RawMarkdownTaskList]
+ },
+
+ parseHTML() {
+ return [{ tag: 'div[data-type="raw-markdown"]', preserveWhitespace: "full" as const }]
+ },
+
+ renderHTML({ HTMLAttributes }) {
+ return ["div", mergeAttributes(HTMLAttributes, { "data-type": "raw-markdown", class: "c-editor-raw-markdown" }), 0]
+ },
+
+ // Note: `this` inside parseMarkdown is NOT the extension, so the node type is a literal.
+ markdownTokenName: "table",
+
+ parseMarkdown(token: MarkdownToken) {
+ return rawMarkdownNode(token.raw || "")
+ },
+
+ renderMarkdown(node: JSONContent): string {
+ return (node.content || []).map((child) => child.text || "").join("")
+ },
+})