Files
lucisv/editors/vscode/hierarchyView.js
T
lucioandClaude Fable 5 651e58bfb3 The design-hierarchy sidebar: codex's feature, integrated
An instance-oriented hierarchy view in the Activity Bar —
lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges,
derived ids; 11.6 MB -> 2.3 MB on opentitan) plus
lucisv/moduleHierarchyChanged invalidation, gated on the extension's
initializationOptions. Format 5 carries decl spans, instance
occurrences and client positions for file-scope declarations
(+1.7-1.9 % store), so a snapshot reads no files at all: handler
145-167 -> 17-20 ms settled, a save with the sidebar open 366 ->
141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds:
no hover preview, all levels collapsed by default with stable ids
across refreshes, and search over a resident flat model (freeze
diagnosed: materialized expanded tree x undebounced double
fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased
index, bitmask prefilter, top-K counting, 200-row cap with an honest
remainder, single-digit ms over a 120k-entry fixture.
LineIndex::utf16_position unifies the index's and the wire's position
math under a cross-crate agreement test.

Implementation: codex. Integration fixes + owner items: Opus dev.
QA: lead (measurement pass) + Sonnet (SHIP, independent oracles).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:39:06 -07:00

277 lines
10 KiB
JavaScript

const crypto = require('crypto');
const vscode = require('vscode');
const {
bookmarkChain,
buildHierarchy,
idForPath,
searchHierarchy,
searchTarget,
treeRows,
} = require('./hierarchyModel');
const VIEW_ID = 'lucisv.hierarchy';
const SNAPSHOT_METHOD = 'lucisv/moduleHierarchy';
const CHANGED_METHOD = 'lucisv/moduleHierarchyChanged';
const BOOKMARK_KEY = 'lucisv.hierarchy.bookmark';
const REFRESH_DEBOUNCE_MS = 100;
class HierarchyView {
constructor(context, client) {
this.context = context;
this.client = client;
this.view = undefined;
this.model = undefined;
this.query = '';
// Which rows the user has opened. Row ids are composed from URIs and
// declaration positions, so they survive a refresh and what was open stays
// open — nothing is expanded on the user's behalf (owner, 2026-08-29).
this.expanded = new Set();
this.nodes = new Map();
this.request = 0;
this.refreshTimer = undefined;
this.bookmarkPath = context.workspaceState.get(BOOKMARK_KEY, '');
this.lostBookmarkReported = false;
context.subscriptions.push(
vscode.window.registerWebviewViewProvider(VIEW_ID, this, {
webviewOptions: { retainContextWhenHidden: true },
}),
vscode.commands.registerCommand('lucisv.hierarchy.refresh', () => this.refresh()),
vscode.commands.registerCommand('lucisv.hierarchy.clearBookmark', () => this.setBookmark('')),
client.onNotification(CHANGED_METHOD, () => this.scheduleRefresh()),
{ dispose: () => clearTimeout(this.refreshTimer) },
);
}
resolveWebviewView(view) {
this.view = view;
const media = vscode.Uri.joinPath(this.context.extensionUri, 'media');
view.webview.options = {
enableScripts: true,
localResourceRoots: [media],
};
this.context.subscriptions.push(
view.webview.onDidReceiveMessage((message) => this.message(message)),
view.onDidDispose(() => {
if (this.view === view) this.view = undefined;
}),
);
// Install the receiver before loading the document: its script posts
// `ready` immediately, and even a fast webview must not outrun the host.
view.webview.html = html(view.webview, media);
}
onStarted() {
this.refresh();
}
scheduleRefresh() {
clearTimeout(this.refreshTimer);
this.refreshTimer = setTimeout(() => this.refresh(), REFRESH_DEBOUNCE_MS);
}
async refresh() {
if (!this.view) return;
const asked = ++this.request;
this.post({ type: 'status', text: 'Loading hierarchy…' });
try {
const snapshot = await this.client.sendRequest(SNAPSHOT_METHOD, {});
if (asked !== this.request) return;
this.model = buildHierarchy(snapshot);
if (this.bookmarkPath && !idForPath(this.model, this.bookmarkPath)) {
await this.context.workspaceState.update(BOOKMARK_KEY, undefined);
this.bookmarkPath = '';
if (!this.lostBookmarkReported) {
this.lostBookmarkReported = true;
vscode.window.showWarningMessage('The bookmarked lucisv instance no longer exists uniquely.');
}
} else {
this.lostBookmarkReported = false;
}
this.render();
} catch (error) {
if (asked !== this.request) return;
const code = error && (error.code || (error.data && error.data.code));
const oldServer = code === -32601 || /method.*not found/i.test(String(error && error.message));
this.post({
type: 'status',
error: true,
text: oldServer
? 'This lucisv server is too old for the hierarchy sidebar.'
: 'The hierarchy is unavailable while the language server is restarting.',
});
}
}
/// Post exactly the rows the view shows — the open part of the tree, or one
/// page of search results. Never the whole design: shipping every path of it
/// on every keystroke is what froze the UI.
render() {
if (!this.model) return;
const common = {
type: 'render',
revision: this.model.revision,
complete: this.model.complete,
query: this.query,
empty: this.model.roots.length === 0,
};
if (this.query.trim() !== '') {
const found = searchHierarchy(this.model, this.query);
this.post({ ...common, mode: 'search', rows: found.rows, truncated: found.truncated, total: found.total });
return;
}
const tree = treeRows(this.model, this.expanded, this.bookmarkPath);
this.nodes = tree.nodes;
this.post({ ...common, mode: 'tree', rows: tree.rows, truncated: 0, total: tree.rows.length });
}
async message(message) {
if (!message || typeof message.type !== 'string') return;
if (message.type === 'ready') {
await this.refresh();
return;
}
if (message.type === 'search' && typeof message.query === 'string') {
this.query = message.query.slice(0, 256);
this.render();
return;
}
if (!this.model || typeof message.id !== 'string') return;
if (message.type === 'toggle') {
if (this.expanded.has(message.id)) this.expanded.delete(message.id);
else this.expanded.add(message.id);
this.render();
return;
}
// A tree row is a path the view is currently showing; a search row names a
// module and, for an instance, which module writes it. Both resolve to the
// same three things an action needs: a site, a definition, and candidates.
const node = this.nodes.get(message.id) || searchTarget(this.model, message.id);
if (!node) return;
if (message.type === 'activate') {
await this.show(node.kind === 'instance' ? node.site : node.definition, false);
return;
}
if (message.type !== 'context' || typeof message.action !== 'string') return;
const actions = new Set(['copyPath', 'definition', 'instance', 'bookmark', 'openRight']);
if (!actions.has(message.action) || node.kind !== 'instance') return;
// A search hit is one row for an instance however many paths reach it, so
// it has no one full path to copy or bookmark.
if (!node.fullPath && (message.action === 'copyPath' || message.action === 'bookmark')) {
vscode.window.showWarningMessage('Clear the search to copy or bookmark an instance path.');
return;
}
switch (message.action) {
case 'copyPath':
await vscode.env.clipboard.writeText(node.fullPath);
break;
case 'definition':
await this.showDefinition(node, false);
break;
case 'instance':
await this.show(node.site, false);
break;
case 'bookmark':
await this.setBookmark(this.bookmarkPath === node.fullPath ? '' : node.fullPath);
break;
case 'openRight':
await this.showDefinition(node, true);
break;
default:
break;
}
}
async setBookmark(path) {
this.bookmarkPath = path;
await this.context.workspaceState.update(BOOKMARK_KEY, path || undefined);
// The one expansion the view performs for the user, and only because the
// user asked for it by bookmarking: the direct ancestors of the marked row.
const chain = path && bookmarkChain(this.model, path);
if (chain) for (const id of chain.slice(0, -1)) this.expanded.add(id);
this.render();
}
async showDefinition(node, beside) {
let location;
if (node.definitions.length === 0) {
vscode.window.showWarningMessage(`No indexed definition was found for module ${node.moduleName}.`);
return;
}
if (node.definitions.length === 1) {
[location] = node.definitions;
} else {
const choices = node.definitions.map((candidate) => ({
label: vscode.workspace.asRelativePath(vscode.Uri.parse(candidate.uri), false),
description: `${candidate.selectionRange.start.line + 1}:${candidate.selectionRange.start.character + 1}`,
location: candidate,
}));
const picked = await vscode.window.showQuickPick(choices, {
placeHolder: `Choose a definition for ${node.moduleName}`,
});
if (!picked) return;
location = picked.location;
}
await this.show(location, beside);
}
async show(location, beside) {
if (!location) return;
const document = await vscode.workspace.openTextDocument(vscode.Uri.parse(location.uri));
await vscode.window.showTextDocument(document, {
viewColumn: beside ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active,
preserveFocus: false,
preview: !beside,
selection: asRange(location.selectionRange),
});
}
post(message) {
if (this.view) this.view.webview.postMessage(message);
}
}
function asRange(range) {
return new vscode.Range(
range.start.line,
range.start.character,
range.end.line,
range.end.character,
);
}
function html(webview, media) {
const nonce = crypto.randomBytes(16).toString('base64');
const script = webview.asWebviewUri(vscode.Uri.joinPath(media, 'hierarchy.js'));
const style = webview.asWebviewUri(vscode.Uri.joinPath(media, 'hierarchy.css'));
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<link rel="stylesheet" href="${style}">
<title>lucisv Hierarchy</title>
</head>
<body>
<div class="search-wrap">
<input id="search" type="search" placeholder="Search module or instance" aria-label="Search module or instance names" autocomplete="off" spellcheck="false">
</div>
<div id="status" role="status" aria-live="polite">Loading hierarchy…</div>
<div id="tree" role="tree" aria-label="Module instance hierarchy"></div>
<div id="results" role="listbox" aria-label="Hierarchy search results" hidden></div>
<div id="more" hidden></div>
<div id="menu" role="menu" aria-label="Instance actions" hidden>
<button role="menuitem" data-action="copyPath">Copy Full Path</button>
<button role="menuitem" data-action="definition">Show Definition</button>
<button role="menuitem" data-action="instance">Show Instance</button>
<button role="menuitem" data-action="bookmark">Highlight / Bookmark</button>
<button role="menuitem" data-action="openRight">Open on the Right</button>
</div>
<script nonce="${nonce}" src="${script}"></script>
</body>
</html>`;
}
module.exports = { HierarchyView, VIEW_ID };