All files / views/trees/definition-tree definition-tree.ts

84.93% Statements 62/73
75% Branches 27/36
72.41% Functions 21/29
87.14% Lines 61/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                                    18x     74x       36x           18x                   18x 18x   18x             18x   18x   18x                                 18x   18x 18x 18x   18x       18x 18x                                     18x 3x         18x 1x               18x               18x 1x 1x 1x         18x               18x   18x               18x   18x 9x 8x 1x     7x   7x 1x     6x   8x 1x     5x     8x 3x             5x 5x 5x   5x       3x   3x 2x         21x 21x             22x 20x   2x               23x 3x 3x   3x 2x   1x        
import * as vscode from 'vscode';
import { container } from 'tsyringe';
import { ServiceToken } from '@src/services/tokens';
import { Debouncer } from '@src/utilities/debounce';
import { ISettingsService } from '@src/services/core';
import { IDocumentContextService } from '@src/services/document';
import { TreeView } from '@src/views/trees/tree-view';
import { DefinitionNodeProvider } from './definition-node-provider';
import { DefinitionTreeNode } from './definition-tree-node';
import { DefinitionNodeDecorationProvider } from './definition-node-decoration-provider';
 
/**
 * Provides a combined explorer for classes, properties and individuals.
 */
export class DefinitionTree implements TreeView {
	/**
	 * The ID which is used to register the view and make it visible in VS Code.
	 */
	readonly id = "mentor.view.definitionTree";
 
	private get _contextService() {
		return container.resolve<IDocumentContextService>(ServiceToken.DocumentContextService);
	}
 
	private get _settings() {
		return container.resolve<ISettingsService>(ServiceToken.SettingsService);
	}
 
	/**
	 * The tree node provider.
	 */
	readonly treeDataProvider = new DefinitionNodeProvider();
 
	private readonly _decorationProvider: DefinitionNodeDecorationProvider;
 
	/**
	 * The tree view.
	 */
	readonly treeView: vscode.TreeView<DefinitionTreeNode>;
 
	constructor() {
		this._decorationProvider = new DefinitionNodeDecorationProvider(this.treeDataProvider);
		this.treeDataProvider.setIssueColorProvider(this._decorationProvider);
 
		this.treeView = vscode.window.createTreeView<DefinitionTreeNode>(this.id, {
			treeDataProvider: this.treeDataProvider,
			showCollapseAll: true
		});
 
		// Defer tree rebuilds while the view is hidden and run them when it is
		// shown again.
		this.treeDataProvider.setViewVisibilityProvider(() => this.treeView.visible);
 
		this._onDidChangeDocumentContext();
 
		const disposables: vscode.Disposable[] = [
			this.treeView,
			this._decorationProvider,
			this._registerDocumentContextHandler(),
			this._registerDecorationProvider(),
			this._registerValidationHandler(),
			this._registerActiveLanguageHandler(),
			this._registerPredicateSettingsHandler(),
			this._registerRefreshCommand(),
			this._registerEditorSelectionHandler(),
			this.treeView.onDidChangeVisibility(e => {
				if (e.visible) {
					this.treeDataProvider.flushPendingRefresh();
				}
			})
		];
 
		const showReferences = this._settings.get('view.showReferences', true);
 
		vscode.commands.executeCommand("setContext", "view.showReferences", showReferences);
		vscode.commands.executeCommand("setContext", "view.showPropertyTypes", true);
		vscode.commands.executeCommand("setContext", "view.showIndividualTypes", true);
 
		Iif (typeof process !== 'undefined' && process.env.MENTOR_E2E === '1') {
			disposables.push(this._registerTestHooks());
		}
 
		const context = container.resolve<vscode.ExtensionContext>(ServiceToken.ExtensionContext);
		context.subscriptions.push(...disposables);
	}
 
	/**
	 * Test-only hook for the e2e suite: reports the state of the tree view, which the VS Code API
	 * does not expose to other extensions. Never registered in normal runs.
	 * @returns A disposable that unregisters the command.
	 */
	private _registerTestHooks(): vscode.Disposable {
		return vscode.commands.registerCommand('mentor.e2e.getDefinitionTreeState', () => ({
			visible: this.treeView.visible,
			selection: this.treeView.selection.map(node => node.id),
			activeContext: this._contextService.activeContext?.uri.toString(),
			document: this.treeDataProvider.document?.uri.toString(),
			rootCount: (this.treeDataProvider.getChildren(undefined) ?? []).length
		}));
	}
 
