268 lines
14 KiB
JavaScript
268 lines
14 KiB
JavaScript
// The debugger's hover inspector: while the program is stopped, hovering an expression in a PHP editor (or Alt+F8 at the caret, or the
|
|
// selected text) opens a card with its value: the full structure expandable lazily (the tree of the Debug window, var-tree.js),
|
|
// Copy (value / JSON / PHP), the pencil to change a scalar in the running program, Add to Watches, Evaluate expression…
|
|
// The expression under the mouse is the whole `$user->name` / `$a['x']` (expr-at.js), read with property_get (no code runs) or, for
|
|
// anything else, evaluated. The card stays while the mouse is over it, closes on Escape, on leaving (a short delay), on scrolling and when the
|
|
// program resumes; it is placed inside the editor it comes from (flips above / below, its body scrolls), never over the bottom panel.
|
|
import { monaco } from './editor.js';
|
|
import { backend } from './backend.js';
|
|
import { el, icon, menu, t, notify } from './ui.js';
|
|
import { expressionAt, isPlainChain } from './expr-at.js';
|
|
import { isScalar, isEditable, plainText } from './var-model.js';
|
|
import { LeaveGuard, scrollMoved, pickSide } from './hover-model.js';
|
|
|
|
const DELAY = 300; // ms the mouse rests on an expression before its card opens
|
|
const MAX_BODY = 360; // px, the body scrolls beyond
|
|
const MAX_WIDTH = 560;
|
|
|
|
export class HoverInspector {
|
|
constructor(panel) {
|
|
this.panel = panel;
|
|
this.editors = new Set();
|
|
this.card = null;
|
|
this.seq = 0;
|
|
this.timer = null;
|
|
this.guard = new LeaveGuard(() => this.close());
|
|
this.guard.typing = () => { const a = document.activeElement; return !!this.card && this.card.contains(a) && /^(INPUT|TEXTAREA)$/.test(a.tagName); };
|
|
this.side = null;
|
|
this.decorations = null;
|
|
this.last = null; // {editor, hit, at, explicit}
|
|
}
|
|
|
|
/** Mouse, scroll and keyboard of an editor. */
|
|
attach(editor) {
|
|
if (editor.__inspector) return;
|
|
editor.__inspector = true;
|
|
this.editors.add(editor);
|
|
editor.onMouseMove((e) => this.onMove(editor, e));
|
|
editor.onMouseLeave(() => this.leaveSoon());
|
|
editor.onDidScrollChange((e) => { if (scrollMoved(e)) this.close(); });
|
|
editor.onDidChangeModel(() => this.close());
|
|
editor.onDidChangeModelContent(() => this.close());
|
|
editor.onKeyDown((e) => { if (e.keyCode === monaco.KeyCode.Escape && this.card) this.close(); });
|
|
editor.addAction({
|
|
id: 'jumphp.debug.inspect', label: t('Inspect Value at Caret'), keybindings: [monaco.KeyMod.Alt | monaco.KeyCode.F8],
|
|
run: () => this.atCaret(editor),
|
|
});
|
|
if (this.panel.paused) editor.updateOptions({ hover: { enabled: false } });
|
|
}
|
|
|
|
/** The program stopped / resumed: Monaco's own hover would cover the card while stopped. */
|
|
stopped(on) {
|
|
this.close();
|
|
for (const editor of this.editors) editor.updateOptions({ hover: { enabled: !on } });
|
|
}
|
|
|
|
// finding what is under the mouse --------------------------------------------------------------------------------------
|
|
|
|
/** The expression at a position: the selected text when the mouse is inside the selection, else the chain under the mouse. */
|
|
hitAt(editor, position, column) {
|
|
const model = editor.getModel();
|
|
if (!model) return null;
|
|
const sel = editor.getSelection();
|
|
if (sel && !sel.isEmpty() && sel.startLineNumber === sel.endLineNumber && sel.containsPosition(position)) {
|
|
const text = model.getValueInRange(sel).trim();
|
|
if (text && text.length <= 200) return { expression: text, range: sel };
|
|
}
|
|
const found = expressionAt(model.getLineContent(position.lineNumber), column - 1);
|
|
return found ? { expression: found.expression, range: new monaco.Range(position.lineNumber, found.start + 1, position.lineNumber, found.end + 1) } : null;
|
|
}
|
|
|
|
onMove(editor, e) {
|
|
if (!this.panel.paused || !this.panel.debuggable(editor.getModel() || { getLanguageId: () => '' })) return;
|
|
if (e.target.type !== monaco.editor.MouseTargetType.CONTENT_TEXT || !e.target.position) { clearTimeout(this.timer); this.leaveSoon(); return; }
|
|
const hit = this.hitAt(editor, e.target.position, e.target.range?.startColumn ?? e.target.position.column);
|
|
if (!hit) { clearTimeout(this.timer); this.leaveSoon(); return; }
|
|
const same = this.last && this.last.editor === editor && this.last.hit.expression === hit.expression && this.last.hit.range.equalsRange(hit.range);
|
|
if (same && this.card) { this.cancelLeave(); return; }
|
|
clearTimeout(this.timer);
|
|
this.cancelLeave();
|
|
this.timer = setTimeout(() => this.show(editor, hit), DELAY);
|
|
}
|
|
|
|
/** Alt+F8: the card for the selection, else the expression at the caret (it takes the focus: the keyboard way in). */
|
|
atCaret(editor) {
|
|
if (!this.panel.paused) { notify(t('The program is not stopped: run it with Debug and wait for a breakpoint.'), 'info', { title: t('Inspect Value at Caret') }); return; }
|
|
const pos = editor.getPosition();
|
|
const sel = editor.getSelection();
|
|
let hit = null;
|
|
if (sel && !sel.isEmpty() && sel.startLineNumber === sel.endLineNumber) hit = this.hitAt(editor, sel.getStartPosition(), sel.startColumn);
|
|
hit ||= pos && this.hitAt(editor, pos, pos.column) || pos && this.hitAt(editor, pos, Math.max(1, pos.column - 1));
|
|
if (hit) this.show(editor, hit, { explicit: true, focus: true });
|
|
}
|
|
|
|
// reading ---------------------------------------------------------------------------------------------------------------
|
|
|
|
/** A variable chain is read with property_get (nothing runs); anything else, or a chain that cannot be read, is evaluated. */
|
|
async read(expression) {
|
|
const session = this.panel.paused?.session;
|
|
if (!session) throw new Error('no program');
|
|
if (isPlainChain(expression)) {
|
|
try {
|
|
const r = await backend.invoke('debug.children', { session, fullname: expression, depth: this.panel.frame, page: 0 });
|
|
if (r && r.type) return { ...r, fullname: expression, expression, name: expression };
|
|
} catch { /* a name the frame does not know: evaluated below */ }
|
|
}
|
|
const r = await backend.invoke('debug.eval', { session, expression });
|
|
if (!r || !r.type) throw new Error(t('{expression} cannot be read here', { expression }));
|
|
return { ...r, fullname: isPlainChain(expression) ? expression : '', expression, name: expression };
|
|
}
|
|
|
|
// the card --------------------------------------------------------------------------------------------------------------
|
|
|
|
async show(editor, hit, { explicit = false, focus = false } = {}) {
|
|
if (!this.panel.paused) return;
|
|
const token = ++this.seq;
|
|
let v = null;
|
|
let error = null;
|
|
try { v = await this.read(hit.expression); } catch (e) { error = e; }
|
|
if (token !== this.seq || !this.panel.paused) return;
|
|
if (!v && !explicit) { this.close(); return; }
|
|
this.close(false);
|
|
this.last = { editor, hit, explicit };
|
|
const vis = editor.getScrolledVisiblePosition(hit.range.getStartPosition());
|
|
const host = editor.getDomNode().getBoundingClientRect();
|
|
this.anchor = vis ? { left: host.left + vis.left, top: host.top + vis.top, height: vis.height, host } : { left: host.left + 20, top: host.top + 20, height: 18, host };
|
|
this.decorations = editor.createDecorationsCollection([{ range: hit.range, options: { inlineClassName: 'dbg-hover-expr' } }]);
|
|
this.build(v, error, hit.expression);
|
|
if (focus) this.card.querySelector('.row')?.focus() ?? this.card.focus();
|
|
}
|
|
|
|
summary(v) {
|
|
const parts = [];
|
|
if (v.facet) parts.push(v.facet);
|
|
parts.push(v.class || v.type || '');
|
|
if (v.type === 'string' && v.length) parts.push(`(${v.length})`);
|
|
else if (v.size && v.type !== 'array') parts.push(`· ${v.size}`);
|
|
return parts.filter(Boolean).join(' ');
|
|
}
|
|
|
|
build(v, error, expression) {
|
|
const body = el('div.dbg-hover-body');
|
|
const title = el('span.dbg-hover-expr', { title: expression }, expression);
|
|
const type = el('span.dbg-hover-type');
|
|
const head = el('div.dbg-hover-head', {}, title, type, el('span.tw-spacer'));
|
|
const card = el('div.dbg-hover', { role: 'dialog', 'aria-label': t('Variable inspector'), tabIndex: -1 }, head, body);
|
|
this.card = card;
|
|
this.body = body;
|
|
this.fill(v, error, expression, { head, title, type, body });
|
|
card.addEventListener('mouseenter', () => this.guard.enter());
|
|
card.addEventListener('mouseleave', () => this.guard.leave());
|
|
card.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); const editor = this.last?.editor; this.close(); editor?.focus(); } });
|
|
document.addEventListener('keydown', this.onKey ||= (e) => { if (e.key === 'Escape' && this.card) this.close(); });
|
|
document.addEventListener('mousedown', this.onDown ||= (e) => { if (this.card && !this.card.contains(e.target) && !e.target.closest?.('.menu, .context-menu, [role=menu]')) this.close(); }, true);
|
|
document.body.append(card);
|
|
this.place();
|
|
this.observer = new ResizeObserver(() => this.place());
|
|
this.observer.observe(body);
|
|
}
|
|
|
|
/** The header buttons and the tree of a value (again after an edit or an evaluation). */
|
|
fill(v, error, expression, { head, title, type, body }) {
|
|
for (const old of head.querySelectorAll('button')) old.remove();
|
|
this.value = v;
|
|
title.textContent = expression;
|
|
title.title = expression;
|
|
type.textContent = v ? this.summary(v) : '';
|
|
body.replaceChildren();
|
|
const button = (label, ico, onclick) => el('button.icon-btn', { title: t(label), 'aria-label': t(label), onclick }, icon(ico));
|
|
if (v) {
|
|
head.append(button('Copy value', 'copy', (e) => this.panel.tree.copyMenu(v, e.currentTarget)));
|
|
if (isEditable(v) && this.panel.paused) head.append(button('Edit value', 'edit', () => body.querySelector('.row')?.parentElement?.edit?.()));
|
|
head.append(button('Add to Watches', 'eye', () => { this.panel.addWatch(expression); notify(t('Added to Watches'), 'info', { timeout: 1500 }); }));
|
|
}
|
|
head.append(button('Evaluate expression…', 'play', () => this.evaluate(expression, { head, title, type, body })));
|
|
head.append(button('Close', 'close', () => { const editor = this.last?.editor; this.close(); editor?.focus(); }));
|
|
if (!v) {
|
|
body.append(el('div.dbg-hover-error', {}, error?.message || t('{expression} cannot be read here', { expression })));
|
|
return;
|
|
}
|
|
// the tree: the first level open for a structure; a long or multi-line string also whole, below
|
|
const tree = this.panel.tree.row({ ...v, name: v.name || expression }, 0, { root: true, open: !!v.children });
|
|
body.append(tree);
|
|
if (v.type === 'string' && (v.length > 60 || /\n/.test(plainText(v)))) body.append(el('pre.dbg-hover-full', {}, plainText(v)));
|
|
}
|
|
|
|
/** Evaluate expression…: a field with the expression (editable, any PHP), Enter shows its value in the card. */
|
|
evaluate(expression, parts) {
|
|
this.card.querySelector('.dbg-hover-eval')?.remove();
|
|
const input = el('input.dbg-hover-eval', { value: expression, spellcheck: false, placeholder: t('A PHP expression, evaluated where the program is stopped'), 'aria-label': t('Evaluate expression…') });
|
|
parts.head.after(input);
|
|
input.focus();
|
|
input.select();
|
|
input.addEventListener('keydown', async (e) => {
|
|
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); input.remove(); this.card?.focus(); return; }
|
|
if (e.key !== 'Enter' || !input.value.trim()) return;
|
|
e.preventDefault();
|
|
const text = input.value.trim();
|
|
let v = null;
|
|
let error = null;
|
|
try { v = await this.read(text); } catch (err) { error = err; }
|
|
if (!this.card || !this.panel.paused) return;
|
|
if (this.last) this.last.hit = { ...this.last.hit, expression: text };
|
|
this.fill(v, error, text, parts);
|
|
this.place();
|
|
});
|
|
this.place();
|
|
}
|
|
|
|
/** The value again after it was changed (the pencil, a Set Value…): the same expression, the same place. */
|
|
async refresh() {
|
|
if (!this.card || !this.last || !this.panel.paused) return;
|
|
const expression = this.last.hit.expression;
|
|
let v = null;
|
|
let error = null;
|
|
try { v = await this.read(expression); } catch (e) { error = e; }
|
|
if (!this.card) return;
|
|
this.fill(v, error, expression, { head: this.card.querySelector('.dbg-hover-head'), title: this.card.querySelector('.dbg-hover-expr'), type: this.card.querySelector('.dbg-hover-type'), body: this.body });
|
|
this.place();
|
|
}
|
|
|
|
/** Inside the editor it comes from: below the text when it fits, else above, else the larger side with a scrolling body. */
|
|
place() {
|
|
const card = this.card;
|
|
const a = this.anchor;
|
|
if (!card || !a) return;
|
|
const gap = 4;
|
|
const head = card.querySelector('.dbg-hover-head')?.offsetHeight || 30;
|
|
const extra = (card.querySelector('.dbg-hover-eval')?.offsetHeight || 0) + 4;
|
|
const host = a.host;
|
|
const width = Math.min(MAX_WIDTH, Math.max(240, host.width - 16), window.innerWidth - 16);
|
|
card.style.maxWidth = `${width}px`;
|
|
const wantBody = Math.min(MAX_BODY, this.body.scrollHeight);
|
|
const need = head + extra + wantBody + 2;
|
|
const below = host.bottom - (a.top + a.height) - gap;
|
|
const above = a.top - host.top - gap;
|
|
const side = this.side = pickSide(this.side, need, below, above);
|
|
const room = Math.max(side === 'below' ? below : above, head + extra + 70);
|
|
this.body.style.maxHeight = `${Math.max(60, Math.min(MAX_BODY, room - head - extra - 2))}px`;
|
|
const height = card.offsetHeight;
|
|
const top = side === 'below' ? a.top + a.height + gap : a.top - gap - height;
|
|
const left = Math.max(host.left + 4, Math.min(a.left, Math.min(host.right, window.innerWidth) - card.offsetWidth - 4));
|
|
card.style.left = `${Math.round(left)}px`;
|
|
card.style.top = `${Math.round(Math.max(host.top, Math.min(top, host.bottom - height)))}px`;
|
|
}
|
|
|
|
// closing ---------------------------------------------------------------------------------------------------------------
|
|
|
|
cancelLeave() { this.guard.cancel(); }
|
|
|
|
leaveSoon() { if (this.card) this.guard.soon(); }
|
|
|
|
/** Closes the card (all = false: only to open another one, the pending one keeps its place in the queue). */
|
|
close(all = true) {
|
|
if (all) { this.seq++; clearTimeout(this.timer); }
|
|
this.guard.cancel();
|
|
this.guard.hovered = false;
|
|
this.guard.pending = 0;
|
|
this.side = null;
|
|
this.observer?.disconnect();
|
|
this.observer = null;
|
|
this.decorations?.clear();
|
|
this.decorations = null;
|
|
if (this.card) { this.card.remove(); this.card = null; this.body = null; }
|
|
if (all) this.last = null;
|
|
if (this.onKey) document.removeEventListener('keydown', this.onKey);
|
|
if (this.onDown) document.removeEventListener('mousedown', this.onDown, true);
|
|
}
|
|
}
|