Skip to content

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

refactor(issue-detail): extract shared MarkdownEditor + stabilize refs (#20018)

boojackb428aa66d319
diff --git a/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx b/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx
new file mode 100644
index 0000000000..8275ec5be1
--- /dev/null
+++ b/frontend/src/react/components/MarkdownEditor/MarkdownEditor.tsx
@@ -0,0 +1,330 @@
+import DOMPurify from "dompurify";
+import { Bold, Code2, Hash, Heading1, Link2 } from "lucide-react";
+import MarkdownIt from "markdown-it";
+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Textarea } from "@/react/components/ui/textarea";
+import { cn } from "@/react/lib/utils";
+
+const markdown = new MarkdownIt({
+ html: true,
+ linkify: true,
+});
+
+const editorBoxClassName =
+ "min-h-34 w-full rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm";
+
+type CommonProps = {
+ content: string;
+ placeholder?: string;
+ maxLength?: number;
+ transform?: (raw: string) => string;
+ maxHeight?: number;
+};
+
+type EditorProps = CommonProps & {
+ mode?: "editor";
+ onChange: (value: string) => void;
+ onSubmit?: () => void;
+};
+
+type PreviewProps = CommonProps & {
+ mode: "preview";
+ onChange?: (value: string) => void;
+ onSubmit?: () => void;
+};
+
+type Props = EditorProps | PreviewProps;
+
+export function MarkdownEditor({
+ content,
+ onChange,
+ onSubmit,
+ placeholder,
+ maxLength = 65536,
+ mode = "editor",
+ transform,
+ maxHeight,
+}: Props) {
+ const { t } = useTranslation();
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const [tab, setTab] = useState<"write" | "preview">(
+ mode === "preview" ? "preview" : "write"
+ );
+ const previewHtml = useMemo(() => {
+ if (!content) {
+ return "";
+ }
+ const source = transform ? transform(content) : content;
+ const rendered = markdown.render(source);
+ return DOMPurify.sanitize(rendered);
+ }, [content, transform]);
+
+ useEffect(() => {
+ setTab(mode === "preview" ? "preview" : "write");
+ }, [mode]);
+
+ useEffect(() => {
+ if (!textareaRef.current) {
+ return;
+ }
+ textareaRef.current.style.height = "auto";
+ textareaRef.current.style.height = `${Math.max(
+ textareaRef.current.scrollHeight,
+ 112
+ )}px`;
+ }, [content, tab]);
+
+ const insertTemplate = (template: string, cursorOffset: number) => {
+ const textarea = textareaRef.current;
+ if (!textarea || !onChange) {
+ return;
+ }
+ const start = textarea.selectionStart;
+ const end = textarea.selectionEnd;
+ const next = `${content.slice(0, start)}${template.slice(
+ 0,
+ cursorOffset
+ )}${content.slice(start, end)}${template.slice(cursorOffset)}${content.slice(end)}`;
+ onChange(next);
+ window.requestAnimationFrame(() => {
+ if (!textareaRef.current) {
+ return;
+ }
+ const cursor = start + cursorOffset;
+ textareaRef.current.focus();
+ textareaRef.current.setSelectionRange(cursor, cursor);
+ });
+ };
+
+ if (mode === "preview") {
+ return (
+ <PreviewBody
+ className="markdown-body min-h-6 wrap-break-word"
+ html={previewHtml}
+ />
+ );
+ }
+
+ return (
+ <div>
+ <div className="mb-2 flex items-center justify-between pb-1">
+ <div className="flex gap-x-4">
+ <button
+ className={cn(
+ "relative px-1 pb-2 text-sm transition-colors",
+ tab === "write"
+ ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"
+ : "text-control-light hover:text-control"
+ )}
+ onClick={() => setTab("write")}
+ type="button"
+ >
+ {t("issue.comment-editor.write")}
+ </button>
+ <button
+ className={cn(
+ "relative px-1 pb-2 text-sm transition-colors",
+ tab === "preview"
+ ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"
+ : "text-control-light hover:text-control"
+ )}
+ onClick={() => setTab("preview")}
+ type="button"
+ >
+ {t("issue.comment-editor.preview")}
+ </button>
+ </div>
+ {tab === "write" && (
+ <div className="flex items-center gap-x-2">
+ <ToolbarButton
+ icon={<Heading1 className="h-4 w-4" />}
+ label={t("issue.comment-editor.toolbar.header")}
+ onClick={() => insertTemplate("### ", 4)}
+ />
+ <ToolbarButton
+ icon={<Bold className="h-4 w-4" />}
+ label={t("issue.comment-editor.toolbar.bold")}
+ onClick={() => insertTemplate("****", 2)}
+ />
+ <ToolbarButton
+ icon={<Code2 className="h-4 w-4" />}
+ label={t("issue.comment-editor.toolbar.code")}
+ onClick={() => insertTemplate("```sql\n\n```", 7)}
+ />
+ <ToolbarButton
+ icon={<Link2 className="h-4 w-4" />}
+ label={t("issue.comment-editor.toolbar.link")}
+ onClick={() => insertTemplate("[](url)", 1)}
+ />
+ <ToolbarButton
+ icon={<Hash className="h-4 w-4" />}
+ label={t("issue.comment-editor.toolbar.hashtag")}
+ onClick={() => insertTemplate("#", 1)}
+ />
+ </div>
+ )}
+ </div>
+
+ {tab === "preview" ? (
+ <PreviewBody
+ className={cn(editorBoxClassName, "markdown-body")}
+ html={previewHtml}
+ />
+ ) : (
+ <Textarea
+ className={editorBoxClassName}
+ maxLength={maxLength}
+ onChange={(e) => onChange?.(e.target.value)}
+ onKeyDown={(e) => {
+ const listContinuation = applyMarkdownListContinuation(
+ content,
+ e.currentTarget.selectionStart,
+ e.currentTarget.selectionEnd
+ );
+ if (
+ e.key === "Enter" &&
+ !e.nativeEvent.isComposing &&
+ !e.metaKey &&
+ !e.ctrlKey &&
+ listContinuation
+ ) {
+ e.preventDefault();
+ onChange?.(listContinuation.content);
+ window.requestAnimationFrame(() => {
+ const target = textareaRef.current;
+ if (!target) {
+ return;
+ }
+ target.focus();
+ target.setSelectionRange(
+ listContinuation.cursor,
+ listContinuation.cursor
+ );
+ });
+ return;
+ }
+ if (
+ e.key === "Enter" &&
+ !e.nativeEvent.isComposing &&
+ (e.metaKey || e.ctrlKey)
+ ) {
+ e.preventDefault();
+ onSubmit?.();
+ }
+ }}
+ placeholder={placeholder ?? t("issue.leave-a-comment")}
+ ref={textareaRef}
+ rows={4}
+ style={{ maxHeight }}
+ value={content}
+ />
+ )}
+ </div>
+ );
+}
+
+function PreviewBody({ className, html }: { className: string; html: string }) {
+ const { t } = useTranslation();
+ return (
+ <div className={className}>
+ {html ? (
+ <div dangerouslySetInnerHTML={{ __html: html }} />
+ ) : (
+ <span className="italic text-control-placeholder">
+ {t("issue.comment-editor.nothing-to-preview")}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function ToolbarButton({
+ icon,
+ label,
+ onClick,
+}: {
+ icon: ReactNode;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ aria-label={label}
+ className="rounded-xs p-1 text-control transition-colors hover:bg-control-bg hover:text-main"
+ onClick={onClick}
+ title={label}
+ type="button"
+ >
+ {icon}
+ </button>
+ );
+}
+
+function applyMarkdownListContinuation(
+ text: string,
+ selectionStart: number,
+ selectionEnd: number
+) {
+ if (selectionStart !== selectionEnd) {
+ return undefined;
+ }
+
+ const lines = text.split("\n");
+ const lineIndex = getActiveLineIndex(text, selectionStart);
+ const currentLine = lines[lineIndex] ?? "";
+ const lineStart = getCursorPosition(lines.slice(0, lineIndex));
+ const indexInCurrentLine = selectionStart - lineStart;
+
+ if (/^\s{0,}(\d{1,}\.|-)\s{1,}$/.test(currentLine)) {
+ lines[lineIndex] = "";
+ return {
+ content: lines.join("\n"),
+ cursor: getCursorPosition(lines.slice(0, lineIndex)),
+ };
+ }
+
+ if (!/^\s{0,}(\d{1,}\.|-)\s/.test(currentLine)) {
+ return undefined;
+ }
+
+ const indent = " ".repeat(
+ currentLine.length - currentLine.trimStart().length
+ );
+ const trailing = currentLine.slice(indexInCurrentLine);
+ lines[lineIndex] = currentLine.slice(0, indexInCurrentLine);
+
+ let nextListStart = "-";
+ if (/^\s{0,}\d{1,}\.\s/.test(currentLine)) {
+ const currentNumber = Number(currentLine.match(/\d+/)?.[0] ?? "1");
+ nextListStart = `${currentNumber + 1}.`;
+ }
+
+ lines.splice(lineIndex + 1, 0, `${indent}${nextListStart} ${trailing}`);
+ return {
+ content: lines.join("\n"),
+ cursor: getCursorPosition(lines.slice(0, lineIndex + 2)) - 1,
+ };
+}
+
+function getActiveLineIndex(content: string, cursorPosition: number): number {
+ const lines = content.split("\n");
+ let count = 0;
+ for (let i = 0; i < lines.length; i++) {
+ count += lines[i].length;
+ if (count >= cursorPosition) {
+ return i;
+ }
+ count += 1;
+ }
+ return lines.length - 1;
+}
+
+function getCursorPosition(lines: string[]): number {
+ let count = 0;
+ for (const line of lines) {
+ count += line.length;
+ count += 1;
+ }
+ return count;
+}
diff --git a/frontend/src/react/components/MarkdownEditor/index.ts b/frontend/src/react/components/MarkdownEditor/index.ts
new file mode 100644
index 0000000000..fc00fe1d88
--- /dev/null
+++ b/frontend/src/react/components/MarkdownEditor/index.ts
@@ -0,0 +1 @@
+export { MarkdownEditor } from "./MarkdownEditor";
diff --git a/frontend/src/react/components/ui/textarea.tsx b/frontend/src/react/components/ui/textarea.tsx
index d3617c7025..9980dd157f 100644
--- a/frontend/src/react/components/ui/textarea.tsx
+++ b/frontend/src/react/components/ui/textarea.tsx
@@ -10,7 +10,7 @@ function Textarea({ className, ref, ...props }: TextareaProps) {
className={cn(
"flex min-h-25 w-full rounded-xs border border-control-border bg-transparent px-3 py-2 text-sm text-main transition-colors",
"placeholder:text-control-placeholder",
- "focus:outline-hidden focus:ring-2 focus:ring-accent focus:border-accent",
+ "focus:outline-hidden focus:ring-1 focus:ring-accent focus:border-accent",
"disabled:cursor-not-allowed disabled:bg-control-bg disabled:opacity-50",
className
)}
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx
index b615c6c574..60111dfee0 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx
@@ -1,22 +1,15 @@
import { create } from "@bufbuild/protobuf";
import dayjs from "dayjs";
-import DOMPurify from "dompurify";
import { first, orderBy } from "lodash-es";
import {
- Bold,
CalendarX,
Check,
ChevronDown,
- Code2,
EllipsisVertical,
- Hash,
- Heading1,
- Link2,
Loader2,
MessageCircle,
X,
} from "lucide-react";
-import MarkdownIt from "markdown-it";
import {
type ReactNode,
useCallback,
@@ -30,6 +23,7 @@ import {
issueServiceClientConnect,
rolloutServiceClientConnect,
} from "@/connect";
+import { MarkdownEditor } from "@/react/components/MarkdownEditor";
import { Button } from "@/react/components/ui/button";
import {
Dialog,
@@ -43,7 +37,6 @@ import {
SheetHeader,
SheetTitle,
} from "@/react/components/ui/sheet";
-import { Textarea } from "@/react/components/ui/textarea";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useClickOutside } from "@/react/hooks/useClickOutside";
import { useVueState } from "@/react/hooks/useVueState";
@@ -102,11 +95,6 @@ import { isApprovalCompleted } from "../utils/approval";
import { refreshIssueDetailState } from "../utils/refreshIssueDetailState";
import { IssueDetailTaskRolloutActionPanel } from "./IssueDetailTaskRolloutActionPanel";
-const markdown = new MarkdownIt({
- html: true,
- linkify: true,
-});
-
export function IssueDetailActionBar() {
const { t } = useTranslation();
const page = useIssueDetailContext();
@@ -901,7 +889,7 @@ function IssueDetailReviewPopover({
const content = (
<div className="flex flex-col gap-y-3">
- <IssueDetailReviewMarkdownEditor
+ <MarkdownEditor
content={comment}
onChange={setComment}
onSubmit={() => {
@@ -1043,268 +1031,6 @@ function IssueDetailReviewOption({
);
}
-function IssueDetailReviewMarkdownEditor({
- content,
- onChange,
- onSubmit,
-}: {
- content: string;
- onChange: (value: string) => void;
- onSubmit: () => void;
-}) {
- const { t } = useTranslation();
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- const [tab, setTab] = useState<"write" | "preview">("write");
- const previewHtml = useMemo(() => {
- const rendered = markdown.render(content || "");
- return DOMPurify.sanitize(rendered);
- }, [content]);
-
- useEffect(() => {
- if (!textareaRef.current) {
- return;
- }
- textareaRef.current.style.height = "auto";
- textareaRef.current.style.height = `${Math.max(
- textareaRef.current.scrollHeight,
- 112
- )}px`;
- }, [content, tab]);
-
- const insertTemplate = (template: string, cursorOffset: number) => {
- const textarea = textareaRef.current;
- if (!textarea) {
- return;
- }
- const start = textarea.selectionStart;
- const end = textarea.selectionEnd;
- const next = `${content.slice(0, start)}${template.slice(
- 0,
- cursorOffset
- )}${content.slice(start, end)}${template.slice(cursorOffset)}${content.slice(end)}`;
- onChange(next);
- window.requestAnimationFrame(() => {
- if (!textareaRef.current) {
- return;
- }
- const cursor = start + cursorOffset;
- textareaRef.current.focus();
- textareaRef.current.setSelectionRange(cursor, cursor);
- });
- };
-
- return (
- <div>
- <div className="mb-2 flex items-center justify-between border-b border-control-border pb-1">
- <div className="flex gap-x-4">
- <button
- className={cn(
- "relative px-1 pb-2 text-sm font-medium transition-colors",
- tab === "write"
- ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"
- : "text-control-light hover:text-control"
- )}
- onClick={() => setTab("write")}
- type="button"
- >
- {t("issue.comment-editor.write")}
- </button>
- <button
- className={cn(
- "relative px-1 pb-2 text-sm font-medium transition-colors",
- tab === "preview"
- ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"
- : "text-control-light hover:text-control"
- )}
- onClick={() => setTab("preview")}
- type="button"
- >
- {t("issue.comment-editor.preview")}
- </button>
- </div>
- {tab === "write" && (
- <div className="flex items-center gap-x-3 pb-1">
- <IssueDetailReviewToolbarButton
- icon={<Heading1 className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.header")}
- onClick={() => insertTemplate("### ", 4)}
- />
- <IssueDetailReviewToolbarButton
- icon={<Bold className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.bold")}
- onClick={() => insertTemplate("****", 2)}
- />
- <IssueDetailReviewToolbarButton
- icon={<Code2 className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.code")}
- onClick={() => insertTemplate("```sql\n\n```", 7)}
- />
- <IssueDetailReviewToolbarButton
- icon={<Link2 className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.link")}
- onClick={() => insertTemplate("[](url)", 1)}
- />
- <IssueDetailReviewToolbarButton
- icon={<Hash className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.hashtag")}
- onClick={() => insertTemplate("#", 1)}
- />
- </div>
- )}
- </div>
-
- {tab === "preview" ? (
- <div className="markdown-body min-h-25 rounded-xs border border-control-border px-4 py-3 text-sm">
- {previewHtml ? (
- <div dangerouslySetInnerHTML={{ __html: previewHtml }} />
- ) : (
- <span className="italic text-gray-400">
- {t("issue.comment-editor.nothing-to-preview")}
- </span>
- )}
- </div>
- ) : (
- <Textarea
- className="min-h-34 rounded-lg px-4 py-3 text-sm"
- maxLength={65536}
- onChange={(e) => onChange(e.target.value)}
- onKeyDown={(e) => {
- const listContinuation = applyMarkdownListContinuation(
- content,
- e.currentTarget.selectionStart,
- e.currentTarget.selectionEnd
- );
- if (
- e.key === "Enter" &&
- !e.nativeEvent.isComposing &&
- !e.metaKey &&
- !e.ctrlKey &&
- listContinuation
- ) {
- e.preventDefault();
- onChange(listContinuation.content);
- window.requestAnimationFrame(() => {
- const target = textareaRef.current;
- if (!target) {
- return;
- }
- target.focus();
- target.setSelectionRange(
- listContinuation.cursor,
- listContinuation.cursor
- );
- });
- return;
- }
- if (
- e.key === "Enter" &&
- !e.nativeEvent.isComposing &&
- (e.metaKey || e.ctrlKey)
- ) {
- e.preventDefault();
- onSubmit();
- }
- }}
- placeholder={t("issue.leave-a-comment")}
- ref={textareaRef}
- rows={4}
- value={content}
- />
- )}
- </div>
- );
-}
-
-function IssueDetailReviewToolbarButton({
- icon,
- label,
- onClick,
-}: {
- icon: ReactNode;
- label: string;
- onClick: () => void;
-}) {
- return (
- <button
- aria-label={label}
- className="rounded-xs p-1 text-control transition-colors hover:bg-control-bg hover:text-main"
- onClick={onClick}
- title={label}
- type="button"
- >
- {icon}
- </button>
- );
-}
-
-function applyMarkdownListContinuation(
- text: string,
- selectionStart: number,
- selectionEnd: number
-) {
- if (selectionStart !== selectionEnd) {
- return undefined;
- }
-
- const lines = text.split("\n");
- const lineIndex = getActiveLineIndex(text, selectionStart);
- const currentLine = lines[lineIndex] ?? "";
- const lineStart = getCursorPosition(lines.slice(0, lineIndex));
- const indexInCurrentLine = selectionStart - lineStart;
-
- if (/^\s{0,}(\d{1,}\.|-)\s{1,}$/.test(currentLine)) {
- lines[lineIndex] = "";
- return {
- content: lines.join("\n"),
- cursor: getCursorPosition(lines.slice(0, lineIndex)),
- };
- }
-
- if (!/^\s{0,}(\d{1,}\.|-)\s/.test(currentLine)) {
- return undefined;
- }
-
- const indent = " ".repeat(
- currentLine.length - currentLine.trimStart().length
- );
- const trailing = currentLine.slice(indexInCurrentLine);
- lines[lineIndex] = currentLine.slice(0, indexInCurrentLine);
-
- let nextListStart = "-";
- if (/^\s{0,}\d{1,}\.\s/.test(currentLine)) {
- const currentNumber = Number(currentLine.match(/\d+/)?.[0] ?? "1");
- nextListStart = `${currentNumber + 1}.`;
- }
-
- lines.splice(lineIndex + 1, 0, `${indent}${nextListStart} ${trailing}`);
- return {
- content: lines.join("\n"),
- cursor: getCursorPosition(lines.slice(0, lineIndex + 2)) - 1,
- };
-}
-
-function getActiveLineIndex(content: string, cursorPosition: number): number {
- const lines = content.split("\n");
- let count = 0;
- for (let i = 0; i < lines.length; i++) {
- count += lines[i].length;
- if (count >= cursorPosition) {
- return i;
- }
- count += 1;
- }
- return lines.length - 1;
-}
-
-function getCursorPosition(lines: string[]): number {
- let count = 0;
- for (const line of lines) {
- count += line.length;
- count += 1;
- }
- return count;
-}
-
function isExportExpired(
rollout: Rollout | undefined,
taskRuns: {
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx
index a84e7fdf5b..11017707e2 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx
@@ -1,22 +1,16 @@
import { create } from "@bufbuild/protobuf";
-import DOMPurify from "dompurify";
+import { Loader2, Pencil, Play, Plus, ThumbsUp } from "lucide-react";
import {
- Bold,
- Code2,
- Hash,
- Heading1,
- Link2,
- Loader2,
- Pencil,
- Play,
- Plus,
- ThumbsUp,
-} from "lucide-react";
-import MarkdownIt from "markdown-it";
-import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
import { useTranslation } from "react-i18next";
import { issueServiceClientConnect } from "@/connect";
import { HumanizeTs } from "@/react/components/HumanizeTs";
+import { MarkdownEditor } from "@/react/components/MarkdownEditor";
import { ReadonlyDiffMonaco } from "@/react/components/monaco";
import { UserAvatar } from "@/react/components/UserAvatar";
import { Button } from "@/react/components/ui/button";
@@ -25,7 +19,6 @@ import {
DialogContent,
DialogTitle,
} from "@/react/components/ui/dialog";
-import { Textarea } from "@/react/components/ui/textarea";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import { router } from "@/router";
@@ -61,14 +54,33 @@ import { hasProjectPermissionV2 } from "@/utils/iam/permission";
import { getSheetStatement } from "@/utils/v1/sheet";
import { useIssueDetailContext } from "../context/IssueDetailContext";
-const markdown = new MarkdownIt({
- html: true,
- linkify: true,
-});
+function useIssueRefTransform(projectName: string | undefined) {
+ const { t } = useTranslation();
+ return useCallback(
+ (raw: string) =>
+ raw
+ .split(/(#\d+)\b/)
+ .map((part) => {
+ if (!part.startsWith("#")) {
+ return part;
+ }
+ const id = Number.parseInt(part.slice(1), 10);
+ if (!Number.isNaN(id) && id > 0 && projectName) {
+ const projectId = extractProjectResourceName(projectName);
+ const url = `${window.location.origin}/projects/${projectId}/issues/${id}`;
+ return `[${t("common.issue")} #${id}](${url})`;
+ }
+ return part;
+ })
+ .join(""),
+ [projectName, t]
+ );
+}
export function IssueDetailCommentList() {
const { t } = useTranslation();
const page = useIssueDetailContext();
+ const { setEditing } = page;
const projectStore = useProjectV1Store();
const userStore = useUserStore();
const issueCommentStore = useIssueCommentStore();
@@ -85,6 +97,7 @@ export function IssueDetailCommentList() {
const [editContent, setEditContent] = useState("");
const [newComment, setNewComment] = useState("");
const [isRefreshing, setIsRefreshing] = useState(false);
+ const newCommentTransform = useIssueRefTransform(project?.name);
const allowCreateComment = Boolean(
project && hasProjectPermissionV2(project, "bb.issueComments.create")
);
@@ -97,11 +110,11 @@ export function IssueDetailCommentList() {
);
useEffect(() => {
- page.setEditing("comment-row", Boolean(activeCommentName));
+ setEditing("comment-row", Boolean(activeCommentName));
return () => {
- page.setEditing("comment-row", false);
+ setEditing("comment-row", false);
};
- }, [activeCommentName, page]);
+ }, [activeCommentName, setEditing]);
useEffect(() => {
if (!issueName) {
@@ -279,14 +292,14 @@ export function IssueDetailCommentList() {
<h3 className="sr-only" id="issue-comment-editor">
{t("common.comment")}
</h3>
- <IssueDetailMarkdownEditor
+ <MarkdownEditor
content={newComment}
onChange={setNewComment}
onSubmit={() => {
void createComment();
}}
placeholder={t("issue.leave-a-comment")}
- projectName={project?.name}
+ transform={newCommentTransform}
/>
<div className="mt-3 flex items-center justify-end">
<Button
@@ -323,6 +336,7 @@ function IssueDescriptionCommentRow({
}) {
const { t } = useTranslation();
const page = useIssueDetailContext();
+ const { setEditing } = page;
const projectStore = useProjectV1Store();
const userStore = useUserStore();
const projectName = `${projectNamePrefix}${page.projectId}`;
@@ -343,11 +357,11 @@ function IssueDescriptionCommentRow({
}, [isEditing, page.issue?.description]);
useEffect(() => {
- page.setEditing("issue-description", isEditing);
+ setEditing("issue-description", isEditing);
return () => {
- page.setEditing("issue-description", false);
+ setEditing("issue-description", false);
};
- }, [isEditing, page]);
+ }, [isEditing, setEditing]);
const allowEdit = Boolean(
project && hasProjectPermissionV2(project, "bb.issues.update")
@@ -830,6 +844,7 @@ function EditableMarkdownContent({
projectName?: string;
}) {
const { t } = useTranslation();
+ const transform = useIssueRefTransform(projectName);
if (!isEditing && !content) {
return (
@@ -841,13 +856,13 @@ function EditableMarkdownContent({
return (
<div>
- <IssueDetailMarkdownEditor
+ <MarkdownEditor
content={isEditing ? editContent : content}
maxHeight={Number.MAX_SAFE_INTEGER}
mode={isEditing ? "editor" : "preview"}
onChange={onChange}
onSubmit={onSave}
- projectName={projectName}
+ transform={transform}
/>
{isEditing && (
<div className="mt-2 flex items-center justify-end gap-x-2">
@@ -864,232 +879,6 @@ function EditableMarkdownContent({
);
}
-function IssueDetailMarkdownEditor({
- content,
- maxHeight = 192,
- mode = "editor",
- onChange,
- onSubmit,
- placeholder,
- projectName,
-}: {
- content: string;
- maxHeight?: number;
- mode?: "editor" | "preview";
- onChange?: (value: string) => void;
- onSubmit?: () => void;
- placeholder?: string;
- projectName?: string;
-}) {
- const { t } = useTranslation();
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- const [tab, setTab] = useState<"write" | "preview">(
- mode === "preview" ? "preview" : "write"
- );
- const previewHtml = useMemo(
- () => renderMarkdown(content, projectName, t),
- [content, projectName, t]
- );
-
- useEffect(() => {
- setTab(mode === "preview" ? "preview" : "write");
- }, [mode]);
-
- useEffect(() => {
- if (tab === "write" && textareaRef.current) {
- autoSizeTextarea(textareaRef.current);
- }
- }, [content, tab]);
-
- const insertTemplate = (template: string, position: number) => {
- const textarea = textareaRef.current;
- if (!textarea || !onChange) {
- return;
- }
- const start = textarea.selectionStart;
- const end = textarea.selectionEnd;
- const next = `${content.slice(0, start)}${template.slice(
- 0,
- position
- )}${content.slice(start, end)}${template.slice(position)}${content.slice(end)}`;
- onChange(next);
- window.requestAnimationFrame(() => {
- const target = textareaRef.current;
- if (!target) {
- return;
- }
- const cursor = start + position;
- target.focus();
- target.setSelectionRange(cursor, cursor);
- autoSizeTextarea(target);
- });
- };
-
- if (mode === "preview") {
- return (
- <div
- className="markdown-body min-h-6 wrap-break-word"
- dangerouslySetInnerHTML={{
- __html:
- previewHtml ||
- `<span class="text-gray-400 italic">${t(
- "issue.comment-editor.nothing-to-preview"
- )}</span>`,
- }}
- />
- );
- }
-
- return (
- <div>
- <div className="mb-2 flex items-center justify-between border-b border-control-border">
- <div className="flex gap-x-4">
- <button
- className={cn(
- "relative px-1 pb-2 text-sm font-medium transition-colors",
- tab === "write"
- ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"
- : "text-control-light hover:text-control"
- )}
- onClick={() => setTab("write")}
- type="button"
- >
- {t("issue.comment-editor.write")}
- </button>
- <button
- className={cn(
- "relative px-1 pb-2 text-sm font-medium transition-colors",
- tab === "preview"
- ? "text-accent after:absolute after:inset-x-0 after:-bottom-px after:h-0.5 after:bg-accent"
- : "text-control-light hover:text-control"
- )}
- onClick={() => setTab("preview")}
- type="button"
- >
- {t("issue.comment-editor.preview")}
- </button>
- </div>
- {tab === "write" && (
- <div className="flex items-center gap-x-1 pb-1">
- <ToolbarButton
- icon={<Heading1 className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.header")}
- onClick={() => insertTemplate("### ", 4)}
- />
- <ToolbarButton
- icon={<Bold className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.bold")}
- onClick={() => insertTemplate("****", 2)}
- />
- <ToolbarButton
- icon={<Code2 className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.code")}
- onClick={() => insertTemplate("```sql\n\n```", 7)}
- />
- <ToolbarButton
- icon={<Link2 className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.link")}
- onClick={() => insertTemplate("[](url)", 1)}
- />
- <ToolbarButton
- icon={<Hash className="h-4 w-4" />}
- label={t("issue.comment-editor.toolbar.hashtag")}
- onClick={() => insertTemplate("#", 1)}
- />
- </div>
- )}
- </div>
-
- {tab === "preview" ? (
- <div className="markdown-body min-h-6 wrap-break-word rounded-md">
- {previewHtml ? (
- <div
- dangerouslySetInnerHTML={{
- __html: previewHtml,
- }}
- />
- ) : (
- <span className="italic text-gray-400">
- {t("issue.comment-editor.nothing-to-preview")}
- </span>
- )}
- </div>
- ) : (
- <Textarea
- className="whitespace-pre-wrap rounded-lg px-4 py-3"
- maxLength={65536}
- onChange={(e) => onChange?.(e.target.value)}
- onKeyDown={(e) => {
- const listContinuation = applyMarkdownListContinuation(
- content,
- e.currentTarget.selectionStart,
- e.currentTarget.selectionEnd
- );
- if (
- e.key === "Enter" &&
- !e.nativeEvent.isComposing &&
- !e.metaKey &&
- !e.ctrlKey &&
- listContinuation
- ) {
- e.preventDefault();
- onChange?.(listContinuation.content);
- window.requestAnimationFrame(() => {
- const target = textareaRef.current;
- if (!target) {
- return;
- }
- target.focus();
- target.setSelectionRange(
- listContinuation.cursor,
- listContinuation.cursor
- );
- autoSizeTextarea(target);
- });
- return;
- }
- if (
- e.key === "Enter" &&
- !e.nativeEvent.isComposing &&
- (e.metaKey || e.ctrlKey)
- ) {
- e.preventDefault();
- onSubmit?.();
- }
- }}
- placeholder={placeholder || t("issue.leave-a-comment")}
- ref={textareaRef}
- rows={4}
- style={{ maxHeight }}
- value={content}
- />
- )}
- </div>
- );
-}
-
-function ToolbarButton({
- icon,
- label,
- onClick,
-}: {
- icon: ReactNode;
- label: string;
- onClick: () => void;
-}) {
- return (
- <button
- aria-label={label}
- className="rounded-xs p-1 text-control transition-colors hover:bg-control-bg hover:text-main"
- onClick={onClick}
- title={label}
- type="button"
- >
- {icon}
- </button>
- );
-}
-
function IssueDetailStatementUpdateButton({
newSheet,
oldSheet,
@@ -1170,103 +959,3 @@ function IssueDetailStatementUpdateButton({
</>
);
}
-
-function autoSizeTextarea(textarea: HTMLTextAreaElement) {
- textarea.style.height = "auto";
- textarea.style.height = `${Math.max(textarea.scrollHeight, 112)}px`;
-}
-
-function applyMarkdownListContinuation(
- text: string,
- selectionStart: number,
- selectionEnd: number
-) {
- if (selectionStart !== selectionEnd) {
- return undefined;
- }
-
- const lines = text.split("\n");
- const lineIndex = getActiveLineIndex(text, selectionStart);
- const currentLine = lines[lineIndex] ?? "";
- const lineStart = getCursorPosition(lines.slice(0, lineIndex));
- const indexInCurrentLine = selectionStart - lineStart;
-
- if (/^\s{0,}(\d{1,}\.|-)\s{1,}$/.test(currentLine)) {
- lines[lineIndex] = "";
- return {
- content: lines.join("\n"),
- cursor: getCursorPosition(lines.slice(0, lineIndex)),
- };
- }
-
- if (!/^\s{0,}(\d{1,}\.|-)\s/.test(currentLine)) {
- return undefined;
- }
-
- const indent = " ".repeat(
- currentLine.length - currentLine.trimStart().length
- );
- const trailing = currentLine.slice(indexInCurrentLine);
- lines[lineIndex] = currentLine.slice(0, indexInCurrentLine);
-
- let nextListStart = "-";
- if (/^\s{0,}\d{1,}\.\s/.test(currentLine)) {
- const currentNumber = Number(currentLine.match(/\d+/)?.[0] ?? "1");
- nextListStart = `${currentNumber + 1}.`;
- }
-
- lines.splice(lineIndex + 1, 0, `${indent}${nextListStart} ${trailing}`);
- return {
- content: lines.join("\n"),
- cursor: getCursorPosition(lines.slice(0, lineIndex + 2)) - 1,
- };
-}
-
-function getActiveLineIndex(content: string, cursorPosition: number): number {
- const lines = content.split("\n");
- let count = 0;
- for (let i = 0; i < lines.length; i++) {
- count += lines[i].length;
- if (count >= cursorPosition) {
- return i;
- }
- count += 1;
- }
- return lines.length - 1;
-}
-
-function getCursorPosition(lines: string[]): number {
- let count = 0;
- for (const line of lines) {
- count += line.length;
- count += 1;
- }
- return count;
-}
-
-function renderMarkdown(
- markdownContent: string,
- projectName: string | undefined,
- t: (key: string) => string
-) {
- if (!markdownContent) {
- return "";
- }
- const withIssueLinks = markdownContent
- .split(/(#\d+)\b/)
- .map((part) => {
- if (!part.startsWith("#")) {
- return part;
- }
- const id = Number.parseInt(part.slice(1), 10);
- if (!Number.isNaN(id) && id > 0 && projectName) {
- const projectId = extractProjectResourceName(projectName);
- const url = `${window.location.origin}/projects/${projectId}/issues/${id}`;
- return `[${t("common.issue")} #${id}](${url})`;
- }
- return part;
- })
- .join("");
- const rendered = markdown.render(withIssueLinks);
- return DOMPurify.sanitize(rendered);
-}
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
index cc3b262cea..16542b9091 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
@@ -69,6 +69,7 @@ import { IssueDetailStatementSection } from "./IssueDetailStatementSection";
const DEFAULT_VISIBLE_TARGETS = 20;
const MAX_INLINE_DATABASES = 5;
const EMPTY_SELECT_VALUE = "__empty__";
+const EMPTY_SPECS: Plan_Spec[] = [];
export function IssueDetailDatabaseChangeView({
onSelectedSpecIdChange,
@@ -79,11 +80,8 @@ export function IssueDetailDatabaseChangeView({
}) {
const { t } = useTranslation();
const page = useIssueDetailContext();
- const { emptySpecIdSet } = useIssueDetailSpecValidation(
- page.plan?.specs ?? []
- );
-
- const specs = page.plan?.specs ?? [];
+ const specs = page.plan?.specs ?? EMPTY_SPECS;
+ const { emptySpecIdSet } = useIssueDetailSpecValidation(specs);
const selectedSpec = useMemo(() => {
return specs.find((spec) => spec.id === selectedSpecId) ?? specs[0];
}, [selectedSpecId, specs]);
@@ -820,7 +818,10 @@ function IssueDetailDatabaseGroupTarget({
const databaseGroup = useVueState(() =>
dbGroupStore.getDBGroupByName(target)
);
- const databases = databaseGroup.matchedDatabases?.map((db) => db.name) ?? [];
+ const databases = useMemo(
+ () => databaseGroup.matchedDatabases?.map((db) => db.name) ?? [],
+ [databaseGroup.matchedDatabases]
+ );
const extraDatabases = databases.slice(MAX_INLINE_DATABASES);
useEffect(() => {
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
index 61372177eb..f1246a5c29 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
@@ -132,6 +132,7 @@ export function IssueDetailDatabaseExportView({
function IssueDetailDatabaseExportOptions() {
const { t } = useTranslation();
const page = useIssueDetailContext();
+ const { setEditing } = page;
const exportDataSpec = useMemo(() => {
return page.plan?.specs.find(
(spec) => spec.config?.case === "exportDataConfig"
@@ -156,11 +157,11 @@ function IssueDetailDatabaseExportOptions() {
}, [exportDataConfig, isEditing]);
useEffect(() => {
- page.setEditing("export-options", isEditing);
+ setEditing("export-options", isEditing);
return () => {
- page.setEditing("export-options", false);
+ setEditing("export-options", false);
};
- }, [isEditing, page]);
+ }, [isEditing, setEditing]);
const shouldShowEditButton = useMemo(() => {
if (page.readonly || page.isCreating || isEditing) {
@@ -697,7 +698,10 @@ function IssueDetailDatabaseExportDatabaseGroupTarget({
const databaseGroup = useVueState(() =>
dbGroupStore.getDBGroupByName(target)
);
- const databases = databaseGroup.matchedDatabases?.map((db) => db.name) ?? [];
+ const databases = useMemo(
+ () => databaseGroup.matchedDatabases?.map((db) => db.name) ?? [],
+ [databaseGroup.matchedDatabases]
+ );
const extraDatabases = databases.slice(MAX_INLINE_DATABASES);
useEffect(() => {
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx
index 176b2d9c53..99ba3b321f 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx
@@ -65,6 +65,7 @@ export function IssueDetailStatementSection({
}) {
const { t } = useTranslation();
const page = useIssueDetailContext();
+ const { setEditing } = page;
const sheetStore = useSheetV1Store();
const releaseStore = useReleaseStore();
const projectStore = useProjectV1Store();
@@ -131,11 +132,11 @@ export function IssueDetailStatementSection({
}, [isEditing, statement]);
useEffect(() => {
- page.setEditing(editingScope, isEditing);
+ setEditing(editingScope, isEditing);
return () => {
- page.setEditing(editingScope, false);
+ setEditing(editingScope, false);
};
- }, [editingScope, isEditing, page]);
+ }, [editingScope, isEditing, setEditing]);
useEffect(() => {
setIsEditing(false);
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx
index 2ef6ba761f..0af5a8a5f1 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx
@@ -16,6 +16,7 @@ import { useIssueDetailContext } from "../context/IssueDetailContext";
export function IssueDetailTitleInput() {
const { t } = useTranslation();
const page = useIssueDetailContext();
+ const { setEditing } = page;
const projectStore = useProjectV1Store();
const projectName = `${projectNamePrefix}${page.projectId}`;
const project = useVueState(() => projectStore.getProjectByName(projectName));
@@ -30,9 +31,9 @@ export function IssueDetailTitleInput() {
useEffect(() => {
return () => {
- page.setEditing("title", false);
+ setEditing("title", false);
};
- }, [page]);
+ }, [setEditing]);
const allowEdit = useMemo(() => {
if (page.readonly || !page.issue || !project) {
@@ -43,7 +44,7 @@ export function IssueDetailTitleInput() {
const isReadOnly = !allowEdit || isUpdating;
const handleBlur = async () => {
- page.setEditing("title", false);
+ setEditing("title", false);
setIsEditing(false);
if (!page.issue || title === page.issue.title) {
setTitle(page.issue?.title || "");
@@ -100,7 +101,7 @@ export function IssueDetailTitleInput() {
if (isReadOnly) {
return;
}
- page.setEditing("title", true);
+ setEditing("title", true);
setIsEditing(true);
}}
onKeyDown={(e) => {
diff --git a/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts b/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts
index 0ffd093566..e7c64a7dce 100644
--- a/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts
+++ b/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts
@@ -120,6 +120,15 @@ const applyDerivedState = (
};
};
+const isSameSnapshot = (
+ prev: IssueDetailPageSnapshot,
+ next: IssueDetailPageSnapshot
+) => {
+ return (Object.keys(next) as Array<keyof IssueDetailPageSnapshot>).every(
+ (key) => Object.is(prev[key], next[key])
+ );
+};
+
const loadIssueDetailSnapshot = async (
projectId: string,
issueId: string
@@ -292,7 +301,10 @@ export const useIssueDetailPage = ({
const patchState = useCallback(
(patch: Partial<IssueDetailPageSnapshot>) => {
- setSnapshot((prev) => applyDerivedState({ ...prev, ...patch }));
+ setSnapshot((prev) => {
+ const next = applyDerivedState({ ...prev, ...patch });
+ return isSameSnapshot(prev, next) ? prev : next;
+ });
},
[setSnapshot]
);
diff --git a/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailSpecValidation.ts b/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailSpecValidation.ts
index 77108c29e6..6ca7a6999a 100644
--- a/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailSpecValidation.ts
+++ b/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailSpecValidation.ts
@@ -42,6 +42,18 @@ const checkSpecStatement = async (
}
};
+const isSameSet = (prev: Set<string>, next: Set<string>) => {
+ if (prev.size !== next.size) {
+ return false;
+ }
+ for (const value of next) {
+ if (!prev.has(value)) {
+ return false;
+ }
+ }
+ return true;
+};
+
export function useIssueDetailSpecValidation(specs: Plan_Spec[]) {
const sheetStore = useSheetV1Store();
const [emptySpecIdSet, setEmptySpecIdSet] = useState<Set<string>>(
@@ -61,7 +73,7 @@ export function useIssueDetailSpecValidation(specs: Plan_Spec[]) {
})
);
if (!canceled) {
- setEmptySpecIdSet(next);
+ setEmptySpecIdSet((prev) => (isSameSet(prev, next) ? prev : next));
}
};
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
index b8aff8c4fb..3dade12d5f 100644
--- a/frontend/tsconfig.app.json
+++ b/frontend/tsconfig.app.json
@@ -10,6 +10,7 @@
"exclude": [
"src/**/__tests__/*",
"src/react/**/*.tsx",
+ "src/react/components/MarkdownEditor/index.ts",
"src/react/components/task-run-log/index.ts",
"src/react/components/monaco/index.ts",
"src/react/components/revision/index.ts"
diff --git a/frontend/tsconfig.vitest.json b/frontend/tsconfig.vitest.json
index 13fd22fe82..a631a90a49 100644
--- a/frontend/tsconfig.vitest.json
+++ b/frontend/tsconfig.vitest.json
@@ -9,6 +9,7 @@
],
"exclude": [
"src/react/**/*.tsx",
+ "src/react/components/MarkdownEditor/index.ts",
"src/react/components/task-run-log/index.ts",
"src/react/components/monaco/index.ts",
"src/react/components/revision/index.ts"