Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix(markdown): open preview links in new tab (#20537)

boojackcccf0c2fb8e9
diff --git a/frontend/src/react/components/MarkdownEditor/MarkdownEditor.test.tsx b/frontend/src/react/components/MarkdownEditor/MarkdownEditor.test.tsx
new file mode 100644
index 0000000000..218bb3ff5e
--- /dev/null
+++ b/frontend/src/react/components/MarkdownEditor/MarkdownEditor.test.tsx
@@ -0,0 +1,54 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, test, vi } from "vitest";
+import { MarkdownEditor } from "./MarkdownEditor";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ return {
+ container,
+ render: () => {
+ act(() => {
+ root.render(element);
+ });
+ },
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+describe("MarkdownEditor", () => {
+ test("opens rendered markdown links in a new tab", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <MarkdownEditor
+ content="[docs](https://docs.bytebase.com) https://example.com"
+ mode="preview"
+ />
+ );
+
+ render();
+
+ const links = Array.from(container.querySelectorAll("a"));
+ expect(links).toHaveLength(2);
+ for (const link of links) {
+ expect(link.getAttribute("target")).toBe("_blank");
+ expect(link.getAttribute("rel")).toBe("noopener noreferrer");
+ }
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx b/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx
index a15110c960..ea45d89928 100644
--- a/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx
+++ b/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx
@@ -57,7 +57,7 @@ export function MarkdownEditor({
}
const source = transform ? transform(content) : content;
const rendered = markdown.render(source);
- return DOMPurify.sanitize(rendered);
+ return sanitizePreviewHtml(rendered);
}, [content, transform]);
useEffect(() => {
@@ -224,6 +224,17 @@ export function MarkdownEditor({
);
}
+function sanitizePreviewHtml(html: string) {
+ const sanitized = DOMPurify.sanitize(html);
+ const template = document.createElement("template");
+ template.innerHTML = sanitized;
+ for (const link of template.content.querySelectorAll("a")) {
+ link.setAttribute("target", "_blank");
+ link.setAttribute("rel", "noopener noreferrer");
+ }
+ return template.innerHTML;
+}
+
function PreviewBody({ className, html }: { className: string; html: string }) {
const { t } = useTranslation();
return (