// Author: Guoliang Chen, a Senior Digital Design Engineer const crypto = require('crypto'); const vscode = require('vscode'); const { bookmarkChain, buildHierarchy, idForPath, searchHierarchy, searchTarget, treeRows, } = require('./hierarchyModel'); const { OTHERS_ID, decorate, defaultOpenIds, menuTable, sectionPrefixes, sectionRows, sections, } = require('./hierarchySections'); const { currentPath, levelChanges, matchingFiles, rowLevels, } = require('./hierarchyCurrent'); const VIEW_ID = 'lucisv.hierarchy'; const SNAPSHOT_METHOD = 'lucisv/moduleHierarchy'; const CHANGED_METHOD = 'lucisv/moduleHierarchyChanged'; const BOOKMARK_KEY = 'lucisv.hierarchy.bookmark'; /** The starred DUTs of this workspace, in the order they were starred. */ const DUTS_KEY = 'lucisv.hierarchy.duts'; /** The same list as a setting, so a team can check theirs in. */ const DUTS_SETTING = 'hierarchy.duts'; /** Whether the rows leading to the active file are lit (default on). */ const HIGHLIGHT_SETTING = 'hierarchy.highlightCurrent'; 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) // except what the user asked for by bookmarking or by starring a DUT. this.expanded = new Set(); this.nodes = new Map(); this.request = 0; this.refreshTimer = undefined; this.bookmarkPath = context.workspaceState.get(BOOKMARK_KEY, ''); this.lostBookmarkReported = false; // The DUTs this workspace starred, in starred order. The settings may name // more; `duts()` is the union the pane actually shows. this.starred = moduleNames(context.workspaceState.get(DUTS_KEY, [])); this.seededFor = undefined; // The current-file path (TODO §71.6). `shown` is the tree the webview holds // — kept while a search list covers it, because its rows are still in the // page — and `levels` what each of its rows is lit at, so a new active file // repaints only the rows whose level changed. this.activeUri = activeUriOf(vscode.window.activeTextEditor); this.pathCache = undefined; this.shown = { rows: [], nodes: new Map(), list: [] }; this.levels = new Map(); 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('')), vscode.commands.registerCommand('lucisv.hierarchy.starDut', (name) => this.starDut(name)), vscode.commands.registerCommand('lucisv.hierarchy.unstarDut', (name) => this.unstarDut(name)), vscode.commands.registerCommand('lucisv.hierarchy.clearDuts', () => this.clearDuts()), vscode.workspace.onDidChangeConfiguration((event) => { if (event.affectsConfiguration(`lucisv.${HIGHLIGHT_SETTING}`)) this.relight(); if (!event.affectsConfiguration('lucisv.hierarchy.duts')) return; this.seededFor = undefined; this.render(); }), vscode.window.onDidChangeActiveTextEditor((editor) => this.activeEditorChanged(editor)), client.onNotification(CHANGED_METHOD, () => this.scheduleRefresh()), { dispose: () => clearTimeout(this.refreshTimer) }, ); } /// The DUTs the settings name: a checked-in list the pane shows but will not /// edit, so its entries are locked against unstarring. lockedDuts() { return moduleNames(vscode.workspace.getConfiguration('lucisv').get(DUTS_SETTING, [])); } /// The effective list: the settings' DUTs first, then this workspace's own /// stars in the order they were made. duts() { const locked = this.lockedDuts(); return [...locked, ...this.starred.filter((name) => !locked.includes(name))]; } 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 duts = this.duts(); const locked = this.lockedDuts(); const common = { type: 'render', revision: this.model.revision, complete: this.model.complete, query: this.query, empty: this.model.roots.length === 0, // One table per render rather than a rule per row: the renderer shows // exactly the items a row's `contextValue` names and decides nothing. menus: menuTable(), }; if (this.query.trim() !== '') { const found = searchHierarchy(this.model, this.query); const rows = decorate(found.rows, duts, locked); this.post({ ...common, mode: 'search', rows, truncated: found.truncated, total: found.total }); return; } const tree = this.treeOrSections(duts); this.nodes = tree.nodes; this.shown = tree; this.levels = rowLevels(tree.rows, tree.nodes, tree.list, this.currentPath()); const rows = decorate(tree.rows, duts, locked); // Only a lit row carries the field, so an unlit pane's rows are exactly // what they were before this feature. for (const row of rows) { if (this.levels.has(row.id)) row.lit = this.levels.get(row.id); } this.post({ ...common, mode: 'tree', rows, truncated: 0, total: rows.length }); } /// With no DUT starred the pane is the plain tree, unchanged and untouched. treeOrSections(duts) { const key = duts.join('\n'); if (duts.length === 0) { // Recorded even here, so re-starring after a clear seeds again. this.seededFor = key; return { ...treeRows(this.model, this.expanded, this.bookmarkPath), list: [] }; } const list = sections(this.model, duts); this.seedExpansion(list, key); return { ...sectionRows(this.model, list, this.expanded, this.bookmarkPath), list }; } /// A new active editor relights the tree the webview already holds. No /// snapshot request and no row rebuild: two walks over the module graph, /// one lookup per row on screen, and a message naming the rows that changed. activeEditorChanged(editor) { // Focus leaving for a panel or a webview is not a new file; only an editor // area with nothing open in it is. if (!editor && vscode.window.visibleTextEditors.length > 0) return; const uri = activeUriOf(editor); if (editor && uri === undefined) return; if (uri === this.activeUri) return; this.activeUri = uri; this.relight(); } relight() { if (!this.model) return; const levels = rowLevels(this.shown.rows, this.shown.nodes, this.shown.list, this.currentPath()); const changes = levelChanges(this.levels, levels); this.levels = levels; if (changes.length > 0) this.post({ type: 'lit', changes }); } /// The distance maps for the active file, computed once per (snapshot, file) /// pair, so opening rows under one file never walks the graph again. currentPath() { const enabled = vscode.workspace.getConfiguration('lucisv').get(HIGHLIGHT_SETTING, true); if (enabled === false || !this.model || !this.activeUri) return undefined; const cache = this.pathCache; if (cache && cache.model === this.model && cache.uri === this.activeUri) return cache.path; const active = this.activeUri; const files = matchingFiles(this.model, (uri) => sameUri(uri, active)); const path = currentPath(this.model, files); this.pathCache = { model: this.model, uri: active, path }; return path; } /// Open the new sections once, when the DUT list changes — not on every /// render, so a section the user closes stays closed. seedExpansion(list, key) { if (this.seededFor === key) return; this.seededFor = key; for (const id of defaultOpenIds(list)) this.expanded.add(id); this.expanded.delete(OTHERS_ID); } 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; await this.contextAction(node, message.action); } /// One row's menu item, chosen by the host's own menu table — so an action a /// row does not offer is one this never sees, and every one is re-checked /// here anyway. async contextAction(node, action) { // Starring is about the row's module — for an instance row, its type — so // it is the one action a module row offers as well. if (action === 'starDut') { await this.starDut(node.moduleName); return; } if (action === 'unstarDut') { await this.unstarDut(node.moduleName); return; } const actions = new Set(['copyPath', 'definition', 'instance', 'bookmark', 'openRight']); if (!actions.has(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 && (action === 'copyPath' || action === 'bookmark')) { vscode.window.showWarningMessage('Clear the search to copy or bookmark an instance path.'); return; } switch (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. // A section holds its own copy of that chain, behind the section's prefix. const chain = path && bookmarkChain(this.model, path); const prefixes = ['', ...sectionPrefixes(this.duts())]; if (chain) { for (const id of chain.slice(0, -1)) { for (const prefix of prefixes) this.expanded.add(`${prefix}${id}`); } } this.render(); } /// Star a module as DUT. Called with a name from the pane's menu, and without /// one from the command palette, where the module is picked from the index. async starDut(name) { const chosen = name || await this.pickModule('Star a module as DUT', this.moduleNamesInIndex()); if (!chosen) return; if (this.duts().includes(chosen)) { vscode.window.showInformationMessage(`${chosen} is already a DUT.`); return; } this.starred = [...this.starred, chosen]; await this.context.workspaceState.update(DUTS_KEY, this.starred); this.render(); } async unstarDut(name) { const chosen = name || await this.pickModule('Unstar a DUT', this.starred); if (!chosen) return; if (this.lockedDuts().includes(chosen)) { vscode.window.showWarningMessage( `${chosen} comes from the lucisv.hierarchy.duts setting. Remove it there to unstar it.`, ); return; } if (!this.starred.includes(chosen)) return; this.starred = this.starred.filter((starred) => starred !== chosen); await this.context.workspaceState.update(DUTS_KEY, this.starred.length > 0 ? this.starred : undefined); this.render(); } /// Clear what this workspace starred. What the settings name stays, because /// only the settings file can take it away. async clearDuts() { this.starred = []; await this.context.workspaceState.update(DUTS_KEY, undefined); const locked = this.lockedDuts(); if (locked.length > 0) { vscode.window.showInformationMessage( `Cleared the starred DUTs; ${locked.join(', ')} come from the lucisv.hierarchy.duts setting.`, ); } this.render(); } moduleNamesInIndex() { if (!this.model) return []; return [...new Set(this.model.modules.map((module) => module.moduleName))].sort(); } async pickModule(placeHolder, choices) { if (choices.length === 0) { vscode.window.showWarningMessage('There is no module to choose: the hierarchy index is empty.'); return undefined; } return vscode.window.showQuickPick(choices, { placeHolder }); } 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); } } /// The active editor's file as a comparable string, or `undefined` for none. /// The Output panel's channels are text editors too, and are never a module. function activeUriOf(editor) { const uri = editor && editor.document && editor.document.uri; if (!uri || uri.scheme === 'output') return undefined; return uri.toString(); } /// The server writes URIs itself, and may encode them differently from VS Code /// (`file:///c%3A/…` against `file:///c:/…`); parsing both through `vscode.Uri` /// puts them in one spelling. function sameUri(serverUri, activeUri) { if (serverUri === activeUri) return true; try { return vscode.Uri.parse(serverUri).toString() === activeUri; } catch { return false; } } /// A stored or configured DUT list, made safe: non-strings, blanks and repeats /// are dropped, and the order the user chose is kept. function moduleNames(value) { if (!Array.isArray(value)) return []; return [...new Set(value.filter((name) => typeof name === 'string' && name.trim() !== ''))]; } 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 `