	private _registerDocumentContextHandler(): vscode.Disposable {
		return this._contextService.onDidChangeDocumentContext(() => {
			this._onDidChangeDocumentContext();
		});
	}
 
	private _registerActiveLanguageHandler(): vscode.Disposable {
		return this._settings.onDidChange("view.activeLanguage", () => {
			this._updateViewTitle();
		});
	}
 
	private _registerPredicateSettingsHandler(): vscode.Disposable {
		// Node labels and tooltips are derived from the mentor.predicates.* settings;
		// re-render the tree as soon as they change so the new predicates apply
		// immediately instead of on the next document switch.
		return vscode.workspace.onDidChangeConfiguration((e) => {
			if (e.affectsConfiguration('mentor.predicates.label') || e.affectsConfiguration('mentor.predicates.description')) {
				this.treeDataProvider.refresh(this._contextService.activeContext);
			}
		});
	}
 
	private _registerRefreshCommand(): vscode.Disposable {
		return vscode.commands.registerCommand('mentor.command.refreshDefinitionsTree', async () => {
			this._updateView();
			this._updateViewTitle();
			this.treeDataProvider.refresh(this._contextService.activeContext);
		});
	}
 
	private _registerDecorationProvider(): vscode.Disposable {
		return vscode.window.registerFileDecorationProvider(this._decorationProvider);
	}
 
	private _registerValidationHandler(): vscode.Disposable {
		// The node icons are colored by SHACL severity, so the tree is rebuilt when a
		// validation changes the severities of the active document. Validations fire for
		// every document and on every edit that drops a result; most leave the severities
		// unchanged and must not rebuild the tree. Coalesce the rebuilds that remain.
		const debouncer = new Debouncer(250);
 
		return this._decorationProvider.onDidChangeSeverities(() => {
			debouncer.schedule(() => {
				this.treeDataProvider.refresh(this._contextService.activeContext);
			});
		});
	}
 
	private _registerEditorSelectionHandler(): vscode.Disposable {
		const debouncer = new Debouncer(300);
 
		return vscode.window.onDidChangeTextEditorSelection((e) => {
			debouncer.schedule(() => {
				if (this.treeView.visible === false) {
					return;
				}
 
				const context = this._contextService.contexts[e.textEditor.document.uri.toString()];
 
				if (!context) {
					return;
				}
 
				const position = e.selections[0]?.active;
 
				if (!position) {
					return;
				}
 
				const iri = this._getShaclFocusNodeForSelection(e.textEditor.document.uri, position)
					?? context.getIriAtPosition(position);
 
				if (iri) {
					this._revealForUri(iri);
				}
			});
		});
	}
 
	private _getShaclFocusNodeForSelection(documentUri: vscode.Uri, position: vscode.Position): string | undefined {
		const diagnostics = vscode.languages.getDiagnostics(documentUri);
		const shaclDiagnostic = diagnostics.find((d) => d.source === 'SHACL' && d.range.contains(position));
		const focusNode = (shaclDiagnostic as vscode.Diagnostic & { data?: { focusNode?: string } } | undefined)?.data?.focusNode;
 
		return typeof focusNode === 'string' && focusNode.length > 0 ? focusNode : undefined;
	}
 
	private _revealForUri(iri: string): void {
		const node = this.treeDataProvider.getNodeForUri(iri);
 
		if (node) {
			this.treeView.reveal(node, { select: true, focus: false, expand: true });
		}
	}
 
	private _onDidChangeDocumentContext() {
		this._updateView();
		this._updateViewTitle();
	}
 
	/**
	 * Shows a message in the tree view if no file is selected.
	 */
	private _updateView() {
		if (!this._contextService.activeContext) {
			this.treeView.message = "No file selected.";
		} else {
			this.treeView.message = undefined;
		}
	}
 
	/**
	 * Update the title of the tree view to include the active language.
	 */
	private _updateViewTitle() {
		if (this._contextService.activeContext) {
			const title = this.treeView.title?.split(' - ')[0];
			const language = this._contextService.activeContext.activeLanguageTag;
 
			if (language) {
				this.treeView.title = `${title} - ${language}`;
			} else {
				this.treeView.title = title;
			}
		}
	}
}