Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions packages/core/src/api/exporters/markdown/htmlToMarkdown.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { parseLinkFigure } from "../../../blocks/File/helpers/parse/parseLinkFigure.js";
import { parseAutolinkLiteral } from "../../parsers/markdown/autolink.js";
import { wrapWithDelimiter } from "./wrapWithDelimiter.js";

Expand Down Expand Up @@ -626,14 +627,24 @@ function serializeFigure(el: HTMLElement, ctx: SerializeContext): string {
ctx,
);
}
const linkFigure = parseLinkFigure(el);
if (linkFigure) {
return serializeMediaFigure(
"a",
linkFigure.url,
linkFigure.name || linkFigure.url,
linkFigure.caption,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
ctx,
);
}
if (link) {
return serializeBlockLink(link as HTMLElement, ctx);
}
return "";
}

function serializeMediaFigure(
kind: "img" | "video" | "audio",
kind: "img" | "video" | "audio" | "a",
src: string,
descriptor: string,
captionText: string,
Expand All @@ -644,7 +655,7 @@ function serializeMediaFigure(
}

// No caption + has a markdown shorthand → use it.
if (!captionText && kind !== "audio") {
if (!captionText && (kind === "img" || kind === "video")) {
return ctx.indent + `![${descriptor}](${src})\n\n`;
}

Expand All @@ -664,10 +675,14 @@ function serializeMediaFigure(
const tag =
kind === "img"
? `<img${descAttr} src="${escapeHtmlAttr(src)}">`
: `<${kind} src="${escapeHtmlAttr(src)}"${descAttr} controls></${kind}>`;
: kind === "a"
? `<a href="${escapeHtmlAttr(src)}">${escapeHtmlText(descriptor)}</a>`
: `<${kind} src="${escapeHtmlAttr(src)}"${descAttr} controls></${kind}>`;

// A line feed is a character reference, so that the figure stays on one
// line: an empty line in the caption would end the HTML block in markdown.
const captionPart = captionText
? `<figcaption>${escapeHtmlText(captionText)}</figcaption>`
? `<figcaption>${escapeHtmlText(captionText).replace(/\n/g, "&#10;")}</figcaption>`
: "";
return ctx.indent + `<figure>${tag}${captionPart}</figure>\n\n`;
}
Expand Down
181 changes: 181 additions & 0 deletions packages/core/src/blocks/File/block.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, expect } from "vite-plus/test";

import { cleanHTMLToMarkdown } from "../../api/exporters/markdown/markdownExporter.js";

describe("external HTML of a file block without a caption", () => {
// The export was a link alone. A link is inline content: the HTML parse
// joined two adjacent links into one paragraph.
Expand All @@ -25,3 +27,182 @@ describe("external HTML of a file block without a caption", () => {
]);
});
});

describe("external HTML of a file block with a caption", () => {
const url = "https://example.com/a.pdf";
const htmlCharacters = {
url: `${url}?a="1"&b=<2>`,
name: `<b>a</b> & "b".pdf`,
caption: `<i>Text</i> & "more"`,
};

// The export was a `div` with the link and the caption in a paragraph. The
// HTML parse and the markdown parse read that as two paragraphs.
it.for([
{ format: "HTML", title: "a name", props: { name: "a.pdf" } },
{ format: "HTML", title: "no name", props: { name: "" } },
{ format: "HTML", title: "HTML characters", props: htmlCharacters },
{ format: "markdown", title: "a name", props: { name: "a.pdf" } },
{ format: "markdown", title: "no name", props: { name: "" } },
{ format: "markdown", title: "HTML characters", props: htmlCharacters },
] as const)(
"reads back as the same block from $format, with $title",
async ({ format, props: caseProps }, { setupEditor }) => {
const { editor } = await setupEditor();
const props = { url, caption: "Text", ...caseProps };

const blocks =
format === "HTML"
? editor.tryParseHTMLToBlocks(
editor.blocksToHTMLLossy([{ type: "file", props }]),
)
: editor.tryParseMarkdownToBlocks(
editor.blocksToMarkdownLossy([{ type: "file", props }]),
);

expect(blocks).toMatchObject([{ type: "file", props }]);
},
);

it.for([
{
figure: "white space and a comment",
html: `<figure>
<a href="a.pdf">
Name
</a>
<!-- A comment -->
<figcaption>Text</figcaption>
</figure>`,
props: { url: "a.pdf", name: "Name", caption: "Text" },
},
{
figure: "a background color",
html: `<figure style="background-color: red"><a href="a.pdf">Name</a><figcaption>Text</figcaption></figure>`,
props: {
url: "a.pdf",
name: "Name",
caption: "Text",
backgroundColor: "red",
},
},
{
figure: "the URL as link text on its own line",
html: `<figure><a href="${url}">
${url}
</a><figcaption>Text</figcaption></figure>`,
props: { url, name: "", caption: "Text" },
},
])(
"reads a figure with $figure as a file block",
async ({ html, props }, { setupEditor }) => {
const { editor } = await setupEditor();

expect(editor.tryParseHTMLToBlocks(html)).toMatchObject([
{ type: "file", props },
]);
},
);

// Only the form that the export writes is a file block. Each other figure
// gives the same blocks and the same markdown as before.
it.for([
{
figure: "a link that wraps an image",
html: `<figure><a href="big.jpg"><img src="small.jpg"></a><figcaption>Text</figcaption></figure>`,
types: ["image"],
markdown: `<figure><img src="small.jpg"><figcaption>Text</figcaption></figure>`,
},
{
figure: "a link without a caption",
html: `<figure><a href="a.pdf">a</a></figure>`,
types: ["paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "a link and an empty caption",
html: `<figure><a href="a.pdf">a</a><figcaption></figcaption></figure>`,
types: ["paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "a link without a URL",
html: `<figure><a name="a">a</a><figcaption>Text</figcaption></figure>`,
types: ["paragraph", "paragraph"],
markdown: "a",
},
{
figure: "a link and more text",
html: `<figure><a href="a.pdf">a</a> and more text<figcaption>Text</figcaption></figure>`,
types: ["paragraph", "paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "two links",
html: `<figure><a href="a.pdf">a</a><a href="b.pdf">b</a><figcaption>Text</figcaption></figure>`,
types: ["paragraph", "paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "the caption before the link",
html: `<figure><figcaption>Text</figcaption><a href="a.pdf">a</a></figure>`,
types: ["paragraph", "paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "a link in a paragraph",
html: `<figure><p>See <a href="a.pdf">a</a> here</p><figcaption>Text</figcaption></figure>`,
types: ["paragraph", "paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "paragraphs in the link",
html: `<figure><a href="a.pdf"><p>One</p><p>Two</p></a><figcaption>Text</figcaption></figure>`,
types: ["paragraph", "paragraph", "paragraph"],
markdown: "[OneTwo](a.pdf)",
},
{
figure: "a link in the caption",
html: `<figure><a href="a.pdf">a</a><figcaption>See <a href="b.pdf">b</a></figcaption></figure>`,
types: ["paragraph", "paragraph"],
markdown: "[a](a.pdf)",
},
{
figure: "a quote, and a link in the caption",
html: `<figure><blockquote>Quote</blockquote><figcaption>By <a href="b.pdf">b</a></figcaption></figure>`,
types: ["quote", "paragraph"],
markdown: "[b](b.pdf)",
},
])(
"does not read a figure with $figure as a file block",
async ({ html, types, markdown }, { setupEditor }) => {
const { editor } = await setupEditor();

expect(
editor.tryParseHTMLToBlocks(html).map((block) => block.type),
).toEqual(types);
expect(cleanHTMLToMarkdown(html)).toBe(`${markdown}\n`);
},
);
});

describe("markdown of a figure with a caption", () => {
// The caption is raw HTML in markdown. An empty line in it ended the HTML
// block: the rest of the caption became a paragraph.
it.for(["file", "image"] as const)(
"keeps a %s block as one block, with an empty line and HTML characters in the caption",
async (type, { setupEditor }) => {
const { editor } = await setupEditor();
const url = "https://example.com/a.png";

const markdown = editor.blocksToMarkdownLossy([
{ type, props: { url, caption: "One\n\n<b>Two</b> & three" } },
]);

// The HTML parse reads a line feed in text as a space.
expect(editor.tryParseMarkdownToBlocks(markdown)).toMatchObject([
{ type, props: { url, caption: "One <b>Two</b> & three" } },
]);
},
);
});
8 changes: 8 additions & 0 deletions packages/core/src/blocks/File/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createBlockConfig, createBlockSpec } from "../../schema/index.js";
import { defaultProps, parseDefaultProps } from "../defaultProps.js";
import { parseEmbedElement } from "./helpers/parse/parseEmbedElement.js";
import { parseFigureElement } from "./helpers/parse/parseFigureElement.js";
import { parseLinkFigure } from "./helpers/parse/parseLinkFigure.js";
import { createFileBlockWrapper } from "./helpers/render/createFileBlockWrapper.js";
import { createLinkWithCaption } from "./helpers/toExternalHTML/createLinkWithCaption.js";

Expand Down Expand Up @@ -46,6 +47,13 @@ export const fileParse = () => (element: HTMLElement) => {
}

if (element.tagName === "FIGURE") {
const linkFigure = parseLinkFigure(element);
if (linkFigure) {
const { backgroundColor } = parseDefaultProps(element);

return { ...linkFigure, backgroundColor };
}

const parsedFigure = parseFigureElement(element, "embed");
if (!parsedFigure) {
return undefined;
Expand Down
37 changes: 37 additions & 0 deletions packages/core/src/blocks/File/helpers/parse/parseLinkFigure.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { parseFigureElement } from "./parseFigureElement.js";

/**
* Reads the figure that `createLinkWithCaption` writes: a link to the file,
* then a caption, each with only text in it, and no other content. Each other
* figure gives `undefined`. A figure without a caption is one of these: the
* export without a caption is a link in a paragraph, which is not a file
* block.
*/
export function parseLinkFigure(figure: HTMLElement) {
const parsedFigure = parseFigureElement(figure, "a");
const url = parsedFigure?.targetElement.getAttribute("href");
if (
!parsedFigure?.caption ||
!url ||
figure.children.length !== 2 ||
figure.lastElementChild?.tagName !== "FIGCAPTION" ||
// An element in the link or in the caption.
figure.querySelector(":scope > * > *") ||
// Text next to them. White space and comments do not count.
Array.from(figure.childNodes).some(
(node) =>
node.nodeType === 3 /* Node.TEXT_NODE */ && node.textContent?.trim(),
)
) {
return undefined;
}

// The export writes the URL as the link text of a block without a name.
const name = parsedFigure.targetElement.textContent.trim();

return {
url,
name: name === url ? "" : name,
caption: parsedFigure.caption,
};
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { createFigureWithCaption } from "./createFigureWithCaption.js";

/**
* Puts the link to the file of a block into a block-level element. With a
* caption, this is a `div` with the link and the caption in a paragraph.
* Without a caption, this is a paragraph. A link alone is inline content: the
* HTML parse joins two adjacent links into one paragraph.
* caption, this is a figure, as for an image with a caption. Without a
* caption, this is a paragraph. A link alone is inline content: the HTML
* parse joins two adjacent links into one paragraph.
*/
export const createLinkWithCaption = (
element: HTMLElement,
Expand All @@ -17,14 +19,5 @@ export const createLinkWithCaption = (
};
}

const wrapper = document.createElement("div");
const fileCaption = document.createElement("p");
fileCaption.textContent = caption;

wrapper.appendChild(element);
wrapper.appendChild(fileCaption);

return {
dom: wrapper,
};
return createFigureWithCaption(element, caption);
};
32 changes: 32 additions & 0 deletions packages/react/src/blocks/File/block.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,35 @@ describe("external HTML of a React file block without a caption", () => {
]);
});
});

describe("external HTML of a React file block with a caption", () => {
// The export was a `div` with the link and the caption in a paragraph. The
// HTML parse and the markdown parse read that as two paragraphs.
it.for([
{ format: "HTML", name: "a.pdf" },
{ format: "HTML", name: "" },
{ format: "markdown", name: "a.pdf" },
{ format: "markdown", name: "" },
] as const)(
"reads back as the same block from $format, with the name '$name'",
async ({ format, name }, { setupEditor }) => {
const { editor } = await setupEditor({
schema: BlockNoteSchema.create().extend({
blockSpecs: { file: ReactFileBlock() },
}),
});
const props = { url: "https://example.com/a.pdf", name, caption: "Text" };

const blocks =
format === "HTML"
? editor.tryParseHTMLToBlocks(
editor.blocksToHTMLLossy([{ type: "file", props }]),
)
: editor.tryParseMarkdownToBlocks(
editor.blocksToMarkdownLossy([{ type: "file", props }]),
);

expect(blocks).toMatchObject([{ type: "file", props }]);
},
);
});
Loading
Loading