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

98.36% Statements 60/61
100% Branches 26/26
95.45% Functions 21/22
98.33% Lines 59/60

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                                    18x     74x       36x       18x           18x                   18x 18x   18x         18x   18x                   18x   18x 18x 18x   18x 18x       18x 3x         18x 1x         18x 1x 1x 1x         18x       18x               18x 9x 1x     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 { 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';
import { ShaclValidationService } from '@src/services/validation/shacl-validation-service';
 
/**
 * 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);
	}
 
	private get _validationService() {
		return container.resolve<ShaclValidationService>(ServiceToken.ShaclValidationService);
	}
 
	/**
	 * 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
		});
 
		this._onDidChangeDocumentContext();
 
		const disposables: vscode.Disposable[] = [
			this.treeView,
			this._registerDocumentContextHandler(),
			this._registerDecorationProvider(),
			this._registerValidationHandler(),
			this._registerActiveLanguageHandler(),
			this._registerRefreshCommand(),
			this._registerEditorSelectionHandler()
		];
 
		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);
 
		const context = container.resolve<vscode.ExtensionContext>(ServiceToken.ExtensionContext);
		context.subscriptions.push(...disposables);
	}
 
	private _registerDocumentContextHandler(): vscode.Disposable {
		return this._contextService.onDidChangeDocumentContext(() => {
			this._onDidChangeDocumentContext();
		});
	}
 
	private _registerActiveLanguageHandler(): vscode.Disposable {
		return this._settings.onDidChange("view.activeLanguage", () => {
			this._updateViewTitle();
		});
	}
 
	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 {
		return this._validationService.onDidValidate(() => {
			this.treeDataProvider.refresh(this._contextService.activeContext);
		});
	}
 
	private _registerEditorSelectionHandler(): vscode.Disposable {
		let debounceTimer: ReturnType<typeof setTimeout> | undefined;
 
		return vscode.window.onDidChangeTextEditorSelection((e) => {
			if (debounceTimer) {
				clearTimeout(debounceTimer);
			}
 
			debounceTimer = setTimeout(() => {
				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);
				}
			}, 300);
		});
	}
 
	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;
			}
		}
	}
}