дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Expanding an object in the debugger's editor value tooltip fixed the tree at 460x260 px inside the hint's 480 px cap, truncating nested fields and package paths. The expanded tree now resizes from all eight edges and corners up to the viewport (minimum 280x120 px) and remembers its size (openidea.debugger.valueTreeSize.v1). hint.ts forwards resize/positioned from built hint content to CodeMirror's TooltipView so the tooltip keeps the dragged size and position. Covered by valueHint.test.ts. Co-authored-by: elfadl <[email protected]>
585 рядки
22 KiB
TypeScript
585 рядки
22 KiB
TypeScript
/**
|
||
* Settings › Debugger › Data Views › "Show value tooltip on mouse hover":
|
||
* while suspended, hovering an expression (or the selection under the mouse)
|
||
* evaluates it in the selected frame.
|
||
*/
|
||
import { syntaxTree } from "@codemirror/language";
|
||
import type { EditorState, Extension } from "@codemirror/state";
|
||
import type { DebugSessionId, Variable } from "@/bindings";
|
||
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";
|
||
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<string, string> = { ")": "(", "]": "[" };
|
||
const CLOSE: Record<string, string> = { "(": ")", "[": "]" };
|
||
|
||
/** Index just past the bracket group opening at `i` (strings skipped), or -1 when it doesn't close on the line. */
|
||
function closeOf(t: string, i: number): number {
|
||
const stack: string[] = [];
|
||
for (let j = i; j < t.length; j++) {
|
||
const c = t[j]!;
|
||
if (c === '"' || c === "'" || c === "`") {
|
||
j++;
|
||
while (j < t.length && t[j] !== c) j += t[j] === "\\" ? 2 : 1;
|
||
if (j >= t.length) return -1;
|
||
} else if (CLOSE[c]) stack.push(CLOSE[c]);
|
||
else if (c === ")" || c === "]") {
|
||
if (stack.pop() !== c) return -1;
|
||
if (!stack.length) return j + 1;
|
||
}
|
||
}
|
||
return -1;
|
||
}
|
||
|
||
/** Index of the bracket opening the group that closes at `i - 1`, or -1. */
|
||
function openOf(t: string, i: number): number {
|
||
for (let start = i - 1; start >= 0; start--) {
|
||
if (t[start] === OPEN[t[i - 1]!] && closeOf(t, start) === i) return start;
|
||
}
|
||
return -1;
|
||
}
|
||
|
||
/** Syntax nodes of an operator's expression (Lezer's Java, JS, Python, C++, Rust, Go grammars). */
|
||
const OPERATOR_EXPRESSION = /^(Binary|Unary|Ternary|Conditional)Expr(ession)?$/;
|
||
/** A call, an increment or an assignment: a plain hover doesn't evaluate those. */
|
||
const SIDE_EFFECTS = /[\p{L}\p{N}_$)\]]\s*\(|\+\+|--|(^|[^=!<>])=(?!=)/u;
|
||
|
||
/**
|
||
* As in IDEA, on an operator the expression it belongs to: `&&` gives `a > 1 && !flag`, `>` gives
|
||
* `a > 1`, `!` gives `!flag`. Without `calls` (a hover), not when evaluating it could change state.
|
||
*/
|
||
function operatorExpressionAt(state: EditorState, pos: number, calls: boolean) {
|
||
const token = syntaxTree(state).resolveInner(pos, 1);
|
||
const parent = token.parent;
|
||
if (token.firstChild || !parent || !OPERATOR_EXPRESSION.test(parent.name)) return null;
|
||
const text = state.sliceDoc(parent.from, parent.to);
|
||
if (text.includes("\n") || (!calls && SIDE_EFFECTS.test(text))) return null;
|
||
return { from: parent.from, to: parent.to, text };
|
||
}
|
||
|
||
/**
|
||
* Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. With
|
||
* `calls`, as for Quick Evaluate: member chains through calls and indexing (`a.getB().c`,
|
||
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`). On an operator,
|
||
* the expression it belongs to.
|
||
*/
|
||
export function expressionAt(
|
||
view: EditorView,
|
||
pos: number,
|
||
{ calls = false } = {},
|
||
): { from: number; to: number; text: string } | null {
|
||
const { state } = view;
|
||
const sel = state.selection.main;
|
||
if (!sel.empty && pos >= sel.from && pos <= sel.to) {
|
||
const text = state.sliceDoc(sel.from, sel.to).trim();
|
||
return text && !text.includes("\n") ? { from: sel.from, to: sel.to, text } : null;
|
||
}
|
||
const line = state.doc.lineAt(pos);
|
||
const t = line.text;
|
||
let start = pos - line.from;
|
||
let end = start;
|
||
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) {
|
||
return /\s/.test(t[end] ?? " ") ? null : operatorExpressionAt(state, pos, calls);
|
||
}
|
||
while (end < t.length && IDENT.test(t[end]!)) end++;
|
||
for (;;) {
|
||
while (start > 0 && IDENT.test(t[start - 1]!)) start--;
|
||
if (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")) start--;
|
||
else if (calls && t[start - 1] === "." && OPEN[t[start - 2] ?? ""]) {
|
||
let open = openOf(t, start - 1);
|
||
// `a.b()[0].c`: walk back over every group, then the name they follow.
|
||
while (open > 0 && OPEN[t[open - 1]!]) open = openOf(t, open);
|
||
if (open <= 0 || !IDENT.test(t[open - 1]!)) break;
|
||
start = open;
|
||
} else break;
|
||
}
|
||
if (calls) {
|
||
let next = end;
|
||
while (t[next] === " ") next++;
|
||
if (t[next] === "(") {
|
||
const close = closeOf(t, next);
|
||
if (close > 0) end = close;
|
||
}
|
||
}
|
||
const text = t.slice(start, end);
|
||
if (!text || /^\d/.test(text)) return null;
|
||
return { from: line.from + start, to: line.from + end, text };
|
||
}
|
||
|
||
/** IDEA's value hint: `expression = value {type}`, objects expandable into a variables tree in place. */
|
||
export function valueHint(
|
||
view: EditorView,
|
||
expression: string,
|
||
value: Variable,
|
||
session: DebugSessionId,
|
||
max: number | null = 400,
|
||
opts: { expanded?: boolean; pin?: () => 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<HTMLElement>(".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 = (reposition = true) => {
|
||
expanded = true;
|
||
dom.classList.remove(styles.valueTooltip!);
|
||
dom.classList.replace(selectableText, styles.valueTooltipTree!);
|
||
dom.replaceChildren();
|
||
|
||
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(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.
|
||
const expand = document.createElement("button");
|
||
expand.type = "button";
|
||
expand.className = styles.valueExpand!;
|
||
expand.setAttribute("aria-label", tx("Expand value"));
|
||
expand.setAttribute("aria-expanded", "false");
|
||
expand.innerHTML = iconMarkup("chevron-right", 12) ?? "";
|
||
expand.addEventListener("mousedown", (e) => e.preventDefault());
|
||
expand.addEventListener("click", () => {
|
||
if (tree) return;
|
||
if (opts.pin) return opts.pin();
|
||
expand.remove();
|
||
expandTree();
|
||
});
|
||
dom.append(expand);
|
||
}
|
||
const summary = document.createElement("span");
|
||
summary.className = styles.valueText!;
|
||
const name = document.createElement("span");
|
||
name.className = styles.valueName!;
|
||
name.textContent = `${expression} = `;
|
||
const shown = shownValue(value.value, value.typeName);
|
||
// A JVM object's `{Type@id}` leads its value; other types follow it.
|
||
const leading = shown.label?.includes("@") ?? false;
|
||
const type = (text: string) => {
|
||
const span = document.createElement("span");
|
||
span.className = styles.valueType!;
|
||
span.textContent = text;
|
||
return span;
|
||
};
|
||
summary.append(name);
|
||
if (leading) summary.append(type(`${shown.label} `));
|
||
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,
|
||
get resize() {
|
||
return expanded ? false : undefined;
|
||
},
|
||
positioned,
|
||
};
|
||
}
|
||
|
||
function watchHintWidth(view: EditorView, dom: HTMLElement): () => void {
|
||
let width = 0;
|
||
let resizeFrame = 0;
|
||
const updateWidth = () => {
|
||
const next = view.dom.clientWidth;
|
||
if (!next || next === width) return;
|
||
width = next;
|
||
dom.style.setProperty("--debug-value-editor-width", `${width}px`);
|
||
};
|
||
updateWidth();
|
||
const resize = new ResizeObserver(() => {
|
||
cancelAnimationFrame(resizeFrame);
|
||
resizeFrame = requestAnimationFrame(updateWidth);
|
||
});
|
||
resize.observe(view.dom);
|
||
return () => {
|
||
resize.disconnect();
|
||
cancelAnimationFrame(resizeFrame);
|
||
};
|
||
}
|
||
|
||
export function showQuickValue(
|
||
view: EditorView,
|
||
pos: number,
|
||
expression: string,
|
||
value: Variable,
|
||
session: DebugSessionId,
|
||
) {
|
||
if (value.variablesReference > 0) showValueTree(view, pos, expression, value, session);
|
||
else showHint(view, () => valueHint(view, expression, value, session), { pos, timeout: 60_000 });
|
||
}
|
||
|
||
export function valueTooltip(): Extension {
|
||
return hoverTooltip(
|
||
async (view, pos) => {
|
||
const dbg = workflowSettings().debugger;
|
||
// ⌘/Ctrl-hover shows the navigation info instead (closed on press by the LSP hover).
|
||
if (!dbg.valueTooltip || navigationModifierHeld()) return null;
|
||
const session = activeSession();
|
||
if (!session || session.status !== "paused") return null;
|
||
const expr = expressionAt(view, pos);
|
||
if (!expr) return null;
|
||
if (dbg.valueTooltipDelay > BASE_HOVER)
|
||
await new Promise((r) => setTimeout(r, dbg.valueTooltipDelay - BASE_HOVER));
|
||
let value;
|
||
try {
|
||
value = await evaluate(expr.text, "hover", session);
|
||
} catch {
|
||
return null;
|
||
}
|
||
if (navigationModifierHeld()) return null;
|
||
return {
|
||
pos: expr.from,
|
||
end: expr.to,
|
||
above: true,
|
||
create: (view) =>
|
||
valueHint(view, expr.text, value, session.id, 400, {
|
||
// The tree outgrows the hint and may move to the other side of the line, away from the
|
||
// mouse, which closed the hover tooltip before it could be reached. Like IDEA's value
|
||
// popup it stays until Escape, a click in the editor or the next step.
|
||
pin: () => showValueTree(view, expr.from, expr.text, value, session.id),
|
||
}),
|
||
};
|
||
},
|
||
{ hoverTime: BASE_HOVER },
|
||
);
|
||
}
|
||
|
||
function showValueTree(view: EditorView, pos: number, expression: string, value: Variable, session: DebugSessionId) {
|
||
view.dispatch({ effects: closeHoverTooltips });
|
||
showHint(view, () => pinnedTree(view, expression, value, session), { pos, timeout: null });
|
||
}
|
||
|
||
/** An expanded value tree, closed when its session leaves the stop it was evaluated in. */
|
||
function pinnedTree(view: EditorView, expression: string, value: Variable, session: DebugSessionId) {
|
||
const stop = useDebug.getState().stopSeq;
|
||
const unsubscribe = useDebug.subscribe((s) => {
|
||
if (s.stopSeq !== stop || s.sessions[session]?.status !== "paused") hideHint(view);
|
||
});
|
||
const hint = valueHint(view, expression, value, session, 400, { expanded: true });
|
||
// The tree has the focus, so the editor's Escape doesn't reach the hint.
|
||
hint.dom.addEventListener("keydown", (e) => {
|
||
if (e.key !== "Escape" || e.defaultPrevented) return;
|
||
e.preventDefault();
|
||
hideHint(view);
|
||
view.focus();
|
||
});
|
||
return {
|
||
dom: hint.dom,
|
||
destroy: () => {
|
||
unsubscribe();
|
||
hint.destroy();
|
||
},
|
||
get resize() {
|
||
return hint.resize;
|
||
},
|
||
positioned: hint.positioned,
|
||
};
|
||
}
|
||
|
||
const SELECTION_DELAY = 400;
|
||
const MAX_SELECTION = 200;
|
||
|
||
/** The selected text when it can be evaluated: one non-blank line, not too long. */
|
||
export function selectionExpression(state: EditorState): { from: number; text: string } | null {
|
||
const sel = state.selection;
|
||
if (sel.ranges.length !== 1 || sel.main.empty) return null;
|
||
const text = state.sliceDoc(sel.main.from, sel.main.to).trim();
|
||
if (!text || text.length > MAX_SELECTION || text.includes("\n")) return null;
|
||
return { from: sel.main.from, text };
|
||
}
|
||
|
||
/**
|
||
* Settings › Debugger › Data Views › "Show value tooltip on code selection": while
|
||
* suspended, selecting an expression shows its value once the selection settles.
|
||
*/
|
||
export function selectionValueTooltip(): Extension {
|
||
return ViewPlugin.fromClass(
|
||
class {
|
||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||
private seq = 0;
|
||
constructor(readonly view: EditorView) {}
|
||
|
||
update(u: ViewUpdate) {
|
||
if (!u.selectionSet) return;
|
||
clearTimeout(this.timer);
|
||
this.seq++;
|
||
if (!u.transactions.some((tr) => tr.isUserEvent("select"))) return;
|
||
const seq = this.seq;
|
||
this.timer = setTimeout(() => void this.show(seq), SELECTION_DELAY);
|
||
}
|
||
|
||
private async show(seq: number) {
|
||
if (!workflowSettings().debugger.valueTooltipOnSelection) return;
|
||
const session = activeSession();
|
||
if (!session || session.status !== "paused") return;
|
||
const expr = selectionExpression(this.view.state);
|
||
if (!expr) return;
|
||
let value;
|
||
try {
|
||
value = await evaluate(expr.text, "hover", session);
|
||
} catch {
|
||
return;
|
||
}
|
||
// The selection moved on while evaluating.
|
||
if (seq !== this.seq) return;
|
||
showHint(this.view, () => valueHint(this.view, expr.text, value, session.id), {
|
||
pos: expr.from,
|
||
timeout: 60_000,
|
||
});
|
||
}
|
||
|
||
destroy() {
|
||
clearTimeout(this.timer);
|
||
}
|
||
},
|
||
);
|
||
}
|