All files / commands implement-prefix-for-iri.ts

100% Statements 15/15
100% Branches 8/8
100% Functions 2/2
100% Lines 14/14

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                1x     5x   5x 4x 4x 4x   4x   2x   2x   1x     1x 1x     1x     1x          
import * as vscode from 'vscode';
import { container } from 'tsyringe';
import { IToken } from '@faubulous/mentor-rdf-parsers';
import { ServiceToken } from '@src/services/tokens';
import { TurtlePrefixDefinitionService } from '../languages/turtle/services/turtle-prefix-definition-service';
import { getTokenPosition } from '@src/utilities';
import { calculateLineOffset } from '@src/utilities/vscode/edit';
 
export const implementPrefixForIri = {
	id: 'mentor.command.implementPrefixForIri',
	handler: async (documentUri: vscode.Uri, namespaceIri: string, token: IToken) => {
		const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === documentUri.toString());
 
		if (document) {
			const editor = vscode.window.activeTextEditor;
			const service = container.resolve<TurtlePrefixDefinitionService>(ServiceToken.TurtlePrefixDefinitionService);
			const edit = await service.implementPrefixForIri(document, namespaceIri);
 
			if (editor && edit.size > 0) {
				// Await the edit application, after this the document is changed and the token position is invalid.
				const success = await vscode.workspace.applyEdit(edit);
 
				if (success) {
					// The token position is valid for the unedited document.
					const position = getTokenPosition(token);
 
					// Calculate the line offset caused by the edit.
					const lineOffset = calculateLineOffset(edit);
					const start = new vscode.Position(position.start.line + lineOffset, position.start.character);
 
					// Set the cursor the the start of the original IRI token which is now the prefix.
					editor.selection = new vscode.Selection(start, start);
 
					// Trigger renaming the prefix.
					vscode.commands.executeCommand('editor.action.rename');
				}
			}
		}
	}
};