diff --git a/src/editor/lsp/hint.ts b/src/editor/lsp/hint.ts index 51fe15ed0f..cc19fc3dd5 100644 --- a/src/editor/lsp/hint.ts +++ b/src/editor/lsp/hint.ts @@ -4,7 +4,7 @@ * Dismissed by the next edit / caret move, Escape, or after a timeout. */ import { StateEffect, StateField, type Extension } from "@codemirror/state"; -import { EditorView, keymap, showTooltip, type Tooltip } from "@codemirror/view"; +import { EditorView, keymap, showTooltip, type Rect, type Tooltip } from "@codemirror/view"; import { Prec } from "@codemirror/state"; import { txTemplate } from "@/platform/i18n"; import { spinnerNode } from "@/ui/iconNode"; @@ -12,7 +12,11 @@ import { spinnerNode } from "@/ui/iconNode"; interface Hint { pos: number; /** Text, or DOM built when shown (with `destroy` when it holds e.g. a React root). */ - content: string | (() => HTMLElement | { dom: HTMLElement; destroy: () => void }); + content: + | string + | (() => + | HTMLElement + | { dom: HTMLElement; destroy?: () => void; resize?: boolean; positioned?: (space: Rect) => void }); tone: "info" | "error" | "warning"; /** Progress of a request still running (`data-pending` on the hint). */ pending?: boolean; @@ -58,7 +62,14 @@ const hintField = StateField.define({ return { dom }; } dom.appendChild(built.dom); - return { dom, destroy: built.destroy }; + return { + dom, + destroy: built.destroy, + get resize() { + return built.resize; + }, + positioned: built.positioned, + }; }, } : null, diff --git a/src/features/debugger/__tests__/valueHint.test.ts b/src/features/debugger/__tests__/valueHint.test.ts index 1e41084e61..43545ead6f 100644 --- a/src/features/debugger/__tests__/valueHint.test.ts +++ b/src/features/debugger/__tests__/valueHint.test.ts @@ -3,7 +3,7 @@ import { EditorState } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import type { DebugSessionId, Variable } from "@/bindings"; import { showHint } from "@/editor/lsp/hint"; -import { valueHint } from "../editor/valueTooltip"; +import { VALUE_TREE_MIN_HEIGHT, VALUE_TREE_MIN_WIDTH, VALUE_TREE_SIZE_KEY, valueHint } from "../editor/valueTooltip"; vi.mock("../ui/ValueHintTree", () => ({ mountValueTree: (host: HTMLElement) => { @@ -27,12 +27,20 @@ const expand = () => { button.click(); }; +const resizePointer = (target: EventTarget, type: string, x: number, y: number, buttons = 1) => { + const event = new MouseEvent(type, { clientX: x, clientY: y, bubbles: true, cancelable: true, button: 0, buttons }); + Object.defineProperty(event, "pointerId", { value: 1 }); + target.dispatchEvent(event); +}; + beforeEach(() => { vi.useFakeTimers(); + localStorage.removeItem(VALUE_TREE_SIZE_KEY); view = new EditorView({ state: EditorState.create({ doc: "order.total" }), parent: document.body }); }); afterEach(() => { view.destroy(); + localStorage.removeItem(VALUE_TREE_SIZE_KEY); vi.useRealTimers(); }); @@ -52,4 +60,111 @@ describe("value hint", () => { expect(pin).toHaveBeenCalled(); expect(document.querySelector(".tree")).toBeNull(); }); + + it("mounts 8 resize handles only after expanding into a value tree", () => { + showHint(view, () => valueHint(view, "order", order, session), { pos: 0 }); + expect(document.querySelectorAll(".cm-lsp-hint [data-resize]")).toHaveLength(0); + + expand(); + const handles = [...document.querySelectorAll(".cm-lsp-hint [data-resize]")]; + expect(handles.map((h) => h.dataset.resize)).toEqual(["n", "s", "w", "e", "nw", "ne", "sw", "se"]); + const separators = document.querySelectorAll('.cm-lsp-hint [role="separator"][aria-label="Resize"]'); + expect(separators).toHaveLength(1); + expect((separators[0] as HTMLElement).dataset.resize).toBe("se"); + }); + + it("resizes beyond 480px via the corner grip and saves the size to localStorage", () => { + showHint(view, () => valueHint(view, "order", order, session, 400, { expanded: true }), { + pos: 0, + timeout: null, + }); + const surface = document.querySelector(".cm-tooltip.cm-lsp-hint")!; + const card = surface.querySelector("[data-resize]")!.parentElement!; + vi.spyOn(surface, "getBoundingClientRect").mockReturnValue({ + x: 100, + y: 100, + left: 100, + top: 100, + right: 560, + bottom: 360, + width: 460, + height: 260, + toJSON: () => ({}), + }); + vi.spyOn(card, "getBoundingClientRect").mockReturnValue({ + x: 100, + y: 100, + left: 100, + top: 100, + right: 560, + bottom: 360, + width: 460, + height: 260, + toJSON: () => ({}), + }); + + const se = card.querySelector('[data-resize="se"]')!; + resizePointer(se, "pointerdown", 560, 360); + resizePointer(window, "pointermove", 700, 500); + resizePointer(window, "pointerup", 700, 500, 0); + + expect(card.hasAttribute("data-resized")).toBe(true); + expect([card.style.width, card.style.height]).toEqual(["600px", "400px"]); + expect(JSON.parse(localStorage.getItem(VALUE_TREE_SIZE_KEY)!)).toEqual({ w: 600, h: 400 }); + }); + + it("resizes from the left and top edges while keeping opposite edges anchored", () => { + showHint(view, () => valueHint(view, "order", order, session, 400, { expanded: true }), { + pos: 0, + timeout: null, + }); + const surface = document.querySelector(".cm-tooltip.cm-lsp-hint")!; + const card = surface.querySelector("[data-resize]")!.parentElement!; + const box = { + x: 200, + y: 150, + left: 200, + top: 150, + right: 660, + bottom: 410, + width: 460, + height: 260, + toJSON: () => ({}), + }; + vi.spyOn(surface, "getBoundingClientRect").mockImplementation(() => box); + vi.spyOn(card, "getBoundingClientRect").mockImplementation(() => box); + + const west = card.querySelector('[data-resize="w"]')!; + resizePointer(west, "pointerdown", 200, 250); + resizePointer(window, "pointermove", 120, 250); + resizePointer(window, "pointerup", 120, 250, 0); + + expect([surface.style.left, card.style.width, card.style.height]).toEqual(["120px", "540px", "260px"]); + + const north = card.querySelector('[data-resize="n"]')!; + resizePointer(north, "pointerdown", 300, 150); + resizePointer(window, "pointermove", 300, 90); + resizePointer(window, "pointerup", 300, 90, 0); + + expect([surface.style.top, card.style.width, card.style.height]).toEqual(["90px", "460px", "320px"]); + }); + + it("restores saved size on subsequent open and clamps below minimum bounds", () => { + localStorage.setItem(VALUE_TREE_SIZE_KEY, JSON.stringify({ w: 620, h: 380 })); + showHint(view, () => valueHint(view, "order", order, session, 400, { expanded: true }), { + pos: 0, + timeout: null, + }); + let card = document.querySelector(".cm-lsp-hint [data-resize]")!.parentElement!; + expect(card.hasAttribute("data-resized")).toBe(true); + expect([card.style.width, card.style.height]).toEqual(["620px", "380px"]); + + localStorage.setItem(VALUE_TREE_SIZE_KEY, JSON.stringify({ w: 100, h: 50 })); + showHint(view, () => valueHint(view, "order", order, session, 400, { expanded: true }), { + pos: 0, + timeout: null, + }); + card = document.querySelector(".cm-lsp-hint [data-resize]")!.parentElement!; + expect([card.style.width, card.style.height]).toEqual([`${VALUE_TREE_MIN_WIDTH}px`, `${VALUE_TREE_MIN_HEIGHT}px`]); + }); }); diff --git a/src/features/debugger/editor/editor.module.css b/src/features/debugger/editor/editor.module.css index fbb106f5a9..a995f6439e 100644 --- a/src/features/debugger/editor/editor.module.css +++ b/src/features/debugger/editor/editor.module.css @@ -190,6 +190,7 @@ margin-top: 1px; } .valueTooltipTree { + position: relative; display: flex; flex: 1 1 auto; min-height: 0; @@ -200,12 +201,104 @@ font-family: var(--font-ui); white-space: normal; } -:global(.cm-lsp-hint):has(> .valueTooltipTree) { +.valueTooltipTreeBody { + display: flex; + flex: 1 1 auto; + flex-direction: column; + min-width: 0; + min-height: 0; +} +.valueTooltipTree[data-resized] { + max-width: calc(100vw - 24px); + max-height: calc(100vh - 24px); +} +:global(.cm-tooltip.cm-lsp-hint):has(> .valueTooltipTree) { display: flex; flex-direction: column; + max-width: calc(100vw - 24px); + max-height: calc(100vh - 24px); padding: 0; overflow: hidden; } +.valueResizeGrip { + position: absolute; + right: 0; + bottom: 0; + z-index: 2; + width: 16px; + height: 16px; + cursor: nwse-resize; + touch-action: none; + background: linear-gradient( + 135deg, + transparent 55%, + var(--fg-faint) 55%, + var(--fg-faint) 62%, + transparent 62%, + transparent 72%, + var(--fg-faint) 72%, + var(--fg-faint) 79%, + transparent 79% + ); + opacity: 0.55; +} +.valueResizeGrip:hover { + opacity: 1; +} +.valueResizeEdge { + position: absolute; + z-index: 2; + touch-action: none; +} +.valueResizeN { + top: 0; + left: 10px; + right: 10px; + height: 4px; + cursor: ns-resize; +} +.valueResizeS { + bottom: 0; + left: 10px; + right: 16px; + height: 4px; + cursor: ns-resize; +} +.valueResizeW { + left: 0; + top: 10px; + bottom: 10px; + width: 4px; + cursor: ew-resize; +} +.valueResizeE { + right: 0; + top: 10px; + bottom: 16px; + width: 4px; + cursor: ew-resize; +} +.valueResizeNW { + top: 0; + left: 0; + width: 10px; + height: 10px; + cursor: nwse-resize; +} +.valueResizeNE { + top: 0; + right: 0; + width: 10px; + height: 10px; + cursor: nesw-resize; +} +.valueResizeSW { + bottom: 0; + left: 0; + width: 10px; + height: 10px; + cursor: nesw-resize; +} :global(.cm-lsp-hint):has(> .valueTooltip) { padding: 0; } diff --git a/src/features/debugger/editor/valueTooltip.ts b/src/features/debugger/editor/valueTooltip.ts index cd9e28fbba..917ee08109 100644 --- a/src/features/debugger/editor/valueTooltip.ts +++ b/src/features/debugger/editor/valueTooltip.ts @@ -6,7 +6,15 @@ import { syntaxTree } from "@codemirror/language"; import type { EditorState, Extension } from "@codemirror/state"; import type { DebugSessionId, Variable } from "@/bindings"; -import { closeHoverTooltips, hoverTooltip, ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view"; +import { + closeHoverTooltips, + hoverTooltip, + repositionTooltips, + ViewPlugin, + type EditorView, + type Rect, + type ViewUpdate, +} from "@codemirror/view"; import { hideHint, showHint } from "@/editor/lsp/hint"; import { workflowSettings } from "@/platform/workflowSettings"; import { navigationModifierHeld } from "@/platform/navigationModifier"; @@ -14,12 +22,60 @@ import { activeSession, evaluate, useDebug } from "../state"; import { inlineValue, shownValue } from "../values"; import { tx } from "@/platform/i18n"; import { iconMarkup, selectableText } from "@/ui"; +import { lockDragCursor, type DragCursor } from "@/ui/dragCursor"; import { iconNode } from "@/ui/iconNode"; import { mountValueTree } from "../ui/ValueHintTree"; import styles from "./editor.module.css"; const BASE_HOVER = 100; const IDENT = /[\p{L}\p{N}_$]/u; +export const VALUE_TREE_SIZE_KEY = "openidea.debugger.valueTreeSize.v1"; +export const VALUE_TREE_MIN_WIDTH = 280; +export const VALUE_TREE_MIN_HEIGHT = 120; +const VIEWPORT_MARGIN = 12; + +function loadValueTreeSize(): { w: number; h: number } | null { + try { + const saved = JSON.parse(localStorage.getItem(VALUE_TREE_SIZE_KEY) ?? "null") as { + w?: unknown; + h?: unknown; + } | null; + return typeof saved?.w === "number" && + typeof saved?.h === "number" && + Number.isFinite(saved.w + saved.h) && + saved.w > 0 && + saved.h > 0 + ? { w: Math.max(VALUE_TREE_MIN_WIDTH, saved.w), h: Math.max(VALUE_TREE_MIN_HEIGHT, saved.h) } + : null; + } catch { + return null; + } +} + +function saveValueTreeSize(size: { w: number; h: number }) { + try { + localStorage.setItem(VALUE_TREE_SIZE_KEY, JSON.stringify(size)); + } catch { + // storage unavailable: the size lasts while the tree is open + } +} + +type ResizeDir = "n" | "s" | "w" | "e" | "nw" | "ne" | "sw" | "se"; + +const RESIZE_HANDLES: ReadonlyArray<{ + dir: ResizeDir; + className: string | undefined; + cursor: DragCursor; +}> = [ + { dir: "n", className: styles.valueResizeN, cursor: "ns-resize" }, + { dir: "s", className: styles.valueResizeS, cursor: "ns-resize" }, + { dir: "w", className: styles.valueResizeW, cursor: "ew-resize" }, + { dir: "e", className: styles.valueResizeE, cursor: "ew-resize" }, + { dir: "nw", className: styles.valueResizeNW, cursor: "nwse-resize" }, + { dir: "ne", className: styles.valueResizeNE, cursor: "nesw-resize" }, + { dir: "sw", className: styles.valueResizeSW, cursor: "nesw-resize" }, + { dir: "se", className: styles.valueResizeGrip, cursor: "nwse-resize" }, +]; const OPEN: Record = { ")": "(", "]": "[" }; const CLOSE: Record = { "(": ")", "[": "]" }; @@ -125,24 +181,202 @@ export function valueHint( session: DebugSessionId, max: number | null = 400, opts: { expanded?: boolean; pin?: () => void } = {}, -): { dom: HTMLElement; destroy: () => void } { +): { dom: HTMLElement; destroy: () => void; readonly resize?: boolean; positioned?: (space: Rect) => void } { const dom = document.createElement("div"); dom.className = `${styles.valueTooltip} ${selectableText}`; + const win = dom.ownerDocument.defaultView ?? window; const stopSizing = watchHintWidth(view, dom); let tree: { unmount(): void } | null = null; + let expanded = false; + let bounds: { left: number; top: number; width: number; height: number } | null = null; + let chrome = { width: 0, height: 0 }; + let disposed = false; + let stopDrag: (() => void) | undefined; + + const getSurface = () => dom.closest(".cm-tooltip") ?? dom; + const clamp = (n: number, min: number, maxN: number) => Math.max(min, Math.min(n, maxN)); + const limits = () => ({ + width: Math.max(1, win.innerWidth - VIEWPORT_MARGIN * 2), + height: Math.max(1, win.innerHeight - VIEWPORT_MARGIN * 2), + }); + const applySurfacePosition = (surface: HTMLElement, next: { left: number; top: number }) => { + const style = win.getComputedStyle(surface); + let left = next.left; + let top = next.top; + if (style.position === "absolute" && surface.offsetParent) { + const parentRect = surface.offsetParent.getBoundingClientRect(); + left -= parentRect.left; + top -= parentRect.top; + } + surface.style.left = `${left}px`; + surface.style.top = `${top}px`; + surface.style.right = ""; + }; + const applyBounds = (next: { left: number; top: number; width: number; height: number }) => { + if (disposed) return; + const { width: maxWidth, height: maxHeight } = limits(); + const width = clamp(next.width, Math.min(VALUE_TREE_MIN_WIDTH, maxWidth), maxWidth); + const height = clamp(next.height, Math.min(VALUE_TREE_MIN_HEIGHT, maxHeight), maxHeight); + bounds = { + left: clamp(next.left, VIEWPORT_MARGIN, win.innerWidth - VIEWPORT_MARGIN - width), + top: clamp(next.top, VIEWPORT_MARGIN, win.innerHeight - VIEWPORT_MARGIN - height), + width, + height, + }; + dom.dataset.resized = ""; + dom.style.width = `${Math.max(1, width - chrome.width)}px`; + dom.style.height = `${Math.max(1, height - chrome.height)}px`; + applySurfacePosition(getSurface(), bounds); + repositionTooltips(view); + }; + const positioned = () => { + if (!expanded || disposed) return; + const surface = getSurface(); + if (bounds) { + applySurfacePosition(surface, bounds); + } else if (dom.dataset.resized !== undefined) { + const rect = surface.getBoundingClientRect(); + const nextLeft = + rect.width > 0 + ? clamp(rect.left, VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, win.innerWidth - VIEWPORT_MARGIN - rect.width)) + : rect.left; + const nextTop = + rect.height > 0 + ? clamp(rect.top, VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, win.innerHeight - VIEWPORT_MARGIN - rect.height)) + : rect.top; + if (nextLeft !== rect.left || nextTop !== rect.top) { + applySurfacePosition(surface, { left: nextLeft, top: nextTop }); + } + } + }; + const fitViewport = () => { + if (!expanded || disposed) return; + stopDrag?.(); + if (bounds) { + applyBounds(bounds); + return; + } + if (dom.dataset.resized !== undefined) { + const { width: maxWidth, height: maxHeight } = limits(); + const w = parseFloat(dom.style.width); + const h = parseFloat(dom.style.height); + if (Number.isFinite(w) && w > maxWidth) dom.style.width = `${maxWidth}px`; + if (Number.isFinite(h) && h > maxHeight) dom.style.height = `${maxHeight}px`; + repositionTooltips(view); + } + }; + win.addEventListener("resize", fitViewport); + const destroy = () => { + disposed = true; + stopDrag?.(); + win.removeEventListener("resize", fitViewport); stopSizing(); tree?.unmount(); }; - const expandTree = () => { + const expandTree = (reposition = true) => { + expanded = true; dom.classList.remove(styles.valueTooltip!); dom.classList.replace(selectableText, styles.valueTooltipTree!); dom.replaceChildren(); - tree = mountValueTree(dom, expression, value, session); + + const body = document.createElement("div"); + body.className = styles.valueTooltipTreeBody!; + dom.append(body); + tree = mountValueTree(body, expression, value, session); + + const saved = loadValueTreeSize(); + if (saved) { + const { width: maxWidth, height: maxHeight } = limits(); + dom.dataset.resized = ""; + dom.style.width = `${Math.min(saved.w, maxWidth)}px`; + dom.style.height = `${Math.min(saved.h, maxHeight)}px`; + } + + for (const { dir, className, cursor } of RESIZE_HANDLES) { + const handle = document.createElement("div"); + handle.dataset.resize = dir; + if (dir === "se") { + handle.className = styles.valueResizeGrip!; + handle.setAttribute("role", "separator"); + handle.setAttribute("aria-orientation", "vertical"); + handle.setAttribute("aria-label", tx("Resize")); + } else { + handle.className = `${styles.valueResizeEdge!} ${className ?? ""}`.trim(); + handle.setAttribute("aria-hidden", "true"); + } + handle.addEventListener("pointerdown", (e) => { + if (disposed || e.button !== 0 || e.isPrimary === false) return; + e.preventDefault(); + e.stopPropagation(); + stopDrag?.(); + const surface = getSurface(); + const start = surface.getBoundingClientRect(); + const card = dom.getBoundingClientRect(); + chrome = { + width: Math.max(0, start.width - card.width), + height: Math.max(0, start.height - card.height), + }; + const releaseCursor = lockDragCursor(cursor); + const startX = e.clientX; + const startY = e.clientY; + const initRight = start.left + start.width; + const initBottom = start.top + start.height; + let didResize = false; + const move = (ev: PointerEvent) => { + if (ev.pointerId !== e.pointerId) return; + if (!(ev.buttons & 1)) return finish(); + const dx = ev.clientX - startX; + const dy = ev.clientY - startY; + const { width: maxWidth, height: maxHeight } = limits(); + const minWidth = Math.min(VALUE_TREE_MIN_WIDTH, maxWidth); + const minHeight = Math.min(VALUE_TREE_MIN_HEIGHT, maxHeight); + let left = start.left; + let top = start.top; + let right = initRight; + let bottom = initBottom; + if (dir.includes("w")) left = clamp(start.left + dx, VIEWPORT_MARGIN, initRight - minWidth); + if (dir.includes("n")) top = clamp(start.top + dy, VIEWPORT_MARGIN, initBottom - minHeight); + if (dir.includes("e")) right = clamp(initRight + dx, left + minWidth, win.innerWidth - VIEWPORT_MARGIN); + if (dir.includes("s")) bottom = clamp(initBottom + dy, top + minHeight, win.innerHeight - VIEWPORT_MARGIN); + didResize = true; + applyBounds({ left, top, width: right - left, height: bottom - top }); + }; + const end = (ev: PointerEvent) => { + if (ev.pointerId === e.pointerId) finish(); + }; + const finish = () => { + win.removeEventListener("pointermove", move); + win.removeEventListener("pointerup", end); + win.removeEventListener("pointercancel", end); + win.removeEventListener("blur", finish); + releaseCursor(); + stopDrag = undefined; + if (didResize && bounds) { + saveValueTreeSize({ w: Math.round(bounds.width), h: Math.round(bounds.height) }); + } + }; + stopDrag = finish; + win.addEventListener("pointermove", move); + win.addEventListener("pointerup", end); + win.addEventListener("pointercancel", end); + win.addEventListener("blur", finish); + }); + dom.append(handle); + } + + if (reposition) repositionTooltips(view); }; if (value.variablesReference > 0 && opts.expanded) { - expandTree(); - return { dom, destroy }; + expandTree(false); + return { + dom, + destroy, + get resize() { + return expanded ? false : undefined; + }, + positioned, + }; } if (value.variablesReference > 0) { // IDEA's value hint: the "+" expands the object into a variables tree in place. @@ -180,7 +414,14 @@ export function valueHint( summary.append(max === null ? shown.text : inlineValue(shown.text, max)); if (shown.label && !leading) summary.append(type(` ${shown.label}`)); dom.append(iconNode("variable", 16, styles.valueGlyph), summary); - return { dom, destroy }; + return { + dom, + destroy, + get resize() { + return expanded ? false : undefined; + }, + positioned, + }; } function watchHintWidth(view: EditorView, dom: HTMLElement): () => void { @@ -276,6 +517,10 @@ function pinnedTree(view: EditorView, expression: string, value: Variable, sessi unsubscribe(); hint.destroy(); }, + get resize() { + return hint.resize; + }, + positioned: hint.positioned, }; }