diff --git a/apps/desktop/src/components/CwdSwitcher.tsx b/apps/desktop/src/components/CwdSwitcher.tsx index 69ec458..5c61f60 100644 --- a/apps/desktop/src/components/CwdSwitcher.tsx +++ b/apps/desktop/src/components/CwdSwitcher.tsx @@ -1,9 +1,9 @@ -import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; -import { VscChevronRight, VscFolder, VscFolderOpened } from "react-icons/vsc"; +import { useEffect, useRef, useState } from "react"; +import { VscChevronRight, VscCopy, VscFolder, VscFolderOpened } from "react-icons/vsc"; -import { Check, ChevronsUpDown, Search, joinPath, parentDirectories } from "@opencollab/ui"; +import { Check, ChevronsUpDown, PopoverMenu, Search, joinPath, parentDirectories } from "@opencollab/ui"; import { listSubdirectories } from "../services/terminalApi"; +import { copyTextToClipboard } from "../services/terminalClipboard"; type Props = { cwd: string; @@ -14,27 +14,37 @@ type Props = { /// Con más subcarpetas que esto se muestra un filtro. const FILTER_FROM = 8; +const COPIED_FEEDBACK_MS = 1500; type Subdirs = { state: "loading" } | { state: "error"; message: string } | { state: "ok"; names: string[] }; /// Ruta del header de una terminal: menú para ir hacia atrás (`..`, directorios -/// padre) o hacia adelante (subcarpetas). +/// padre) o hacia adelante (subcarpetas), y acción para copiar la ruta actual. export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) { const [open, setOpen] = useState(false); - const [position, setPosition] = useState<{ left: number; top: number } | null>(null); + const [copied, setCopied] = useState(false); const [subdirs, setSubdirs] = useState({ state: "loading" }); const [filter, setFilter] = useState(""); const buttonRef = useRef(null); - const menuRef = useRef(null); + const copyTimerRef = useRef(null); const parents = parentDirectories(cwd); - // El panel recorta su contenido (overflow: hidden): el menú va en un portal - // con posición fija, debajo del botón. - useLayoutEffect(() => { - if (!open || !buttonRef.current) return; - const r = buttonRef.current.getBoundingClientRect(); - setPosition({ left: r.left, top: r.bottom + 4 }); - }, [open]); + useEffect(() => { + return () => { + if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current); + }; + }, []); + + const copyPath = async () => { + const ok = await copyTextToClipboard(cwd); + if (!ok) return; + setCopied(true); + if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current); + copyTimerRef.current = window.setTimeout(() => { + setCopied(false); + copyTimerRef.current = null; + }, COPIED_FEEDBACK_MS); + }; // Las subcarpetas se piden al abrir: el disco pudo cambiar desde la última vez. useEffect(() => { @@ -50,24 +60,6 @@ export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) { }; }, [open, cwd]); - useEffect(() => { - if (!open) return; - const onDown = (e: PointerEvent) => { - const t = e.target as Node; - if (!menuRef.current?.contains(t) && !buttonRef.current?.contains(t)) setOpen(false); - }; - const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false); - const close = () => setOpen(false); - document.addEventListener("pointerdown", onDown); - document.addEventListener("keydown", onKey); - window.addEventListener("resize", close); - return () => { - document.removeEventListener("pointerdown", onDown); - document.removeEventListener("keydown", onKey); - window.removeEventListener("resize", close); - }; - }, [open]); - // Si la shell deja de estar disponible (arranca un agente), cerrar el menú. useEffect(() => { if (disabledReason) setOpen(false); @@ -98,90 +90,103 @@ export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) { {cwd} + - {open && - position && - createPortal( -
-
- - {cwd} - - - -
+ setOpen(false)} anchorRef={buttonRef} align="left"> +
+ + {cwd} + + + +
+ - {/* Hacia adelante: subcarpetas del directorio actual. */} -
-
Subdirectories
- {subdirs.state === "ok" && subdirs.names.length > FILTER_FROM && ( - - )} -
- {subdirs.state === "loading" &&
Cargando…
} - {subdirs.state === "error" && ( -
- No se pudo leer la carpeta -
- )} - {subdirs.state === "ok" && visible.length === 0 && ( -
- {subdirs.names.length === 0 ? "Sin subcarpetas" : "Sin coincidencias"} -
- )} - {visible.map((name) => ( - - ))} + {/* Hacia adelante: subcarpetas del directorio actual. */} +
+
Subdirectories
+ {subdirs.state === "ok" && subdirs.names.length > FILTER_FROM && ( + + )} +
+ {subdirs.state === "loading" &&
Cargando…
} + {subdirs.state === "error" && ( +
+ No se pudo leer la carpeta
+ )} + {subdirs.state === "ok" && visible.length === 0 && ( +
+ {subdirs.names.length === 0 ? "Sin subcarpetas" : "Sin coincidencias"} +
+ )} + {visible.map((name) => ( + + ))} +
- {/* Hacia atrás: `..` y todos los directorios padre. */} - {parents.length > 0 && ( - <> -
-
Parent directories
- - {parents.map((path) => ( - - ))} - - )} -
, - document.body, + {/* Hacia atrás: `..` y todos los directorios padre. */} + {parents.length > 0 && ( + <> +
+
Parent directories
+ + {parents.map((path) => ( + + ))} + )} + ); } diff --git a/apps/desktop/src/components/NewTerminalMenu.tsx b/apps/desktop/src/components/NewTerminalMenu.tsx index 9bb6fec..50fb94c 100644 --- a/apps/desktop/src/components/NewTerminalMenu.tsx +++ b/apps/desktop/src/components/NewTerminalMenu.tsx @@ -1,8 +1,15 @@ -import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; +import { useEffect, useRef, useState } from "react"; import { VscFolderOpened, VscHome } from "react-icons/vsc"; -import { Plus, TerminalIcon, agentInfo, modKey, shiftKey, type AgentId } from "@opencollab/ui"; +import { + Plus, + PopoverMenu, + TerminalIcon, + agentInfo, + modKey, + shiftKey, + type AgentId, +} from "@opencollab/ui"; import { availableAgents } from "../services/terminalApi"; type Props = { @@ -17,18 +24,8 @@ type Props = { /// por defecto, o directamente un agente instalado (corre dentro de la shell). export function NewTerminalMenu({ cwd, onOpen }: Props) { const [open, setOpen] = useState(false); - const [position, setPosition] = useState<{ right: number; top: number } | null>(null); const [agents, setAgents] = useState([]); const buttonRef = useRef(null); - const menuRef = useRef(null); - - // Mismo motivo que en CwdSwitcher: el panel recorta (overflow: hidden), así que - // el menú va en un portal con posición fija, alineado al borde derecho del botón. - useLayoutEffect(() => { - if (!open || !buttonRef.current) return; - const r = buttonRef.current.getBoundingClientRect(); - setPosition({ right: window.innerWidth - r.right, top: r.bottom + 4 }); - }, [open]); // Se consulta al abrir por primera vez (el núcleo lo cachea en `availableAgents`). useEffect(() => { @@ -40,24 +37,6 @@ export function NewTerminalMenu({ cwd, onOpen }: Props) { }; }, [open]); - useEffect(() => { - if (!open) return; - const onDown = (e: PointerEvent) => { - const t = e.target as Node; - if (!menuRef.current?.contains(t) && !buttonRef.current?.contains(t)) setOpen(false); - }; - const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false); - const close = () => setOpen(false); - document.addEventListener("pointerdown", onDown); - document.addEventListener("keydown", onKey); - window.addEventListener("resize", close); - return () => { - document.removeEventListener("pointerdown", onDown); - document.removeEventListener("keydown", onKey); - window.removeEventListener("resize", close); - }; - }, [open]); - const choose = (dir: string | null, agent?: AgentId) => { setOpen(false); onOpen(dir, agent); @@ -77,53 +56,58 @@ export function NewTerminalMenu({ cwd, onOpen }: Props) { - {open && - position && - createPortal( -
-
New terminal
- - - {agents.length > 0 && ( - <> -
Launch agent{cwd ? " here" : ""}
- {agents.map((id) => ( - - ))} - - )} -
, - document.body, + setOpen(false)} + anchorRef={buttonRef} + align="right" + className="new-terminal-menu" + > +
New terminal
+ + + {agents.length > 0 && ( + <> +
Launch agent{cwd ? " here" : ""}
+ {agents.map((id) => ( + + ))} + )} +
); } diff --git a/apps/desktop/src/components/TerminalPane.tsx b/apps/desktop/src/components/TerminalPane.tsx index 21c23fc..2bc21ee 100644 --- a/apps/desktop/src/components/TerminalPane.tsx +++ b/apps/desktop/src/components/TerminalPane.tsx @@ -9,14 +9,17 @@ import { Maximize, Minus, Panel, + PopoverMenu, TerminalIcon, agentInfo, applyActivity, applyFocus, cdCommand, + clampMenuPosition, initialActivity, isWatching, localUser, + modKey, parseOsc7, statusLabel, type ActivityState, @@ -36,6 +39,11 @@ import { resizeTerminal, writeTerminal, } from "../services/terminalApi"; +import { + copyTerminalSelection, + createTerminalKeyEventHandler, + pasteFromClipboard, +} from "../services/terminalClipboard"; type Props = { paneId: string; @@ -102,6 +110,11 @@ export function TerminalPane(props: Props) { const branch = useGitBranch(cwd, activityState.activity === "idle"); const [status, setStatus] = useState("starting"); const [error, setError] = useState(null); + const [contextMenu, setContextMenu] = useState<{ + left: number; + top: number; + hasSelection: boolean; + } | null>(null); useEffect(() => onStatus(paneId, status), [paneId, status, onStatus]); useEffect( @@ -144,6 +157,24 @@ export function TerminalPane(props: Props) { const fit = new FitAddon(); term.loadAddon(fit); term.open(container); + term.attachCustomKeyEventHandler(createTerminalKeyEventHandler(term)); + + const onContextMenu = (e: MouseEvent) => { + e.preventDefault(); + props.onFocus(); + const { left, top } = clampMenuPosition( + e.clientX, + e.clientY, + window.innerWidth, + window.innerHeight, + ); + setContextMenu({ + left, + top, + hasSelection: term.hasSelection(), + }); + }; + container.addEventListener("contextmenu", onContextMenu); // fit() con el contenedor oculto (0x0) deja la terminal en 1 columna. const fitIfVisible = () => { @@ -213,6 +244,7 @@ export function TerminalPane(props: Props) { return () => { disposed = true; + container.removeEventListener("contextmenu", onContextMenu); osc7.dispose(); observer.disconnect(); input.dispose(); @@ -303,16 +335,87 @@ export function TerminalPane(props: Props) { ); return ( - props.registerEl(paneId, el)} - className={classes} - hidden={props.hidden} - style={{ order: props.order }} - // pointerdown y no mousedown: el arrastre cancela los eventos de mouse del header. - onPointerDown={props.onFocus} - header={header} - bodyRef={containerRef} - bodyClassName="pane-body" - /> + <> + props.registerEl(paneId, el)} + className={classes} + hidden={props.hidden} + style={{ order: props.order }} + // pointerdown y no mousedown: el arrastre cancela los eventos de mouse del header. + onPointerDown={props.onFocus} + header={header} + bodyRef={containerRef} + bodyClassName="pane-body" + /> + setContextMenu(null)} + position={contextMenu ? { left: contextMenu.left, top: contextMenu.top } : null} + className="term-context-menu" + > + + +
+ + + + ); } diff --git a/apps/desktop/src/services/terminalClipboard.test.ts b/apps/desktop/src/services/terminalClipboard.test.ts new file mode 100644 index 0000000..724b1ab --- /dev/null +++ b/apps/desktop/src/services/terminalClipboard.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + copyTextToClipboard, + createTerminalKeyEventHandler, + pasteFromClipboard, + type ClipboardAdapter, + type TerminalLike, +} from "./terminalClipboard"; + +function makeTerm(selection = ""): TerminalLike & { + pasted: string[]; + clearedSelection: number; + selectedAll: number; + clearedBuffer: number; +} { + let currentSelection = selection; + const term = { + pasted: [] as string[], + clearedSelection: 0, + selectedAll: 0, + clearedBuffer: 0, + hasSelection: () => currentSelection.length > 0, + getSelection: () => currentSelection, + clearSelection: () => { + currentSelection = ""; + term.clearedSelection += 1; + }, + paste: (data: string) => { + term.pasted.push(data); + }, + selectAll: () => { + term.selectedAll += 1; + }, + clear: () => { + term.clearedBuffer += 1; + }, + }; + return term; +} + +function makeKeyEvent( + overrides: Partial & { key: string }, +): KeyboardEvent & { defaultPrevented: boolean } { + const event = { + type: "keydown", + ctrlKey: false, + metaKey: false, + shiftKey: false, + altKey: false, + defaultPrevented: false, + preventDefault() { + this.defaultPrevented = true; + }, + ...overrides, + }; + return event as unknown as KeyboardEvent & { defaultPrevented: boolean }; +} + +describe("terminalClipboard", () => { + it("Ctrl+C with active selection copies text, clears selection, and blocks SIGINT", async () => { + const term = makeTerm("hello world"); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue(""), + }; + const handler = createTerminalKeyEventHandler(term, clipboard); + const event = makeKeyEvent({ key: "c", ctrlKey: true }); + + const allowXterm = handler(event); + + expect(allowXterm).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledWith("hello world"); + expect(term.clearedSelection).toBe(1); + }); + + it("Ctrl+C without selection passes through to xterm so SIGINT reaches the PTY", () => { + const term = makeTerm(""); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue(""), + }; + const handler = createTerminalKeyEventHandler(term, clipboard); + const event = makeKeyEvent({ key: "c", ctrlKey: true }); + + const allowXterm = handler(event); + + expect(allowXterm).toBe(true); + expect(clipboard.writeText).not.toHaveBeenCalled(); + }); + + it("Ctrl+Shift+C always blocks PTY input and copies when selection exists", () => { + const termWithSel = makeTerm("selected output"); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue(""), + }; + const handlerWithSel = createTerminalKeyEventHandler(termWithSel, clipboard); + + expect(handlerWithSel(makeKeyEvent({ key: "C", ctrlKey: true, shiftKey: true }))).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledWith("selected output"); + expect(termWithSel.clearedSelection).toBe(1); + + const termEmpty = makeTerm(""); + const handlerEmpty = createTerminalKeyEventHandler(termEmpty, clipboard); + expect(handlerEmpty(makeKeyEvent({ key: "C", ctrlKey: true, shiftKey: true }))).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledTimes(1); + }); + + it("Ctrl+V and Ctrl+Shift+V prevent default browser paste, read clipboard, and paste into terminal", async () => { + const term = makeTerm(""); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue("npm test"), + }; + const handler = createTerminalKeyEventHandler(term, clipboard); + const ctrlV = makeKeyEvent({ key: "v", ctrlKey: true }); + + const allowXterm = handler(ctrlV); + + expect(allowXterm).toBe(false); + expect(ctrlV.defaultPrevented).toBe(true); + await vi.waitFor(() => { + expect(term.pasted).toEqual(["npm test"]); + }); + + const ctrlShiftV = makeKeyEvent({ key: "V", ctrlKey: true, shiftKey: true }); + expect(handler(ctrlShiftV)).toBe(false); + expect(ctrlShiftV.defaultPrevented).toBe(true); + await vi.waitFor(() => { + expect(term.pasted).toEqual(["npm test", "npm test"]); + }); + }); + + it("copyTextToClipboard and pasteFromClipboard handle clipboard operations safely", async () => { + const term = makeTerm(""); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue("copied path"), + }; + + expect(await copyTextToClipboard("C:\\Users\\facun", clipboard)).toBe(true); + expect(clipboard.writeText).toHaveBeenCalledWith("C:\\Users\\facun"); + + await pasteFromClipboard(term, clipboard); + expect(term.pasted).toEqual(["copied path"]); + }); +}); diff --git a/apps/desktop/src/services/terminalClipboard.ts b/apps/desktop/src/services/terminalClipboard.ts new file mode 100644 index 0000000..daa4942 --- /dev/null +++ b/apps/desktop/src/services/terminalClipboard.ts @@ -0,0 +1,107 @@ +export interface ClipboardAdapter { + writeText(text: string): Promise; + readText(): Promise; +} + +export interface TerminalLike { + hasSelection(): boolean; + getSelection(): string; + clearSelection(): void; + paste(data: string): void; + selectAll(): void; + clear(): void; +} + +const defaultClipboard: ClipboardAdapter = { + writeText: async (text: string) => { + if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + } + }, + readText: async () => { + if (typeof navigator !== "undefined" && navigator.clipboard?.readText) { + return navigator.clipboard.readText(); + } + return ""; + }, +}; + +export async function copyTextToClipboard( + text: string, + clipboard: ClipboardAdapter = defaultClipboard, +): Promise { + if (!text) return false; + try { + await clipboard.writeText(text); + return true; + } catch { + return false; + } +} + +export function copyTerminalSelection( + term: TerminalLike, + clipboard: ClipboardAdapter = defaultClipboard, +): boolean { + if (!term.hasSelection()) return false; + const selection = term.getSelection(); + if (!selection) return false; + void copyTextToClipboard(selection, clipboard); + term.clearSelection(); + return true; +} + +export async function pasteFromClipboard( + term: TerminalLike, + clipboard: ClipboardAdapter = defaultClipboard, +): Promise { + try { + const text = await clipboard.readText(); + if (text) term.paste(text); + } catch { + // El permiso de portapapeles puede fallar o estar vacío; se ignora sin romper la sesión. + } +} + +/// Manejador para `term.attachCustomKeyEventHandler`: +/// - `Ctrl+C` / `Cmd+C` con selección activa copia al portapapeles y evita mandar `SIGINT` (`\x03`). +/// - `Ctrl+C` / `Cmd+C` sin selección deja pasar el evento para interrumpir el proceso en el PTY. +/// - `Ctrl+Shift+C` siempre actúa como atajo explícito de copia y nunca envía `SIGINT`. +/// - `Ctrl+V` / `Ctrl+Shift+V` pega desde el portapapeles usando `term.paste` sin enviar `\x16`. +export function createTerminalKeyEventHandler( + term: TerminalLike, + clipboard: ClipboardAdapter = defaultClipboard, +): (e: KeyboardEvent) => boolean { + return (e: KeyboardEvent): boolean => { + const mod = e.ctrlKey || e.metaKey; + if (!mod || e.altKey) return true; + + const key = e.key.toLowerCase(); + + if (key === "c") { + if (e.shiftKey) { + if (e.type === "keydown") { + copyTerminalSelection(term, clipboard); + } + return false; + } + if (term.hasSelection()) { + if (e.type === "keydown") { + copyTerminalSelection(term, clipboard); + } + return false; + } + return true; + } + + if (key === "v") { + e.preventDefault(); + if (e.type === "keydown") { + void pasteFromClipboard(term, clipboard); + } + return false; + } + + return true; + }; +} diff --git a/packages/ui/src/components/PopoverMenu.tsx b/packages/ui/src/components/PopoverMenu.tsx new file mode 100644 index 0000000..d23f809 --- /dev/null +++ b/packages/ui/src/components/PopoverMenu.tsx @@ -0,0 +1,116 @@ +import { + useEffect, + useLayoutEffect, + useRef, + useState, + type ReactNode, + type RefObject, +} from "react"; +import { createPortal } from "react-dom"; + +export type MenuAlign = "left" | "right"; +export type MenuPosition = { left?: number; right?: number; top: number }; + +export function anchorMenuPosition( + rect: Pick, + align: MenuAlign = "left", + viewportWidth = typeof window !== "undefined" ? window.innerWidth : 0, + gap = 4, +): MenuPosition { + if (align === "right") { + return { + right: viewportWidth - rect.right, + top: rect.bottom + gap, + }; + } + return { + left: rect.left, + top: rect.bottom + gap, + }; +} + +export function clampMenuPosition( + clientX: number, + clientY: number, + viewportWidth: number, + viewportHeight: number, + menuWidth = 210, + menuHeight = 160, + margin = 8, +): { left: number; top: number } { + return { + left: Math.min(clientX, Math.max(margin, viewportWidth - menuWidth - margin)), + top: Math.min(clientY, Math.max(margin, viewportHeight - menuHeight - margin)), + }; +} + +type Props = { + open: boolean; + onClose: () => void; + /// Botón que abre el menú: el menú se ubica debajo suyo y los clics sobre él no disparan `onClose` acá. + anchorRef?: RefObject; + /// Alineación respecto de `anchorRef` (`left` en CwdSwitcher, `right` en NewTerminalMenu). + align?: MenuAlign; + /// Coordenadas fijas cuando el menú se abre en el cursor (p. ej. clic derecho en la terminal). + position?: MenuPosition | null; + className?: string; + children: ReactNode; +}; + +/// Menú flotante renderizado en un portal sobre `document.body` para no quedar +/// recortado por contenedores con `overflow: hidden`. Se cierra solo con clic +/// afuera (`pointerdown`), `Escape` o al redimensionar la ventana. +export function PopoverMenu({ + open, + onClose, + anchorRef, + align = "left", + position, + className, + children, +}: Props) { + const menuRef = useRef(null); + const onCloseRef = useRef(onClose); + onCloseRef.current = onClose; + const [anchorPos, setAnchorPos] = useState(null); + + useLayoutEffect(() => { + if (!open || position || !anchorRef?.current) return; + const rect = anchorRef.current.getBoundingClientRect(); + setAnchorPos(anchorMenuPosition(rect, align, window.innerWidth)); + }, [open, position, anchorRef, align]); + + useEffect(() => { + if (!open) return; + const onDown = (e: PointerEvent) => { + const target = e.target as Node; + if (menuRef.current?.contains(target)) return; + if (anchorRef?.current?.contains(target)) return; + onCloseRef.current(); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onCloseRef.current(); + }; + const onResize = () => onCloseRef.current(); + document.addEventListener("pointerdown", onDown); + document.addEventListener("keydown", onKey); + window.addEventListener("resize", onResize); + return () => { + document.removeEventListener("pointerdown", onDown); + document.removeEventListener("keydown", onKey); + window.removeEventListener("resize", onResize); + }; + }, [open, anchorRef]); + + const resolvedPosition = position ?? anchorPos; + if (!open || !resolvedPosition) return null; + + const classes = ["cwd-menu", className].filter(Boolean).join(" "); + + return createPortal( +
+ {children} +
, + document.body, + ); +} diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index 6c916ea..8c59dec 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -1,5 +1,6 @@ export * from "./components/Button"; export * from "./components/Panel"; +export * from "./components/PopoverMenu"; export * from "./components/StatusBar"; export * from "./components/TopBar"; export * from "./components/Sidebar"; diff --git a/packages/ui/src/popoverMenu.test.ts b/packages/ui/src/popoverMenu.test.ts new file mode 100644 index 0000000..7466e09 --- /dev/null +++ b/packages/ui/src/popoverMenu.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; + +import { anchorMenuPosition, clampMenuPosition } from "./components/PopoverMenu"; + +describe("PopoverMenu positioning", () => { + it("anchorMenuPosition aligns to left edge of anchor by default", () => { + const rect = { left: 40, right: 140, bottom: 32 }; + expect(anchorMenuPosition(rect, "left", 1024)).toEqual({ + left: 40, + top: 36, + }); + }); + + it("anchorMenuPosition aligns to right edge of anchor when align is right", () => { + const rect = { left: 800, right: 924, bottom: 32 }; + expect(anchorMenuPosition(rect, "right", 1024)).toEqual({ + right: 100, + top: 36, + }); + }); + + it("clampMenuPosition keeps context menu inside viewport bounds", () => { + expect(clampMenuPosition(100, 120, 1000, 800)).toEqual({ + left: 100, + top: 120, + }); + expect(clampMenuPosition(950, 760, 1000, 800, 210, 160)).toEqual({ + left: 782, + top: 632, + }); + }); +}); diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.css index d36cfeb..2e63359 100644 --- a/packages/ui/src/styles.css +++ b/packages/ui/src/styles.css @@ -854,6 +854,41 @@ kbd { flex: 1; min-width: 0; display: flex; + align-items: center; + gap: 2px; +} + +.cwd-copy-btn { + width: 22px; + height: 22px; + flex: none; +} + +.cwd-copy-btn svg { + width: 13px; + height: 13px; +} + +.cwd-copy-btn--copied { + color: var(--green); +} + +.term-context-menu { + min-width: 200px; +} + +.term-context-menu .cwd-item { + font-family: var(--font); + font-size: 13px; +} + +.term-context-menu .cwd-item:disabled { + opacity: 0.45; + cursor: default; +} + +.term-context-menu .cwd-item:disabled:hover { + background: transparent; } /* Ruta clickeable: mismo ⇅ que la tarjeta de usuario del sidebar. */