Skip to content

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

chore(frontend): render issue description as markdown (#10523)

Liu Jid81c2af508b6
diff --git a/frontend/src/assets/css/github-markdown-style.css b/frontend/src/assets/css/github-markdown-style.css
index c561a4bbc6..51c1fa9754 100644
--- a/frontend/src/assets/css/github-markdown-style.css
+++ b/frontend/src/assets/css/github-markdown-style.css
@@ -6,7 +6,7 @@
background-color: #ffffff;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial,
sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
- font-size: 16px;
+ font-size: 14px;
line-height: 1.5;
word-wrap: break-word;
}
@@ -23,8 +23,8 @@
.markdown-body h4:hover .anchor .octicon-link:before,
.markdown-body h5:hover .anchor .octicon-link:before,
.markdown-body h6:hover .anchor .octicon-link:before {
- width: 16px;
- height: 16px;
+ width: 14px;
+ height: 14px;
content: " ";
display: inline-block;
background-color: currentColor;
@@ -554,6 +554,10 @@
margin-bottom: 16px;
}
+.markdown-body p {
+ white-space: pre-wrap;
+}
+
.markdown-body blockquote > :first-child {
margin-top: 0;
}
diff --git a/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue b/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue
index 37a386d4b0..d6ba948c83 100644
--- a/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue
+++ b/frontend/src/components/IssueV1/components/ActivitySection/ActivityList.vue
@@ -109,7 +109,7 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch, watchEffect } from "vue";
import { useRoute } from "vue-router";
-import MarkdownEditor from "@/components/MarkdownEditor.vue";
+import MarkdownEditor from "@/components/MarkdownEditor";
import { IssueBuiltinFieldId } from "@/plugins";
import { useActivityV1Store, useCurrentUserV1, useIssueV1Store } from "@/store";
import { getLogId } from "@/store/modules/v1/common";
diff --git a/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue b/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue
index f89adbe356..dc447881d0 100644
--- a/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue
+++ b/frontend/src/components/IssueV1/components/DescriptionSection/DescriptionSection.vue
@@ -51,7 +51,12 @@
class="min-h-[3rem] max-h-[12rem] whitespace-pre-wrap px-[10px] py-[4.5px] text-sm"
>
<template v-if="issue.description">
- {{ issue.description }}
+ <iframe
+ v-if="issue.description"
+ ref="contentPreviewArea"
+ :srcdoc="renderedContent"
+ class="rounded-md w-full overflow-hidden"
+ />
</template>
<span v-else class="text-control-placeholder">
{{ $t("issue.add-some-description") }}
@@ -65,6 +70,7 @@
import { NInput, NButton } from "naive-ui";
import { computed, nextTick, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
+import { useRenderMarkdown } from "@/components/MarkdownEditor";
import { issueServiceClient } from "@/grpcweb";
import { emitWindowEvent } from "@/plugins";
import { pushNotification, useCurrentUserV1 } from "@/store";
@@ -85,6 +91,7 @@ type LocalState = {
const { t } = useI18n();
const { isCreating, issue } = useIssueContext();
const currentUser = useCurrentUserV1();
+const contentPreviewArea = ref<HTMLIFrameElement>();
const state = reactive<LocalState>({
isEditing: false,
@@ -172,6 +179,12 @@ const cancelEdit = () => {
state.isEditing = false;
};
+const { renderedContent } = useRenderMarkdown(
+ computed(() => issue.value.description),
+ contentPreviewArea,
+ computed(() => issue.value.projectEntity)
+);
+
// Reset the edit state after creating the issue.
watch(isCreating, (curr, prev) => {
if (!curr && prev) {
diff --git a/frontend/src/components/MarkdownEditor.vue b/frontend/src/components/MarkdownEditor/MarkdownEditor.vue
similarity index 82%
rename from frontend/src/components/MarkdownEditor.vue
rename to frontend/src/components/MarkdownEditor/MarkdownEditor.vue
index 94adaccc60..9cacae059c 100644
--- a/frontend/src/components/MarkdownEditor.vue
+++ b/frontend/src/components/MarkdownEditor/MarkdownEditor.vue
@@ -56,9 +56,8 @@
<iframe
v-if="state.showPreview"
ref="contentPreviewArea"
- :srcdoc="markdownContent"
+ :srcdoc="renderedContent"
class="rounded-md w-full overflow-hidden"
- @load="adjustIframe"
/>
<div v-else-if="mode === 'editor'" class="relative">
<textarea
@@ -105,41 +104,17 @@
</template>
<script lang="ts" setup>
-import hljs from "highlight.js/lib/core";
-import codeStyle from "highlight.js/styles/github.css?raw";
-import { computed, nextTick, ref, reactive, watch } from "vue";
+import { nextTick, ref, reactive, watch, toRef } from "vue";
import { useI18n } from "vue-i18n";
import { ComposedIssue, ComposedProject } from "@/types";
import { Task_Status } from "@/types/proto/v1/rollout_service";
import {
activeTaskInRollout,
- extractProjectResourceName,
isDatabaseRelatedIssue,
sizeToFit,
} from "@/utils";
-import markdownStyle from "../assets/css/github-markdown-style.css?raw";
-import IssueStatusIcon from "./IssueV1/components/IssueStatusIcon.vue";
-
-const [{ default: MarkdownIt }, { default: DOMPurify }] = await Promise.all([
- import("markdown-it"),
- import("dompurify"),
-]);
-
-const md = new MarkdownIt({
- html: true,
- linkify: true,
- highlight: function (code, lang) {
- if (lang && hljs.getLanguage(lang)) {
- try {
- return hljs.highlight(code, { language: lang }).value;
- } catch {
- return "";
- }
- }
-
- return ""; // use external default escaping
- },
-});
+import IssueStatusIcon from "../IssueV1/components/IssueStatusIcon.vue";
+import { useRenderMarkdown } from "./useRenderMarkdown";
interface LocalState {
showPreview: boolean;
@@ -178,47 +153,20 @@ watch(
(mode) => (state.showPreview = mode === "preview")
);
-const markdownPlaceholder = t("issue.comment-editor.nothing-to-preview");
-const markdownContent = computed(() => {
- if (!state.content) {
- return `<span>${markdownPlaceholder}</span>`;
- }
-
- // we met a valid #{issue_id} in which issue_id is an integer and >= 0
- // render a link to the issue
- const format = state.content
- .split(/(#\d+)\b/)
- .map((part) => {
- if (!part.startsWith("#")) {
- return part;
- }
- const id = parseInt(part.slice(1), 10);
- if (!Number.isNaN(id) && id > 0) {
- if (props.project) {
- // Here we assume that the referenced issue and the current issue are always
- // in the same project
- // if props.project is specified
- const path = `projects/${extractProjectResourceName(
- props.project.name
- )}/issues/${id}`;
- const url = `${window.location.origin}/${path}`;
- return `[${t("common.issue")} #${id}](${url})`;
- } else {
- return `[${t("common.issue")} #${id}](${
- window.location.origin
- }/issue/${id})`;
- }
- }
- return part;
- })
- .join("");
- return DOMPurify.sanitize(md.render(format));
-});
const contentTextArea = ref<HTMLTextAreaElement>();
const contentPreviewArea = ref<HTMLIFrameElement>();
const issuePanel = ref<HTMLDivElement>();
const filterIssueList = ref<ComposedIssue[]>([]);
+const { renderedContent } = useRenderMarkdown(
+ toRef(state, "content"),
+ contentPreviewArea,
+ toRef(props, "project"),
+ {
+ placeholder: `<span>${t("issue.comment-editor.nothing-to-preview")}</span>`,
+ }
+);
+
watch(
() => state.content,
(val) => emit("change", val)
@@ -246,35 +194,6 @@ watch(
}
);
-const adjustIframe = () => {
- if (!contentPreviewArea.value) return;
- if (contentPreviewArea.value.contentWindow) {
- contentPreviewArea.value.contentWindow.document.body.style.overflow =
- "hidden";
- }
-
- if (contentPreviewArea.value.contentDocument) {
- const cssLink = document.createElement("style");
- cssLink.append(codeStyle, markdownStyle);
- contentPreviewArea.value.contentDocument.head.append(cssLink);
- contentPreviewArea.value.contentDocument.body.className = "markdown-body";
-
- const links =
- contentPreviewArea.value.contentDocument.querySelectorAll("a");
- for (let i = 0; i < links.length; i++) {
- links[i].setAttribute("target", "_blank");
- }
- }
-
- nextTick(() => {
- if (!contentPreviewArea.value) return;
- const height =
- contentPreviewArea.value.contentDocument?.documentElement.offsetHeight ??
- 0;
- contentPreviewArea.value.style.height = `${height + 2}px`;
- });
-};
-
const keyboardHandler = (e: KeyboardEvent) => {
if (!contentTextArea.value) {
return;
diff --git a/frontend/src/components/MarkdownEditor/index.ts b/frontend/src/components/MarkdownEditor/index.ts
new file mode 100644
index 0000000000..42dec1c912
--- /dev/null
+++ b/frontend/src/components/MarkdownEditor/index.ts
@@ -0,0 +1,5 @@
+import MarkdownEditor from "./MarkdownEditor.vue";
+
+export default MarkdownEditor;
+
+export * from "./useRenderMarkdown";
diff --git a/frontend/src/components/MarkdownEditor/resize-observer.ts b/frontend/src/components/MarkdownEditor/resize-observer.ts
new file mode 100644
index 0000000000..e07b12f941
--- /dev/null
+++ b/frontend/src/components/MarkdownEditor/resize-observer.ts
@@ -0,0 +1,22 @@
+document.addEventListener("DOMContentLoaded", () => {
+ const populateBodySize = () => {
+ const rect = document.body.getBoundingClientRect();
+ window.parent.postMessage(
+ {
+ source: "bb.markdown.renderer",
+ key: window.name,
+ width: rect.width,
+ height: rect.height,
+ },
+ "*"
+ );
+ };
+
+ const ob = new ResizeObserver((entries) => {
+ const bodyEntry = entries.find((entry) => entry.target === document.body);
+ if (!bodyEntry) return;
+ populateBodySize();
+ });
+
+ ob.observe(document.body);
+});
diff --git a/frontend/src/components/MarkdownEditor/useRenderMarkdown.ts b/frontend/src/components/MarkdownEditor/useRenderMarkdown.ts
new file mode 100644
index 0000000000..a0582c6000
--- /dev/null
+++ b/frontend/src/components/MarkdownEditor/useRenderMarkdown.ts
@@ -0,0 +1,180 @@
+import { useEventListener } from "@vueuse/core";
+import { v1 as uuidv1 } from "uuid";
+import { Ref, computed, ref, unref, watchEffect } from "vue";
+import { useI18n } from "vue-i18n";
+import { ComposedProject, MaybeRef } from "@/types";
+import {
+ ExtractPromiseType,
+ extractProjectResourceName,
+ minmax,
+} from "@/utils";
+
+export type UseRenderMarkdownOptions = {
+ minHeight: number;
+ maxHeight: number;
+ placeholder: string;
+};
+
+const defaultOptions = (): UseRenderMarkdownOptions => ({
+ minHeight: 48 /* 3rem */,
+ maxHeight: 192 /* 12rem */,
+ placeholder: "",
+});
+
+export const useRenderMarkdown = (
+ markdown: MaybeRef<string>,
+ iframeRef: Ref<HTMLIFrameElement | undefined>,
+ projectRef: MaybeRef<ComposedProject | undefined> = ref(),
+ options: Partial<UseRenderMarkdownOptions> | undefined = undefined
+) => {
+ const windowName = uuidv1();
+ const mergedOptions = Object.assign(defaultOptions(), options);
+ const { t } = useI18n();
+ const request = Promise.all([
+ import("highlight.js/lib/core"),
+ import("highlight.js/styles/github.css?raw"),
+ import("@/assets/css/github-markdown-style.css?raw"),
+ import("markdown-it"),
+ import("dompurify"),
+ import("./resize-observer?raw"),
+ ]);
+ const modules = ref<ExtractPromiseType<typeof request>>();
+ request.then((dep) => {
+ modules.value = dep;
+ });
+ const deps = computed(() => {
+ if (!modules.value) return undefined;
+ const [
+ { default: hljs },
+ { default: codeStyle },
+ { default: markdownStyle },
+ { default: MarkdownIt },
+ { default: DOMPurify },
+ { default: resizeObserverScript },
+ ] = modules.value;
+ const md = new MarkdownIt({
+ html: true,
+ linkify: true,
+ highlight: function (code, lang) {
+ if (lang && hljs.getLanguage(lang)) {
+ try {
+ return hljs.highlight(code, { language: lang }).value;
+ } catch {
+ return "";
+ }
+ }
+
+ return ""; // use external default escaping
+ },
+ });
+
+ // See: https://github.com/cure53/DOMPurify/tree/main/demos#hook-to-open-all-links-in-a-new-window-link
+ // Add a hook to make all links open a new window
+ DOMPurify.addHook("afterSanitizeAttributes", function (node) {
+ // set all elements owning target to target=_blank
+ if ("target" in node) {
+ node.setAttribute("target", "_blank");
+ }
+ // set non-HTML/MathML links to xlink:show=new
+ if (
+ !node.hasAttribute("target") &&
+ (node.hasAttribute("xlink:href") || node.hasAttribute("href"))
+ ) {
+ node.setAttribute("xlink:show", "new");
+ }
+ });
+ return {
+ md,
+ codeStyle,
+ markdownStyle,
+ DOMPurify,
+ resizeObserverScript,
+ };
+ });
+
+ const rawRenderedContent = computed(() => {
+ if (!deps.value) return "";
+ if (!unref(markdown)) return mergedOptions.placeholder;
+
+ // we met a valid #{issue_id} in which issue_id is an integer and >= 0
+ // render a link to the issue
+ const formatted = unref(markdown)
+ .split(/(#\d+)\b/)
+ .map((part) => {
+ if (!part.startsWith("#")) {
+ return part;
+ }
+ const id = parseInt(part.slice(1), 10);
+ if (!Number.isNaN(id) && id > 0) {
+ const project = unref(projectRef);
+ if (project) {
+ // Here we assume that the referenced issue and the current issue are always
+ // in the same project
+ // if project is specified
+ const path = `projects/${extractProjectResourceName(
+ project.name
+ )}/issues/${id}`;
+ const url = `${window.location.origin}/${path}`;
+ return `[${t("common.issue")} #${id}](${url})`;
+ } else {
+ return `[${t("common.issue")} #${id}](${
+ window.location.origin
+ }/issue/${id})`;
+ }
+ }
+ return part;
+ })
+ .join("");
+ const { md, DOMPurify } = deps.value;
+ const rendered = md.render(formatted);
+ const html = DOMPurify.sanitize(rendered);
+ return html;
+ });
+
+ const renderedContent = computed(() => {
+ if (!deps.value) return "";
+ const content = rawRenderedContent.value;
+
+ const { codeStyle, markdownStyle, resizeObserverScript } = deps.value;
+
+ return [
+ `<head>`,
+ `<style>${codeStyle}</style>`,
+ `<style>${markdownStyle}</style>`,
+ `</head>`,
+ `<body style="overflow: auto;" class="markdown-body">`,
+ content,
+ `</body>`,
+ `<script>${resizeObserverScript}</script>`,
+ ].join("\n");
+ });
+
+ watchEffect(() => {
+ const iframe = iframeRef.value;
+ if (!iframe) return;
+ const win = iframe.contentWindow;
+ if (!win) return;
+ win.name = windowName;
+ });
+
+ useEventListener("message", (e: MessageEvent) => {
+ if (e.data?.source !== "bb.markdown.renderer") return;
+ if (e.data.key !== windowName) return;
+ const iframe = iframeRef.value;
+ if (!iframe) return;
+ const win = iframe.contentWindow;
+ if (!win) return;
+ const height = (e.data.height as number) ?? 0;
+ const normalizedHeight = minmax(
+ height,
+ mergedOptions.minHeight,
+ mergedOptions.maxHeight
+ );
+ iframe.style.height = `${normalizedHeight + 2}px`;
+ });
+
+ const ready = computed(() => {
+ return !!deps.value;
+ });
+ return { ready, renderedContent };
+};