Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
"use client";
/**
* LinkHoverCard — floating card shown on link hover.
*
* Displays the URL with Copy and Open actions. Portaled to body
* with position:fixed to escape overflow:hidden containers.
* Shows after 300ms hover delay, hides after 150ms mouse-out
* (cancelled if mouse enters the card).
*/
import { useState, useEffect, useCallback, useRef } from "react";
import { createPortal } from "react-dom";
import { AnimatePresence, motion } from "motion/react";
import { computePosition, offset, flip, shift } from "@floating-ui/dom";
import { useReducedMotion } from "@multica/core/appearance";
import { ExternalLink, Copy } from "@multica/ui/icons";
import { toast } from "sonner";
import { IconButton } from "@multica/ui/components/common/icon-button";
import { copyText } from "@multica/ui/lib/clipboard";
import { UI_EASE_IN, UI_EASE_OUT, UI_MOTION_DURATION } from "@multica/ui/lib/motion";
import { useWorkspaceSlug } from "@multica/core/paths";
import { useAppOrigin } from "../navigation";
import { useT } from "../i18n";
import { openLink, isMentionHref } from "./utils/link-handler";
import { useEditorOverlayOwner } from "./overlay-owner";
import { useOpenAttachmentLink } from "./use-open-attachment-link";
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)}…`;
}
}
// Hook — manages hover state with enter/leave delays
const SHOW_DELAY = 300;
const HIDE_DELAY = 150;
interface HoverState {
visible: boolean;
href: string;
anchorEl: HTMLAnchorElement | null;
}
function useLinkHover(containerRef: React.RefObject<HTMLElement | null>, disabled?: boolean) {
const [state, setState] = useState<HoverState>({ visible: false, href: "", anchorEl: null });
const showTimer = useRef(0);
const hideTimer = useRef(0);
const cardRef = useRef<HTMLDivElement>(null);
const clearTimers = useCallback(() => {
clearTimeout(showTimer.current);
clearTimeout(hideTimer.current);
}, []);
// Container mouse events — detect <a> hover
useEffect(() => {
const container = containerRef.current;
if (!container || disabled) return;
const onMouseOver = (e: MouseEvent) => {
const target = e.target as HTMLElement;
const link = target.closest("a") as HTMLAnchorElement | null;
if (!link) return;
const href = link.getAttribute("href");
if (!href || isMentionHref(href)) return;
// Mention chips render as <a class="issue-mention"> / <a
// class="project-mention"> — they display their own rich info, so a URL
// hover card is redundant, and the URL it would offer to copy is an
// in-app path rather than the shareable link the user expects.
if (
link.classList.contains("issue-mention") ||
link.classList.contains("project-mention") ||
link.classList.contains("doc-mention")
) {
return;
}
clearTimeout(hideTimer.current);
showTimer.current = window.setTimeout(() => {
setState({ visible: true, href, anchorEl: link });
}, SHOW_DELAY);
};
const onMouseOut = (e: MouseEvent) => {
const related = e.relatedTarget as HTMLElement | null;
// Don't hide if mouse moved to the hover card
if (related && cardRef.current?.contains(related)) return;
// Don't hide if mouse moved to another part of the same link
const link = (e.target as HTMLElement).closest("a");
if (link && link.contains(related)) return;
clearTimeout(showTimer.current);
hideTimer.current = window.setTimeout(() => {
setState((s) => ({ ...s, visible: false }));
}, HIDE_DELAY);
};
container.addEventListener("mouseover", onMouseOver);
container.addEventListener("mouseout", onMouseOut);
return () => {
container.removeEventListener("mouseover", onMouseOver);
container.removeEventListener("mouseout", onMouseOut);
clearTimers();
};
}, [containerRef, disabled, clearTimers]);
// Card mouse events — keep visible while hovering the card
const onCardEnter = useCallback(() => {
clearTimeout(hideTimer.current);
}, []);
const onCardLeave = useCallback(() => {
hideTimer.current = window.setTimeout(() => {
setState((s) => ({ ...s, visible: false }));
}, HIDE_DELAY);
}, []);
return { ...state, cardRef, onCardEnter, onCardLeave };
}
// Component
function LinkHoverCard({
visible,
href,
anchorEl,
cardRef,
onCardEnter,
onCardLeave,
}: {
visible: boolean;
href: string;
anchorEl: HTMLAnchorElement | null;
cardRef: React.RefObject<HTMLDivElement | null>;
onCardEnter: () => void;
onCardLeave: () => void;
}) {
const [pos, setPos] = useState({ top: 0, left: 0 });
const [positioned, setPositioned] = useState(false);
const reduceMotion = useReducedMotion();
const slug = useWorkspaceSlug();
const appOrigin = useAppOrigin();
const { t } = useT("editor");
const overlayOwner = useEditorOverlayOwner();
const attachmentLink = useOpenAttachmentLink();
// Position the card when the portal div is mounted (ref callback).
// Using useEffect would race with portal rendering — the div might
// not be in the DOM yet when the effect runs.
const setCardRef = useCallback(
(node: HTMLDivElement | null) => {
(cardRef as React.MutableRefObject<HTMLDivElement | null>).current = node;
if (!node || !anchorEl) {
setPositioned(false);
return;
}
computePosition(anchorEl, node, {
placement: "bottom-start",
strategy: "fixed",
middleware: [offset(4), flip(), shift({ padding: 8 })],
}).then(({ x, y }) => {
setPos({ top: y, left: x });
setPositioned(true);
});
},
[anchorEl, cardRef],
);
// Reset positioned when hidden
useEffect(() => {
if (!visible) setPositioned(false);
}, [visible]);
const handleCopy = async (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
if (await copyText(href)) {
toast.success(t(($) => $.link_hover.link_copied));
} else {
toast.error(t(($) => $.link_hover.copy_failed));
}
};
const handleOpen = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
if (attachmentLink.open(href)) return;
openLink(href, slug, appOrigin);
};
// The viewer keeps one position in the tree whether or not the card shows:
// the card hides as soon as the pointer leaves it, which must not remount
// the viewer opened from it.
return (
<>
{attachmentLink.modal}
{typeof document !== "undefined" &&
createPortal(
<AnimatePresence>
{visible && anchorEl && (
<motion.div
key="link-hover-card"
ref={setCardRef}
className="link-hover-card"
data-editor-overlay-owner={overlayOwner}
initial={reduceMotion ? false : { opacity: 0, y: 4, scale: 0.97 }}
animate={
positioned
? {
opacity: 1,
y: 0,
scale: 1,
transition: { duration: reduceMotion ? 0 : UI_MOTION_DURATION.fast, ease: UI_EASE_OUT },
}
: { opacity: 0 }
}
exit={
reduceMotion
? { opacity: 0, transition: { duration: 0 } }
: {
opacity: 0,
y: 3,
scale: 0.97,
transition: { duration: UI_MOTION_DURATION.micro, ease: UI_EASE_IN },
}
}
style={{
position: "fixed",
top: pos.top,
left: pos.left,
zIndex: 50,
visibility: positioned ? "visible" : "hidden",
}}
onMouseEnter={onCardEnter}
onMouseLeave={onCardLeave}
>
<span
className="min-w-0 flex-1 truncate text-caption text-muted-foreground px-1"
title={href}
>
{truncateUrl(href)}
</span>
<IconButton
size="icon-xs"
variant="ghost"
className="text-muted-foreground"
onClick={handleCopy}
label={t(($) => $.link_hover.copy_link)}
>
<Copy className="size-3.5" />
</IconButton>
<IconButton
size="icon-xs"
variant="ghost"
className="text-muted-foreground"
onClick={handleOpen}
label={t(($) => $.link_hover.open_link)}
>
<ExternalLink className="size-3.5" />
</IconButton>
</motion.div>
)}
</AnimatePresence>,
document.body,
)}
</>
);
}
export { useLinkHover, LinkHoverCard };