codelensWidget.ts 10.5 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

J
Johannes Rieken 已提交
6
import 'vs/css!./codelensWidget';
7
import * as dom from 'vs/base/browser/dom';
A
Alex Dima 已提交
8
import { coalesce, isFalsyOrEmpty } from 'vs/base/common/arrays';
9
import { IDisposable } from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
10
import { escape, format } from 'vs/base/common/strings';
11
import * as editorBrowser from 'vs/editor/browser/editorBrowser';
A
Alex Dima 已提交
12 13
import { Range } from 'vs/editor/common/core/range';
import { IModelDecorationsChangeAccessor, IModelDeltaDecoration, ITextModel } from 'vs/editor/common/model';
A
Alex Dima 已提交
14
import { ModelDecorationOptions } from 'vs/editor/common/model/textModel';
A
Alex Dima 已提交
15
import { Command, ICodeLensSymbol } from 'vs/editor/common/modes';
16
import { editorCodeLensForeground } from 'vs/editor/common/view/editorColorRegistry';
A
Alex Dima 已提交
17 18
import { ICodeLensData } from 'vs/editor/contrib/codelens/codelens';
import { ICommandService } from 'vs/platform/commands/common/commands';
19
import { INotificationService } from 'vs/platform/notification/common/notification';
A
Alex Dima 已提交
20 21
import { editorActiveLinkForeground } from 'vs/platform/theme/common/colorRegistry';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
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

class CodeLensViewZone implements editorBrowser.IViewZone {

	readonly heightInLines: number;
	readonly suppressMouseDown: boolean;
	readonly domNode: HTMLElement;

	afterLineNumber: number;

	private _lastHeight: number;
	private _onHeight: Function;

	constructor(afterLineNumber: number, onHeight: Function) {
		this.afterLineNumber = afterLineNumber;
		this._onHeight = onHeight;

		this.heightInLines = 1;
		this.suppressMouseDown = true;
		this.domNode = document.createElement('div');
	}

	onComputedHeight(height: number): void {
		if (this._lastHeight === undefined) {
			this._lastHeight = height;
		} else if (this._lastHeight !== height) {
			this._lastHeight = height;
			this._onHeight();
		}
	}
}

class CodeLensContentWidget implements editorBrowser.IContentWidget {

	private static _idPool: number = 0;

	// Editor.IContentWidget.allowEditorOverflow
	readonly allowEditorOverflow: boolean = false;
	readonly suppressMouseDown: boolean = true;

	private readonly _id: string;
	private readonly _domNode: HTMLElement;
63
	private readonly _disposable: IDisposable;
64 65 66 67 68 69 70 71 72
	private readonly _editor: editorBrowser.ICodeEditor;

	private _widgetPosition: editorBrowser.IContentWidgetPosition;
	private _commands: { [id: string]: Command } = Object.create(null);

	constructor(
		editor: editorBrowser.ICodeEditor,
		symbolRange: Range,
		commandService: ICommandService,
73
		notificationService: INotificationService
74 75 76 77 78 79 80 81 82 83 84
	) {

		this._id = 'codeLensWidget' + (++CodeLensContentWidget._idPool);
		this._editor = editor;

		this.setSymbolRange(symbolRange);

		this._domNode = document.createElement('span');
		this._domNode.innerHTML = ' ';
		dom.addClass(this._domNode, 'codelens-decoration');
		dom.addClass(this._domNode, 'invisible-cl');
85
		this.updateHeight();
86

87
		this._disposable = dom.addDisposableListener(this._domNode, 'click', e => {
88 89 90 91 92
			let element = <HTMLElement>e.target;
			if (element.tagName === 'A' && element.id) {
				let command = this._commands[element.id];
				if (command) {
					editor.focus();
93
					commandService.executeCommand(command.id, ...command.arguments).then(undefined, err => {
94
						notificationService.error(err);
95 96 97
					});
				}
			}
98
		});
99 100 101 102 103

		this.updateVisibility();
	}

