Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): rewrite bubble menu and link preview with useFloating
Naiyuan Qing6a451c1ce7e2
diff --git a/packages/views/editor/bubble-menu.tsx b/packages/views/editor/bubble-menu.tsxindex 95b5c5848d..903a036aea 100644--- a/packages/views/editor/bubble-menu.tsx+++ b/packages/views/editor/bubble-menu.tsx@@ -1,11 +1,27 @@"use client";-import { useState, useEffect, useCallback, useRef } from "react";-import { BubbleMenu } from "@tiptap/react/menus";+/**+ * EditorBubbleMenu — floating formatting toolbar for text selection.+ *+ * Positioned with @floating-ui/react-dom (useFloating + autoUpdate) and+ * portaled to document.body via createPortal. This escapes ALL overflow+ * containers in the ancestor chain (Card overflow:hidden, scrollable+ * containers, etc.) while autoUpdate monitors every ancestor scroll+ * container to keep the menu anchored to the selection.+ *+ * Previously used Tiptap's <BubbleMenu> component, but that plugin:+ * - only supports a single scrollTarget (misses nested scroll)+ * - shows the element before computing position (flash on first show)+ * - uses position:absolute which gets clipped by overflow:hidden+ */++import { useState, useEffect, useCallback, useRef, useMemo } from "react";+import { createPortal } from "react-dom";+import { useFloating, offset, flip, shift, autoUpdate } from "@floating-ui/react-dom";+import { getOverflowAncestors } from "@floating-ui/dom";import type { Editor } from "@tiptap/core";+import { posToDOMRect } from "@tiptap/core";import { NodeSelection } from "@tiptap/pm/state";-import type { EditorState } from "@tiptap/pm/state";-import type { EditorView } from "@tiptap/pm/view";import { Toggle } from "@multica/ui/components/ui/toggle";import { Separator } from "@multica/ui/components/ui/separator";import {@@ -42,38 +58,19 @@ import {} from "lucide-react";// ----------------------------------------------------------------------------// Helpers+// Visibility logic// ----------------------------------------------------------------------------/** Force re-render when editor state changes so isActive() returns fresh values */-function useEditorTransactionUpdate(editor: Editor) {- const [, setState] = useState(0);- useEffect(() => {- const handler = () => setState((n) => n + 1);- editor.on("transaction", handler);- return () => {- editor.off("transaction", handler);- };- }, [editor]);-}--function shouldShowBubbleMenu({- editor,- state,- from,- to,-}: {- editor: Editor;- view: EditorView;- state: EditorState;- oldState?: EditorState;- from: number;- to: number;-}) {+function shouldShowBubbleMenu(editor: Editor): boolean {if (!editor.isEditable) return false;- if (state.selection.empty) return false;+ // Don't check hasFocus() here — it's unreliable during transaction events.+ // Focus loss is handled separately by the debounced blur handler.+ const { state } = editor;+ const { selection } = state;+ if (selection.empty) return false;+ const { from, to } = selection;if (!state.doc.textBetween(from, to).length) return false;- if (state.selection instanceof NodeSelection) return false;+ if (selection instanceof NodeSelection) return false;const $from = state.doc.resolve(from);if ($from.parent.type.name === "codeBlock") return false;return true;@@ -84,15 +81,6 @@ const isMac =typeof navigator !== "undefined" && /Mac/.test(navigator.platform);const mod = isMac ? "\u2318" : "Ctrl";-/** Hoisted to avoid new reference on every render (triggers plugin updateOptions) */-const BUBBLE_MENU_OPTIONS = {- strategy: "fixed" as const,- placement: "top" as const,- offset: 8,- flip: true,- shift: { padding: 8 },-};-// ---------------------------------------------------------------------------// Mark Toggle Button// ---------------------------------------------------------------------------@@ -141,6 +129,26 @@ function MarkButton({);}+// ---------------------------------------------------------------------------+// URL normalisation+// ---------------------------------------------------------------------------++/** Protocols that can execute code in the browser — the only ones we block. */+const DANGEROUS_PROTOCOL_RE = /^(javascript|data|vbscript):/i;+const HAS_PROTOCOL_RE = /^[a-z][a-z0-9+.-]*:\/?\/?/i;+const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;++function normalizeUrl(input: string): string {+ const trimmed = input.trim();+ if (!trimmed) return "";+ if (trimmed.startsWith("/")) return trimmed;+ if (DANGEROUS_PROTOCOL_RE.test(trimmed)) return "";+ if (HAS_PROTOCOL_RE.test(trimmed)) return trimmed;+ if (EMAIL_RE.test(trimmed)) return `mailto:${trimmed}`;+ if (trimmed.startsWith("//")) return `https:${trimmed}`;+ return `https://${trimmed}`;+}+// ---------------------------------------------------------------------------// Link Edit Bar// ---------------------------------------------------------------------------@@ -157,19 +165,15 @@ function LinkEditBar({const inputRef = useRef<HTMLInputElement>(null);useEffect(() => {- // autoFocus workaround — setTimeout to ensure the input is mountedconst t = setTimeout(() => inputRef.current?.focus(), 0);return () => clearTimeout(t);}, []);const apply = useCallback(() => {- let href = url.trim();+ const href = normalizeUrl(url);if (!href) {editor.chain().focus().extendMarkRange("link").unsetLink().run();} else {- if (!/^https?:\/\//.test(href) && !href.startsWith("/")) {- href = `https://${href}`;- }editor.chain().focus()@@ -256,34 +260,12 @@ function HeadingDropdown({const activeLevel = [1, 2, 3].find((l) =>editor.isActive("heading", { level: l }),);-const label = activeLevel ? `H${activeLevel}` : "Text";-const items = [- {- label: "Normal Text",- icon: Type,- active: !activeLevel,- action: () => editor.chain().focus().setParagraph().run(),- },- {- label: "Heading 1",- icon: Heading1,- active: activeLevel === 1,- action: () => editor.chain().focus().toggleHeading({ level: 1 }).run(),- },- {- label: "Heading 2",- icon: Heading2,- active: activeLevel === 2,- action: () => editor.chain().focus().toggleHeading({ level: 2 }).run(),- },- {- label: "Heading 3",- icon: Heading3,- active: activeLevel === 3,- action: () => editor.chain().focus().toggleHeading({ level: 3 }).run(),- },+ { label: "Normal Text", icon: Type, active: !activeLevel, action: () => editor.chain().focus().setParagraph().run() },+ { label: "Heading 1", icon: Heading1, active: activeLevel === 1, action: () => editor.chain().focus().toggleHeading({ level: 1 }).run() },+ { label: "Heading 2", icon: Heading2, active: activeLevel === 2, action: () => editor.chain().focus().toggleHeading({ level: 2 }).run() },+ { label: "Heading 3", icon: Heading3, active: activeLevel === 3, action: () => editor.chain().focus().toggleHeading({ level: 3 }).run() },];return (@@ -295,18 +277,9 @@ function HeadingDropdown({{label}<ChevronDown className="size-3" /></DropdownMenuTrigger>- <DropdownMenuContent- side="bottom"- sideOffset={8}- align="start"- className="w-auto"- >+ <DropdownMenuContent side="bottom" sideOffset={8} align="start" className="w-auto">{items.map((item) => (- <DropdownMenuItem- key={item.label}- onClick={item.action}- className="gap-2 text-xs"- >+ <DropdownMenuItem key={item.label} onClick={item.action} className="gap-2 text-xs"><item.icon className="size-3.5" />{item.label}{item.active && <Check className="ml-auto size-3.5" />}@@ -346,28 +319,15 @@ function ListDropdown({<List className="size-3.5" /><ChevronDown className="size-3" /></TooltipTrigger>- <TooltipContent side="top" sideOffset={8}>- List- </TooltipContent>+ <TooltipContent side="top" sideOffset={8}>List</TooltipContent></Tooltip>- <DropdownMenuContent- side="bottom"- sideOffset={8}- align="start"- className="w-auto"- >- <DropdownMenuItem- onClick={() => editor.chain().focus().toggleBulletList().run()}- className="gap-2 text-xs"- >+ <DropdownMenuContent side="bottom" sideOffset={8} align="start" className="w-auto">+ <DropdownMenuItem onClick={() => editor.chain().focus().toggleBulletList().run()} className="gap-2 text-xs"><List className="size-3.5" />Bullet List{isBullet && <Check className="ml-auto size-3.5" />}</DropdownMenuItem>- <DropdownMenuItem- onClick={() => editor.chain().focus().toggleOrderedList().run()}- className="gap-2 text-xs"- >+ <DropdownMenuItem onClick={() => editor.chain().focus().toggleOrderedList().run()} className="gap-2 text-xs"><ListOrdered className="size-3.5" />Ordered List{isOrdered && <Check className="ml-auto size-3.5" />}@@ -378,125 +338,120 @@ function ListDropdown({}// ----------------------------------------------------------------------------// Main Bubble Menu+// Main Bubble Menu — useFloating + portal to body// ---------------------------------------------------------------------------function EditorBubbleMenu({ editor }: { editor: Editor }) {+ const [visible, setVisible] = useState(false);const [mode, setMode] = useState<"toolbar" | "link-edit">("toolbar");- const [focused, setFocused] = useState(editor.view.hasFocus());- const modeRef = useRef(mode);- modeRef.current = mode;- // Track whether a child dropdown is open — blur during dropdown interaction should not hide- const menuOpenRef = useRef(false);- const handleMenuOpenChange = useCallback((open: boolean) => {- menuOpenRef.current = open;- }, []);- useEditorTransactionUpdate(editor);+ // Virtual reference that tracks the text selection.+ // contextElement tells autoUpdate where to find scroll ancestors.+ const virtualRef = useMemo(+ () => ({+ getBoundingClientRect: () => {+ const { from, to } = editor.state.selection;+ return posToDOMRect(editor.view, from, to);+ },+ contextElement: editor.view.dom,+ }),+ [editor],+ );++ const { refs, floatingStyles, isPositioned, update } = useFloating({+ strategy: "fixed",+ placement: "top",+ open: visible,+ middleware: [offset(8), flip(), shift({ padding: 8 })],+ elements: { reference: virtualRef },+ whileElementsMounted: autoUpdate,+ });- // Hide bubble menu when editor loses focus (but not when a child dropdown is open)+ // Show/hide based on selection state — no blur/focus handling.useEffect(() => {- const onFocus = () => setFocused(true);- const onBlur = () => {- setTimeout(() => {- if (!editor.isDestroyed && !editor.view.hasFocus() && !menuOpenRef.current) {- setFocused(false);- }- }, 0);+ const onTransaction = () => {+ const show = shouldShowBubbleMenu(editor);+ setVisible(show);+ // Must call update() manually — autoUpdate can't detect virtual+ // reference movement (it's not a real DOM element).+ if (show) update();};- editor.on("focus", onFocus);- editor.on("blur", onBlur);- return () => {- editor.off("focus", onFocus);- editor.off("blur", onBlur);+ editor.on("transaction", onTransaction);+ return () => { editor.off("transaction", onTransaction); };+ }, [editor, update]);++ // Close on outside click (mousedown not in editor and not in menu)+ useEffect(() => {+ if (!visible) return;+ const handle = (e: MouseEvent) => {+ const target = e.target as HTMLElement;+ if (editor.view.dom.contains(target)) return;+ if (target.closest(".bubble-menu") || target.closest(".bubble-menu-link-edit")) return;+ setVisible(false);};- }, [editor]);+ document.addEventListener("mousedown", handle);+ return () => document.removeEventListener("mousedown", handle);+ }, [visible, editor]);- // Reset to toolbar mode when selection changes — but not during link editing.- // Also restore focused state (scroll sets it to false, new selection should bring it back).+ // Close on any ancestor scroll or window resizeuseEffect(() => {- const handler = () => {- if (modeRef.current !== "link-edit") setMode("toolbar");- if (editor.view.hasFocus()) setFocused(true);+ if (!visible) return;+ const close = () => {+ setVisible(false);};- editor.on("selectionUpdate", handler);+ const ancestors = getOverflowAncestors(editor.view.dom);+ ancestors.forEach((el) => el.addEventListener("scroll", close, { passive: true }));+ window.addEventListener("resize", close);return () => {- editor.off("selectionUpdate", handler);+ ancestors.forEach((el) => el.removeEventListener("scroll", close));+ window.removeEventListener("resize", close);};- }, [editor]);+ }, [visible, editor]);- // Hide when an ancestor of the editor scrolls (capture phase catches non-bubbling scroll events).- // Scoped to ancestors only — dropdown/sidebar scrolls won't trigger this.+ // Reset mode on selection changeuseEffect(() => {- const handler = (e: Event) => {- const target = e.target;- if (- target instanceof HTMLElement &&- target.contains(editor.view.dom)- ) {- setFocused(false);- }- };- document.addEventListener("scroll", handler, true);- return () => document.removeEventListener("scroll", handler, true);+ const handler = () => setMode("toolbar");+ editor.on("selectionUpdate", handler);+ return () => { editor.off("selectionUpdate", handler); };}, [editor]);- const openLinkEdit = useCallback(() => {- setMode("link-edit");- }, []);+ // Refocus editor when Base UI dropdown closes+ const handleMenuOpenChange = useCallback(+ (open: boolean) => { if (!open) editor.commands.focus(); },+ [editor],+ );+ const openLinkEdit = useCallback(() => setMode("link-edit"), []);const closeLinkEdit = useCallback(() => {setMode("toolbar");- }, []);-- if (!focused) return null;+ editor.commands.focus();+ }, [editor]);- return (- <BubbleMenu- editor={editor}- shouldShow={shouldShowBubbleMenu}- updateDelay={0}- style={{ zIndex: 50 }}- options={BUBBLE_MENU_OPTIONS}+ return createPortal(+ <div+ ref={refs.setFloating}+ style={{+ ...floatingStyles,+ zIndex: 50,+ // display:none when hidden — no residual animations from children.+ // Also hide until Floating UI has computed position (isPositioned)+ // to avoid a flash at top:0 left:0.+ display: visible && isPositioned ? undefined : "none",+ }}+ onMouseDown={(e) => e.preventDefault()}>{mode === "link-edit" ? (<LinkEditBar editor={editor} onClose={closeLinkEdit} />) : (<TooltipProvider delay={300}><div className="bubble-menu">- {/* Group 1: Inline Marks */}- <MarkButton- editor={editor}- mark="bold"- icon={Bold}- label="Bold"- shortcut={`${mod}+B`}- />- <MarkButton- editor={editor}- mark="italic"- icon={Italic}- label="Italic"- shortcut={`${mod}+I`}- />- <MarkButton- editor={editor}- mark="strike"- icon={Strikethrough}- label="Strikethrough"- shortcut={`${mod}+Shift+S`}- />- <MarkButton- editor={editor}- mark="code"- icon={Code}- label="Code"- shortcut={`${mod}+E`}- />+ <MarkButton editor={editor} mark="bold" icon={Bold} label="Bold" shortcut={`${mod}+B`} />+ <MarkButton editor={editor} mark="italic" icon={Italic} label="Italic" shortcut={`${mod}+I`} />+ <MarkButton editor={editor} mark="strike" icon={Strikethrough} label="Strikethrough" shortcut={`${mod}+Shift+S`} />+ <MarkButton editor={editor} mark="code" icon={Code} label="Code" shortcut={`${mod}+E`} /><Separator orientation="vertical" className="mx-0.5 h-5" />- {/* Group 2: Link */}<Tooltip><TooltipTriggerrender={@@ -510,14 +465,11 @@ function EditorBubbleMenu({ editor }: { editor: Editor }) {><Link2 className="size-3.5" /></TooltipTrigger>- <TooltipContent side="top" sideOffset={8}>- Link- </TooltipContent>+ <TooltipContent side="top" sideOffset={8}>Link</TooltipContent></Tooltip><Separator orientation="vertical" className="mx-0.5 h-5" />- {/* Group 3: Block Transforms */}<HeadingDropdown editor={editor} onOpenChange={handleMenuOpenChange} /><ListDropdown editor={editor} onOpenChange={handleMenuOpenChange} /><Tooltip>@@ -526,23 +478,20 @@ function EditorBubbleMenu({ editor }: { editor: Editor }) {<Togglesize="sm"pressed={editor.isActive("blockquote")}- onPressedChange={() =>- editor.chain().focus().toggleBlockquote().run()- }+ onPressedChange={() => editor.chain().focus().toggleBlockquote().run()}onMouseDown={(e) => e.preventDefault()}/>}><Quote className="size-3.5" /></TooltipTrigger>- <TooltipContent side="top" sideOffset={8}>- Quote- </TooltipContent>+ <TooltipContent side="top" sideOffset={8}>Quote</TooltipContent></Tooltip></div></TooltipProvider>)}- </BubbleMenu>+ </div>,+ document.body,);}diff --git a/packages/views/editor/content-editor.css b/packages/views/editor/content-editor.cssindex 42c4a29123..be30935269 100644--- a/packages/views/editor/content-editor.css+++ b/packages/views/editor/content-editor.css@@ -486,4 +486,21 @@0 4px 12px color-mix(in srgb, black 12%, transparent),0 0 0 1px color-mix(in srgb, black 4%, transparent);min-width: 300px;-}\ No newline at end of file+}++/* Link preview card — portaled to body with position: fixed to escape+ * overflow:hidden containers (Card component, scrollable editors, etc.). */+.link-preview-card {+ display: flex;+ align-items: center;+ gap: 0.25rem;+ padding: 0.25rem 0.25rem 0.25rem 0.5rem;+ background: var(--popover);+ border: 1px solid color-mix(in srgb, var(--foreground) 10%, transparent);+ border-radius: var(--radius);+ box-shadow:+ 0 4px 12px color-mix(in srgb, black 12%, transparent),+ 0 0 0 1px color-mix(in srgb, black 4%, transparent);+ max-width: min(360px, calc(100vw - 2rem));+ white-space: nowrap;+}diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex f2dcc9d4c5..6af697e26d 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -39,8 +39,21 @@ import { createEditorExtensions } from "./extensions";import { uploadAndInsertFile } from "./extensions/file-upload";import { preprocessMarkdown } from "./utils/preprocess";import { EditorBubbleMenu } from "./bubble-menu";+import { EditorLinkPreview } from "./link-preview";import "./content-editor.css";+// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/** Blob URLs (blob:http://…) are process-local and expire on reload. Strip them+ * from serialised markdown so they never reach the database. */+const BLOB_IMAGE_RE = /!\[[^\]]*\]\(blob:[^)]*\)\n?/g;++function stripBlobUrls(md: string): string {+ return md.replace(BLOB_IMAGE_RE, "");+}+// ---------------------------------------------------------------------------// Types// ---------------------------------------------------------------------------@@ -62,6 +75,8 @@ interface ContentEditorRef {clearContent: () => void;focus: () => void;uploadFile: (file: File) => void;+ /** True when file uploads are still in progress. */+ hasActiveUploads: () => boolean;}// ---------------------------------------------------------------------------@@ -114,7 +129,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(if (!onUpdateRef.current) return;if (debounceRef.current) clearTimeout(debounceRef.current);debounceRef.current = setTimeout(() => {- onUpdateRef.current?.(ed.getMarkdown());+ onUpdateRef.current?.(stripBlobUrls(ed.getMarkdown()));}, debounceMs);},onBlur: () => {@@ -131,33 +146,25 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(const href = link?.getAttribute("href");if (!href || href.startsWith("mention://")) return false;- const openLink = () => {- if (href.startsWith("/")) {- // Internal path — dispatch custom event so the app can handle it- // (direct window.open breaks in Electron hash router)- window.dispatchEvent(- new CustomEvent("multica:navigate", { detail: { path: href } }),- );- } else {- window.open(href, "_blank", "noopener,noreferrer");- }- };-- if (!editable) {- // Readonly: any click on link opens new tab- event.preventDefault();- openLink();- return true;+ if (editable) {+ // Edit mode: don't open link on click. ProseMirror's+ // mousedown/mouseup cycle (already completed by the time+ // this click handler runs) places the cursor on the link.+ // LinkBubbleMenu detects cursor-on-link and shows the+ // preview card with Open / Copy / Edit actions.+ return false;}- if (event.metaKey || event.ctrlKey) {- // Edit mode: Cmd/Ctrl+click opens link- event.preventDefault();- openLink();- return true;+ // Readonly mode: open immediately.+ event.preventDefault();+ if (href.startsWith("/")) {+ window.dispatchEvent(+ new CustomEvent("multica:navigate", { detail: { path: href } }),+ );+ } else {+ window.open(href, "_blank", "noopener,noreferrer");}-- return false;+ return true;},},attributes: {@@ -192,7 +199,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(}, [editor, editable, defaultValue]);useImperativeHandle(ref, () => ({- getMarkdown: () => editor?.getMarkdown() ?? "",+ getMarkdown: () => stripBlobUrls(editor?.getMarkdown() ?? ""),clearContent: () => {editor?.commands.clearContent();},@@ -204,6 +211,15 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(const endPos = editor.state.doc.content.size;uploadAndInsertFile(editor, file, onUploadFileRef.current, endPos);},+ hasActiveUploads: () => {+ if (!editor) return false;+ let uploading = false;+ editor.state.doc.descendants((node) => {+ if (node.attrs.uploading) uploading = true;+ return !uploading;+ });+ return uploading;+ },}));if (!editor) return null;@@ -211,7 +227,12 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(return (<div className="relative min-h-full"><EditorContent editor={editor} />- {editable && <EditorBubbleMenu editor={editor} />}+ {editable && (+ <>+ <EditorBubbleMenu editor={editor} />+ <EditorLinkPreview editor={editor} />+ </>+ )}</div>);},diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.tsindex 9f69ab7d29..eeccaf6a8e 100644--- a/packages/views/editor/extensions/index.ts+++ b/packages/views/editor/extensions/index.ts@@ -47,9 +47,10 @@ import { ImageView } from "./image-view";const lowlight = createLowlight(common);const LinkEditable = Link.extend({ inclusive: false }).configure({- openOnClick: true,+ openOnClick: false,autolink: true,- linkOnPaste: false,+ linkOnPaste: true,+ defaultProtocol: "https",});const LinkReadonly = Link.configure({@@ -103,6 +104,9 @@ export function createEditorExtensions(return ReactNodeViewRenderer(CodeBlockView);},}).configure({ lowlight }),+ // ⚠️ Link MUST appear before markdownPaste in this array.+ // linkOnPaste relies on Link's handlePaste plugin firing first;+ // markdownPaste's handlePaste is a catch-all that returns true.editable ? LinkEditable : LinkReadonly,ImageExtension,Table.configure({ resizable: false }),diff --git a/packages/views/editor/extensions/markdown-paste.ts b/packages/views/editor/extensions/markdown-paste.tsindex 00132ce205..fa3811eded 100644--- a/packages/views/editor/extensions/markdown-paste.ts+++ b/packages/views/editor/extensions/markdown-paste.ts@@ -40,6 +40,9 @@ export function createMarkdownPasteExtension() {const clipboard = event.clipboardData;if (!clipboard) return false;+ // If clipboard has files, defer to the fileUpload extension.+ if (clipboard.files?.length) return false;+const text = clipboard.getData("text/plain");if (!text) return false;diff --git a/packages/views/editor/link-preview.tsx b/packages/views/editor/link-preview.tsxnew file mode 100644index 0000000000..622b3acc24--- /dev/null+++ b/packages/views/editor/link-preview.tsx@@ -0,0 +1,307 @@+"use client";++/**+ * Link preview system — floating card for link inspection.+ *+ * Two entry points, same UI:+ * - EditorLinkPreview: editable ContentEditor (cursor on link)+ * - ReadonlyLinkWrapper: ReadonlyContent (click on link)+ *+ * Both use @floating-ui/react-dom (useFloating + autoUpdate) portaled+ * to document.body. This escapes ALL overflow:hidden ancestors while+ * autoUpdate keeps the card anchored across any ancestor scroll.+ */++import {+ useState,+ useEffect,+ useCallback,+ useRef,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import { useFloating, offset, flip, shift, autoUpdate } from "@floating-ui/react-dom";+import { getOverflowAncestors } from "@floating-ui/dom";+import { ExternalLink, Copy } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@multica/ui/components/ui/button";+import type { Editor } from "@tiptap/core";++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function openLink(href: string) {+ if (href.startsWith("/")) {+ window.dispatchEvent(+ new CustomEvent("multica:navigate", { detail: { path: href } }),+ );+ } else {+ window.open(href, "_blank", "noopener,noreferrer");+ }+}++function truncateUrl(url: string, max = 48): string {+ if (url.length <= max) return url;+ try {+ const u = new URL(url);+ const origin = u.origin;+ const rest = url.slice(origin.length);+ if (rest.length <= 10) return url;+ return `${origin}${rest.slice(0, max - origin.length - 1)}…`;+ } catch {+ return `${url.slice(0, max - 1)}…`;+ }+}++// ---------------------------------------------------------------------------+// LinkPreviewCard — pure UI+// ---------------------------------------------------------------------------++function LinkPreviewCard({+ href,+ onMouseDown,+}: {+ href: string;+ onMouseDown?: (e: React.MouseEvent) => void;+}) {+ const handleCopy = useCallback(+ async (e: React.MouseEvent) => {+ e.stopPropagation();+ try {+ await navigator.clipboard.writeText(href);+ toast.success("Link copied");+ } catch {+ toast.error("Failed to copy");+ }+ },+ [href],+ );++ const handleOpen = useCallback(+ (e: React.MouseEvent) => {+ e.stopPropagation();+ openLink(href);+ },+ [href],+ );++ return (+ <div className="link-preview-card" onMouseDown={onMouseDown}>+ <span+ className="min-w-0 flex-1 truncate text-xs text-muted-foreground px-1"+ title={href}+ >+ {truncateUrl(href)}+ </span>+ <Button+ size="icon-xs"+ variant="ghost"+ className="text-muted-foreground"+ onClick={handleCopy}+ title="Copy link"+ >+ <Copy className="size-3.5" />+ </Button>+ <Button+ size="icon-xs"+ variant="ghost"+ className="text-muted-foreground"+ onClick={handleOpen}+ title="Open link"+ >+ <ExternalLink className="size-3.5" />+ </Button>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Shared hooks+// ---------------------------------------------------------------------------++function useCloseOnOutsideClick(active: boolean, close: () => void) {+ useEffect(() => {+ if (!active) return;+ const handle = (e: MouseEvent) => {+ if ((e.target as HTMLElement).closest(".link-preview-card")) return;+ close();+ };+ const t = setTimeout(() => document.addEventListener("mousedown", handle), 0);+ return () => {+ clearTimeout(t);+ document.removeEventListener("mousedown", handle);+ };+ }, [active, close]);+}++function useCloseOnEscape(active: boolean, close: () => void) {+ useEffect(() => {+ if (!active) return;+ const handle = (e: KeyboardEvent) => {+ if (e.key === "Escape") close();+ };+ document.addEventListener("keydown", handle);+ return () => document.removeEventListener("keydown", handle);+ }, [active, close]);+}++// ---------------------------------------------------------------------------+// EditorLinkPreview — for editable ContentEditor+// ---------------------------------------------------------------------------++function EditorLinkPreview({ editor }: { editor: Editor }) {+ const [visible, setVisible] = useState(false);+ const [href, setHref] = useState("");++ const close = useCallback(() => setVisible(false), []);++ const virtualRef = useRef({+ getBoundingClientRect: () => new DOMRect(),+ contextElement: editor.view.dom,+ });++ const { refs, floatingStyles, isPositioned, update } = useFloating({+ strategy: "fixed",+ placement: "bottom",+ open: visible,+ middleware: [offset(4), flip(), shift({ padding: 8 })],+ elements: { reference: virtualRef.current },+ whileElementsMounted: autoUpdate,+ });++ useEffect(() => {+ const check = () => {+ if (!editor.isEditable) {+ setVisible(false);+ return;+ }+ if (!editor.state.selection.empty || !editor.isActive("link")) {+ setVisible(false);+ return;+ }+ const linkHref = (editor.getAttributes("link").href as string) || "";+ if (!linkHref) {+ setVisible(false);+ return;+ }++ const coords = editor.view.coordsAtPos(editor.state.selection.from);+ virtualRef.current = {+ getBoundingClientRect: () =>+ new DOMRect(coords.left, coords.top, 0, coords.bottom - coords.top),+ contextElement: editor.view.dom,+ };++ setHref(linkHref);+ setVisible(true);+ update();+ };++ editor.on("selectionUpdate", check);+ return () => { editor.off("selectionUpdate", check); };+ }, [editor, update]);++ // Close on any ancestor scroll or window resize+ useEffect(() => {+ if (!visible) return;+ const close = () => {+ setVisible(false);+ };+ const ancestors = getOverflowAncestors(editor.view.dom);+ ancestors.forEach((el) => el.addEventListener("scroll", close, { passive: true }));+ window.addEventListener("resize", close);+ return () => {+ ancestors.forEach((el) => el.removeEventListener("scroll", close));+ window.removeEventListener("resize", close);+ };+ }, [visible, editor]);++ useCloseOnOutsideClick(visible, close);+ useCloseOnEscape(visible, close);++ return createPortal(+ <div+ ref={refs.setFloating}+ style={{+ ...floatingStyles,+ zIndex: 50,+ display: visible && isPositioned ? undefined : "none",+ }}+ >+ <LinkPreviewCard href={href} onMouseDown={(e) => e.preventDefault()} />+ </div>,+ document.body,+ );+}++// ---------------------------------------------------------------------------+// ReadonlyLinkWrapper — for ReadonlyContent (react-markdown)+// ---------------------------------------------------------------------------++function ReadonlyLinkWrapper({+ href,+ children,+}: {+ href: string;+ children: ReactNode;+}) {+ const [open, setOpen] = useState(false);+ const anchorRef = useRef<HTMLAnchorElement>(null);++ const close = useCallback(() => setOpen(false), []);++ const { refs, floatingStyles } = useFloating({+ strategy: "fixed",+ placement: "bottom-start",+ middleware: [offset(4), flip(), shift({ padding: 8 })],+ elements: { reference: anchorRef.current },+ open,+ });++ const toggle = useCallback(+ (e: React.MouseEvent) => {+ e.preventDefault();+ e.stopPropagation();+ setOpen((v) => !v);+ },+ [],+ );++ // Close on any ancestor scroll+ useEffect(() => {+ if (!open || !anchorRef.current) return;+ const hide = () => setOpen(false);+ const ancestors = getOverflowAncestors(anchorRef.current);+ ancestors.forEach((el) => el.addEventListener("scroll", hide, { passive: true }));+ return () => {+ ancestors.forEach((el) => el.removeEventListener("scroll", hide));+ };+ }, [open]);++ useCloseOnOutsideClick(open, close);+ useCloseOnEscape(open, close);++ return (+ <>+ <a+ ref={anchorRef}+ href={href}+ onClick={toggle}+ role="button"+ aria-expanded={open}+ >+ {children}+ </a>+ {open &&+ createPortal(+ <div ref={refs.setFloating} style={{ ...floatingStyles, zIndex: 50 }}>+ <LinkPreviewCard href={href} />+ </div>,+ document.body,+ )}+ </>+ );+}++export { EditorLinkPreview, ReadonlyLinkWrapper, openLink };diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsxindex 97bd9020cb..5052e04a61 100644--- a/packages/views/editor/readonly-content.tsx+++ b/packages/views/editor/readonly-content.tsx@@ -33,6 +33,7 @@ import { cn } from "@multica/ui/lib/utils";import { useNavigation } from "../navigation";import { IssueMentionCard } from "../issues/components/issue-mention-card";import { ImageLightbox } from "./extensions/image-view";+import { ReadonlyLinkWrapper } from "./link-preview";import { preprocessMarkdown } from "./utils/preprocess";import "./content-editor.css";@@ -109,7 +110,7 @@ function IssueMentionLink({ issueId, label }: { issueId: string; label?: string}const components: Partial<Components> = {- // Links — route mention:// to mention components, others open in new tab+ // Links — route mention:// to mention components, others show preview carda: ({ href, children }) => {if (href?.startsWith("mention://")) {const match = href.match(@@ -128,18 +129,9 @@ const components: Partial<Components> = {return <span className="mention">{children}</span>;}- // Regular links — open in new tab- return (- <a- href={href}- onClick={(e) => {- e.preventDefault();- if (href) window.open(href, "_blank", "noopener,noreferrer");- }}- >- {children}- </a>- );+ // Regular links — show preview card on click+ if (!href) return <a>{children}</a>;+ return <ReadonlyLinkWrapper href={href}>{children}</ReadonlyLinkWrapper>;},// Images — centered with toolbar + lightbox (matches Tiptap ImageView NodeView)diff --git a/packages/views/editor/title-editor.tsx b/packages/views/editor/title-editor.tsxindex 971ec8d936..23b3ba8774 100644--- a/packages/views/editor/title-editor.tsx+++ b/packages/views/editor/title-editor.tsx@@ -90,7 +90,9 @@ const TitleEditor = forwardRef<TitleEditorRef, TitleEditorProps>(const editor = useEditor({immediatelyRender: false,- content: `<p>${defaultValue}</p>`,+ content: defaultValue+ ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: defaultValue }] }] }+ : "",extensions: [SingleLineDocument,Paragraph,diff --git a/packages/views/editor/utils/preprocess.ts b/packages/views/editor/utils/preprocess.tsindex db96c52eed..f9da68337a 100644--- a/packages/views/editor/utils/preprocess.ts+++ b/packages/views/editor/utils/preprocess.ts@@ -32,6 +32,10 @@ export function preprocessMarkdown(markdown: string): string {*/const FILE_LINK_LINE = /^\[([^\]]+)\]\((https?:\/\/[^)]+)\)$/;+function escapeAttr(s: string): string {+ return s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");+}+function preprocessFileCards(markdown: string): string {return markdown.split("\n")@@ -42,7 +46,7 @@ function preprocessFileCards(markdown: string): string {const filename = match[1]!;const url = match[2]!;if (!isFileCardUrl(url)) return line;- return `<div data-type="fileCard" data-href="${url}" data-filename="${filename}"></div>`;+ return `<div data-type="fileCard" data-href="${escapeAttr(url)}" data-filename="${escapeAttr(filename)}"></div>`;}).join("\n");}diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex b2b360628b..03cc44d773 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -267,7 +267,7 @@ function CommentRow({className="relative mt-1.5 pl-8"onKeyDown={(e) => { if (e.key === "Escape") cancelEdit(); }}>- <div className="max-h-48 overflow-y-auto text-sm leading-relaxed">+ <div className="text-sm leading-relaxed"><ContentEditorref={editEditorRef}defaultValue={entry.content ?? ""}@@ -484,7 +484,7 @@ function CommentCard({className="relative pl-10"onKeyDown={(e) => { if (e.key === "Escape") cancelEdit(); }}>- <div className="max-h-48 overflow-y-auto text-sm leading-relaxed">+ <div className="text-sm leading-relaxed"><ContentEditorref={editEditorRef}defaultValue={entry.content ?? ""}diff --git a/packages/views/package.json b/packages/views/package.jsonindex 5bd9e9f50e..c1e4add111 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -40,10 +40,11 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@floating-ui/dom": "^1.7.6",+ "@floating-ui/react-dom": "^2.1.8","@multica/core": "workspace:*","@multica/ui": "workspace:*","@tiptap/core": "^3.22.1",- "@tiptap/extension-bubble-menu": "^3.22.1",+"@tiptap/extension-code-block-lowlight": "^3.22.1","@tiptap/extension-document": "^3.22.1","@tiptap/extension-image": "^3.22.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2c158ea77a..4db6ff1f4e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -589,6 +589,9 @@ importers:'@floating-ui/dom':specifier: ^1.7.6version: 1.7.6+ '@floating-ui/react-dom':+ specifier: ^2.1.8'@multica/core':specifier: workspace:*version: link:../core@@ -601,9 +604,6 @@ importers:'@tiptap/core':specifier: ^3.22.1version: 3.22.1(@tiptap/[email protected])- '@tiptap/extension-bubble-menu':- specifier: ^3.22.1'@tiptap/extension-code-block-lowlight':specifier: ^3.22.1version: 3.22.1(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))(@tiptap/[email protected])([email protected])([email protected])@@ -8500,6 +8500,7 @@ snapshots:'@floating-ui/dom': 1.7.6'@tiptap/core': 3.22.1(@tiptap/[email protected])'@tiptap/pm': 3.22.1+ optional: true'@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':dependencies: