rob-revisited/ide/ui/js/calls.js

138 lines
7.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Calls window: who calls a method or a function (the "↳ N calls" lens above each one in the editor, or the
// Navigate > Call Hierarchy action at the cursor). The callers come grouped by the method they are written in; a caller
// unfolds into its own callers, level by level, up the whole chain. Click a call: the file opens at that line.
// PHP: php.calls (ide/src/Php/Intelligence.php calls()).
import { backend } from './backend.js';
import { el, clear, icon, t } from './ui.js';
export class CallsPanel {
constructor(app) {
this.app = app;
this.node = el('div.calls-view');
this.root = null; // {target, kind, callers, count, place}
this.render();
}
title() { return t('Calls'); }
actions() {
return [el('button', { title: t('Refresh'), onclick: () => this.root && this.show(this.root.place) }, icon('refresh'))];
}
/** The calls of the method at a place ({path, line, column, text?}): the window shows them. */
async show(place) {
this.app.showTool('calls', true);
this.node.replaceChildren(el('p.pub-faint', {}, t('Looking for the calls…')));
try {
const r = await backend.invoke('php.calls', place);
this.root = { ...r, place };
} catch (e) {
this.root = { target: '', callers: [], count: 0, place, error: String(e.message || e) };
}
this.render();
}
render() {
clear(this.node);
const r = this.root;
if (!r) {
this.node.append(el('p.pub-faint', {}, t('Click "↳ calls" above a method in the editor (or Navigate > Call Hierarchy at the cursor) to see who calls it.')));
return;
}
if (r.error) { this.node.append(el('p.cryo-error', {}, r.error)); return; }
if (!r.target) { this.node.append(el('p.pub-faint', {}, t('Put the cursor on the name of a method or a function.'))); return; }
this.node.append(el('div.calls-head', {}, el('b', {}, r.target), ' ',
el('span.pub-faint', {}, r.count ? t('{n} call(s) in {m} place(s)', { n: r.count, m: r.callers.length }) : t('No call found in the project'))));
const list = el('div.calls-tree');
for (const c of r.callers) list.append(this.caller(c, 0));
this.node.append(list);
}
/** A caller: its name (unfolds into its own callers), then its call lines */
caller(c, depth) {
const box = el('div.calls-node', { style: { marginLeft: depth * 14 + 'px' } });
const children = el('div.calls-children', { hidden: true });
let loaded = false;
const toggle = el('button.calls-toggle', { title: t('Who calls it'), disabled: !c.line }, '▸');
toggle.onclick = async () => {
const open = children.hidden;
children.hidden = !open;
toggle.textContent = open ? '▾' : '▸';
if (open && !loaded) {
loaded = true;
children.replaceChildren(el('p.pub-faint', { style: { marginLeft: (depth + 1) * 14 + 'px' } }, t('Looking for the calls…')));
const up = await backend.invoke('php.calls', { path: c.path, line: c.line, column: c.col }).catch(() => ({ callers: [] }));
children.replaceChildren(...(up.callers.length ? up.callers.map((u) => this.caller(u, depth + 1))
: [el('p.pub-faint', { style: { marginLeft: (depth + 1) * 14 + 'px' } }, t('No caller: the chain starts here'))]));
}
};
const name = el('a.calls-caller', { href: '#', onclick: (e) => { e.preventDefault(); if (c.line) this.open(c.path, c.line); } }, c.caller);
box.append(el('div.calls-row', {}, toggle, name, el('span.pub-faint', {}, ` ${c.path} · ${c.calls.length}×`)));
for (const call of c.calls) {
box.append(el('a.calls-line', { href: '#', style: { marginLeft: '22px' }, title: call.certain ? '' : t('Maybe (its object\'s class is not known for sure)'),
onclick: (e) => { e.preventDefault(); this.open(c.path, call.line, call.col); } },
el('span.calls-ln', {}, String(call.line)), el('code', {}, call.text), call.certain ? null : el('span.pub-faint', {}, ' ?')));
}
box.append(children);
return box;
}
open(path, line, col = 1) { this.app.editors.open(path, { line, col }).catch(() => null); }
}
/**
* The lens above each method / function of a PHP file: "↳ N calls", counted when it is on screen; a click opens the Calls window.
* Monaco resolves the lenses one by one, again after every change: the visible ones of a file are asked together (php.callCounts:
* one question, the text sent and analyzed once), and the counts of a version of the text are kept.
*/
export function registerCallLenses(monaco, app, pathOf) {
const command = monaco.editor.registerCommand('jumphp.calls', (_accessor, place) => app.calls?.show(place));
/** uri -> {version, counts: Map(line -> n), queue: [{place, resolve}], timer} */
const files = new Map();
const countOf = (model, place) => new Promise((resolve) => {
const uri = model.uri.toString();
let file = files.get(uri);
if (!file || file.version !== model.getVersionId()) {
// an edited file waits for a typing pause: the backend runs on the GTK thread and would block the keys
file = { version: model.getVersionId(), counts: new Map(), queue: [], timer: 0, wait: file ? 900 : 40 };
files.set(uri, file);
}
if (file.counts.has(place.line)) { resolve(file.counts.get(place.line)); return; }
file.queue.push({ place, resolve });
if (file.timer) return;
file.timer = setTimeout(async () => {
const queue = file.queue.splice(0);
file.timer = 0;
if (model.isDisposed() || model.getVersionId() !== file.version) { queue.forEach((q) => q.resolve(null)); return; }
const counts = await backend.invoke('php.callCounts', { path: place.path, text: model.getValue(),
places: queue.map((q) => ({ line: q.place.line, column: q.place.column })) }).catch(() => null);
queue.forEach((q, i) => {
const n = Array.isArray(counts) ? (counts[i] || 0) : null;
if (n !== null) file.counts.set(q.place.line, n);
q.resolve(n);
});
}, file.wait);
});
monaco.editor.onWillDisposeModel?.((model) => files.delete(model.uri.toString()));
monaco.languages.registerCodeLensProvider('php', {
provideCodeLenses(model) {
const lenses = [];
const lines = model.getLinesContent();
for (let i = 0; i < lines.length && lenses.length < 400; i++) {
if (!lines[i].includes('function')) continue;
const m = /^\s*(?:(?:public|protected|private|static|final|abstract|readonly)\s+)*function\s+&?([A-Za-z_]\w*)\s*\(/.exec(lines[i]);
if (!m || m[1].startsWith('__')) continue;
const column = lines[i].indexOf(m[1], lines[i].indexOf('function')) + 1;
lenses.push({ range: new monaco.Range(i + 1, 1, i + 1, 1), id: `calls:${i + 1}`, place: { path: pathOf(model.uri), line: i + 1, column } });
}
return { lenses, dispose() {} };
},
async resolveCodeLens(model, lens, token) {
const n = token?.isCancellationRequested ? null : await countOf(model, lens.place);
// the text only when the window asks (a getter: no copy of the whole file per lens)
const place = { ...lens.place, get text() { return model.isDisposed() ? undefined : model.getValue(); } };
lens.command = { id: command ? 'jumphp.calls' : '', title: n === null ? '↳ …' : n ? `↳ ${t('{n} call(s)', { n })}` : `↳ ${t('no call')}`, arguments: [place] };
return lens;
},
});
}