	dispose(): void {
104
		this._disposable.dispose();
105 106
	}

107
	updateHeight(): void {
108 109 110 111
		const { fontInfo, lineHeight } = this._editor.getConfiguration();
		this._domNode.style.height = `${Math.round(lineHeight * 1.1)}px`;
		this._domNode.style.lineHeight = `${lineHeight}px`;
		this._domNode.style.fontSize = `${Math.round(fontInfo.fontSize * .9)}px`;
112
		this._domNode.style.paddingRight = `${Math.round(fontInfo.fontSize * .45)}px`;
113 114 115 116 117 118 119 120 121 122 123 124
		this._domNode.innerHTML = '&nbsp;';
	}

	updateVisibility(): void {
		if (this.isVisible()) {
			dom.removeClass(this._domNode, 'invisible-cl');
			dom.addClass(this._domNode, 'fadein');
		}
	}

	withCommands(symbols: ICodeLensSymbol[]): void {
		this._commands = Object.create(null);
J
Johannes Rieken 已提交
125 126
		symbols = coalesce(symbols);
		if (isFalsyOrEmpty(symbols)) {
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
			this._domNode.innerHTML = 'no commands';
			return;
		}

		let html: string[] = [];
		for (let i = 0; i < symbols.length; i++) {
			let command = symbols[i].command;
			let title = escape(command.title);
			let part: string;
			if (command.id) {
				part = format('<a id={0}>{1}</a>', i, title);
				this._commands[i] = command;
			} else {
				part = format('<span>{0}</span>', title);
			}
			html.push(part);
		}

		this._domNode.innerHTML = html.join('<span>&nbsp;|&nbsp;</span>');
		this._editor.layoutContentWidget(this);
	}

	getId(): string {
		return this._id;
	}

	getDomNode(): HTMLElement {
		return this._domNode;
	}

	setSymbolRange(range: Range): void {
		const lineNumber = range.startLineNumber;
		const column = this._editor.getModel().getLineFirstNonWhitespaceColumn(lineNumber);
		this._widgetPosition = {
			position: { lineNumber: lineNumber, column: column },
			preference: [editorBrowser.ContentWidgetPositionPreference.ABOVE]
		};
	}

	getPosition(): editorBrowser.IContentWidgetPosition {
		return this._widgetPosition;
	}

	isVisible(): boolean {
		return this._domNode.hasAttribute('monaco-visible-content-widget');
	}
}

export interface IDecorationIdCallback {
	(decorationId: string): void;
}

export class CodeLensHelper {

	private _removeDecorations: string[];
182
	private _addDecorations: IModelDeltaDecoration[];
183 184 185 186 187 188 189 190
	private _addDecorationsCallbacks: IDecorationIdCallback[];

	constructor() {
		this._removeDecorations = [];
		this._addDecorations = [];
		this._addDecorationsCallbacks = [];
	}

191
	addDecoration(decoration: IModelDeltaDecoration, callback: IDecorationIdCallback): void {
192 193 194 195 196 197 198 199
		this._addDecorations.push(decoration);
		this._addDecorationsCallbacks.push(callback);
	}

	removeDecoration(decorationId: string): void {
		this._removeDecorations.push(decorationId);
	}

200
	commit(changeAccessor: IModelDecorationsChangeAccessor): void {
A
Alex Dima 已提交
201
		let resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations);
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
		for (let i = 0, len = resultingDecorations.length; i < len; i++) {
			this._addDecorationsCallbacks[i](resultingDecorations[i]);
		}
	}
}

export class CodeLens {

	private readonly _editor: editorBrowser.ICodeEditor;
	private readonly _viewZone: CodeLensViewZone;
	private readonly _viewZoneId: number;
	private readonly _contentWidget: CodeLensContentWidget;
	private _decorationIds: string[];
	private _data: ICodeLensData[];

	constructor(
		data: ICodeLensData[],
		editor: editorBrowser.ICodeEditor,
		helper: CodeLensHelper,
		viewZoneChangeAccessor: editorBrowser.IViewZoneChangeAccessor,
222
		commandService: ICommandService, notificationService: INotificationService,
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
		updateCallabck: Function
	) {
		this._editor = editor;
		this._data = data;
		this._decorationIds = new Array<string>(this._data.length);

		let range: Range;
		this._data.forEach((codeLensData, i) => {

			helper.addDecoration({
				range: codeLensData.symbol.range,
				options: ModelDecorationOptions.EMPTY
			}, id => this._decorationIds[i] = id);

			// the range contains all lenses on this line
			if (!range) {
				range = Range.lift(codeLensData.symbol.range);
			} else {
				range = Range.plusRange(range, codeLensData.symbol.range);
			}
		});

245
		this._contentWidget = new CodeLensContentWidget(editor, range, commandService, notificationService);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
		this._viewZone = new CodeLensViewZone(range.startLineNumber - 1, updateCallabck);

		this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone);
		this._editor.addContentWidget(this._contentWidget);
	}

	dispose(helper: CodeLensHelper, viewZoneChangeAccessor: editorBrowser.IViewZoneChangeAccessor): void {
		while (this._decorationIds.length) {
			helper.removeDecoration(this._decorationIds.pop());
		}
		if (viewZoneChangeAccessor) {
			viewZoneChangeAccessor.removeZone(this._viewZoneId);
		}
		this._editor.removeContentWidget(this._contentWidget);

		this._contentWidget.dispose();
	}

	isValid(): boolean {
		return this._decorationIds.some((id, i) => {
			const range = this._editor.getModel().getDecorationRange(id);
			const symbol = this._data[i].symbol;
			return range && Range.isEmpty(symbol.range) === range.isEmpty();
		});
	}

	updateCodeLensSymbols(data: ICodeLensData[], helper: CodeLensHelper): void {
		while (this._decorationIds.length) {
			helper.removeDecoration(this._decorationIds.pop());
		}
		this._data = data;
		this._decorationIds = new Array<string>(this._data.length);
		this._data.forEach((codeLensData, i) => {
			helper.addDecoration({
				range: codeLensData.symbol.range,
				options: ModelDecorationOptions.EMPTY
			}, id => this._decorationIds[i] = id);
		});
	}

A
Alex Dima 已提交
286
	computeIfNecessary(model: ITextModel): ICodeLensData[] {
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
		this._contentWidget.updateVisibility(); // trigger the fade in
		if (!this._contentWidget.isVisible()) {
			return null;
		}

		// Read editor current state
		for (let i = 0; i < this._decorationIds.length; i++) {
			this._data[i].symbol.range = model.getDecorationRange(this._decorationIds[i]);
		}
		return this._data;
	}

	updateCommands(symbols: ICodeLensSymbol[]): void {
		this._contentWidget.withCommands(symbols);
	}

303 304 305 306
	updateHeight(): void {
		this._contentWidget.updateHeight();
	}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
	getLineNumber(): number {
		const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
		if (range) {
			return range.startLineNumber;
		}
		return -1;
	}

	update(viewZoneChangeAccessor: editorBrowser.IViewZoneChangeAccessor): void {
		if (this.isValid()) {
			const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);

			this._viewZone.afterLineNumber = range.startLineNumber - 1;
			viewZoneChangeAccessor.layoutZone(this._viewZoneId);

			this._contentWidget.setSymbolRange(range);
			this._editor.layoutContentWidget(this._contentWidget);
		}
	}
}

registerThemingParticipant((theme, collector) => {
M
Matt Bierner 已提交
329
	const codeLensForeground = theme.getColor(editorCodeLensForeground);
330 331 332
	if (codeLensForeground) {
		collector.addRule(`.monaco-editor .codelens-decoration { color: ${codeLensForeground}; }`);
	}
M
Matt Bierner 已提交
333
	const activeLinkForeground = theme.getColor(editorActiveLinkForeground);
334 335 336 337
	if (activeLinkForeground) {
		collector.addRule(`.monaco-editor .codelens-decoration > a:hover { color: ${activeLinkForeground} !important; }`);
	}
});