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

'use strict';

import 'vs/css!./media/notificationsToasts';
9
import { INotificationsModel, NotificationChangeType, INotificationChangeEvent, INotificationViewItem, NotificationViewItemLabelKind } from 'vs/workbench/common/notifications';
10
import { IDisposable, dispose, toDisposable } from 'vs/base/common/lifecycle';
B
Benjamin Pasero 已提交
11
import { addClass, removeClass, isAncestor, addDisposableListener, EventType } from 'vs/base/browser/dom';
12 13 14 15 16
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { NotificationsList } from 'vs/workbench/browser/parts/notifications/notificationsList';
import { Dimension } from 'vs/base/browser/builder';
import { once } from 'vs/base/common/event';
import { IPartService, Parts } from 'vs/workbench/services/part/common/partService';
17
import { Themable, NOTIFICATIONS_TOAST_BORDER } from 'vs/workbench/common/theme';
18 19
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { widgetShadow } from 'vs/platform/theme/common/colorRegistry';
20
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
21
import { NotificationsToastsVisibleContext } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
22
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
23
import { localize } from 'vs/nls';
24
import { Severity } from 'vs/platform/notification/common/notification';
25
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
B
Benjamin Pasero 已提交
26
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
27 28

interface INotificationToast {
29
	item: INotificationViewItem;
30 31
	list: NotificationsList;
	container: HTMLElement;
32
	toast: HTMLElement;
33 34 35
	disposeables: IDisposable[];
}

B
Benjamin Pasero 已提交
36 37 38 39 40 41
enum ToastVisibility {
	HIDDEN_OR_VISIBLE,
	HIDDEN,
	VISIBLE
}

42 43
export class NotificationsToasts extends Themable {

44
	private static MAX_WIDTH = 450;
45
	private static MAX_NOTIFICATIONS = 3;
46

47 48
	private static PURGE_TIMEOUT: { [severity: number]: number } = (() => {
		const intervals = Object.create(null);
49 50
		intervals[Severity.Info] = 10000;
		intervals[Severity.Warning] = 12000;
51 52 53 54 55
		intervals[Severity.Error] = 15000;

		return intervals;
	})();

56 57 58 59
	private notificationsToastsContainer: HTMLElement;
	private workbenchDimensions: Dimension;
	private isNotificationsCenterVisible: boolean;
	private mapNotificationToToast: Map<INotificationViewItem, INotificationToast>;
60
	private notificationsToastsVisibleContextKey: IContextKey<boolean>;
61 62 63 64 65 66

	constructor(
		private container: HTMLElement,
		private model: INotificationsModel,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPartService private partService: IPartService,
67
		@IThemeService themeService: IThemeService,
68
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
B
Benjamin Pasero 已提交
69 70
		@IContextKeyService contextKeyService: IContextKeyService,
		@ILifecycleService private lifecycleService: ILifecycleService
71 72 73 74
	) {
		super(themeService);

		this.mapNotificationToToast = new Map<INotificationViewItem, INotificationToast>();
75
		this.notificationsToastsVisibleContextKey = NotificationsToastsVisibleContext.bindTo(contextKeyService);
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

		// Show toast for initial notifications if any
		model.notifications.forEach(notification => this.addToast(notification));

		this.registerListeners();
	}

	private registerListeners(): void {
		this.toUnbind.push(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e)));
	}

	private onDidNotificationChange(e: INotificationChangeEvent): void {
		switch (e.kind) {
			case NotificationChangeType.ADD:
				return this.addToast(e.item);
			case NotificationChangeType.REMOVE:
				return this.removeToast(e.item);
		}
	}

	private addToast(item: INotificationViewItem): void {
		if (this.isNotificationsCenterVisible) {
			return; // do not show toasts while notification center is visibles
		}

		// Lazily create toasts containers
		if (!this.notificationsToastsContainer) {
			this.notificationsToastsContainer = document.createElement('div');
			addClass(this.notificationsToastsContainer, 'notifications-toasts');

			this.container.appendChild(this.notificationsToastsContainer);
		}

		// Make Visible
		addClass(this.notificationsToastsContainer, 'visible');

		const itemDisposeables: IDisposable[] = [];

		// Container
		const notificationToastContainer = document.createElement('div');
116
		addClass(notificationToastContainer, 'notification-toast-container');
117 118 119 120 121 122 123 124

		const firstToast = this.notificationsToastsContainer.firstChild;
		if (firstToast) {
			this.notificationsToastsContainer.insertBefore(notificationToastContainer, firstToast); // always first
		} else {
			this.notificationsToastsContainer.appendChild(notificationToastContainer);
		}

125
		itemDisposeables.push(toDisposable(() => this.notificationsToastsContainer.removeChild(notificationToastContainer)));
126

127 128 129 130 131
		// Toast
		const notificationToast = document.createElement('div');
		addClass(notificationToast, 'notification-toast');
		notificationToastContainer.appendChild(notificationToast);

132
		// Create toast with item and show
133
		const notificationList = this.instantiationService.createInstance(NotificationsList, notificationToast, {
134 135 136
			ariaLabel: localize('notificationsToast', "Notification Toast"),
			verticalScrollMode: ScrollbarVisibility.Hidden
		});
137
		itemDisposeables.push(notificationList);
138
		this.mapNotificationToToast.set(item, { item, list: notificationList, container: notificationToastContainer, toast: notificationToast, disposeables: itemDisposeables });
139 140 141 142

		// Make visible
		notificationList.show();

143 144 145
		// Layout lists
		const maxDimensions = this.computeMaxDimensions();
		this.layoutLists(maxDimensions.width);
146 147 148 149

		// Show notification
		notificationList.updateNotificationsList(0, 0, [item]);

150 151 152 153
		// Layout container: only after we show the notification to ensure that
		// the height computation takes the content of it into account!
		this.layoutContainer(maxDimensions.height);

154 155
		// Update when item height changes due to expansion
		itemDisposeables.push(item.onDidExpansionChange(() => {
156 157 158
			notificationList.updateNotificationsList(0, 1, [item]);
		}));

159 160 161 162 163 164 165
		// Update when item height potentially changes due to label changes
		itemDisposeables.push(item.onDidLabelChange(e => {
			if (e.kind === NotificationViewItemLabelKind.ACTIONS || e.kind === NotificationViewItemLabelKind.MESSAGE) {
				notificationList.updateNotificationsList(0, 1, [item]);
			}
		}));

166 167 168 169 170
		// Remove when item gets disposed
		once(item.onDidDispose)(() => {
			this.removeToast(item);
		});

B
Benjamin Pasero 已提交
171 172
		// Automatically hide collapsed notifications
		if (!item.expanded) {
B
Benjamin Pasero 已提交
173 174 175 176 177 178 179

			// Track mouse over item
			let isMouseOverToast = false;
			itemDisposeables.push(addDisposableListener(notificationToastContainer, EventType.MOUSE_OVER, () => isMouseOverToast = true));
			itemDisposeables.push(addDisposableListener(notificationToastContainer, EventType.MOUSE_OUT, () => isMouseOverToast = false));

			// Install Timers
180 181 182
			let timeoutHandle: number;
			const hideAfterTimeout = () => {
				timeoutHandle = setTimeout(() => {
B
Benjamin Pasero 已提交
183
					if (!notificationList.hasFocus() && !item.expanded && !isMouseOverToast) {
B
Benjamin Pasero 已提交
184
						this.removeToast(item);
185
					} else {
B
Benjamin Pasero 已提交
186
						hideAfterTimeout(); // push out disposal if item has focus or is expanded
187 188 189 190 191
					}
				}, NotificationsToasts.PURGE_TIMEOUT[item.severity]);
			};

			hideAfterTimeout();
192 193 194 195

			itemDisposeables.push(toDisposable(() => clearTimeout(timeoutHandle)));
		}

196 197
		// Theming
		this.updateStyles();
198 199 200

		// Context Key
		this.notificationsToastsVisibleContextKey.set(true);
B
Benjamin Pasero 已提交
201

B
Benjamin Pasero 已提交
202 203
		// Animate In if we are in a running session (otherwise just show directly)
		if (this.lifecycleService.phase >= LifecyclePhase.Running) {
204 205 206 207
			addClass(notificationToast, 'notification-fade-in');
			itemDisposeables.push(addDisposableListener(notificationToast, 'transitionend', () => {
				removeClass(notificationToast, 'notification-fade-in');
				addClass(notificationToast, 'notification-fade-in-done');
B
Benjamin Pasero 已提交
208 209
			}));
		} else {
210
			addClass(notificationToast, 'notification-fade-in-done');
B
Benjamin Pasero 已提交
211
		}
212 213 214 215
	}

	private removeToast(item: INotificationViewItem): void {
		const notificationToast = this.mapNotificationToToast.get(item);
216
		let focusEditor = false;
217
		if (notificationToast) {
218 219 220 221
			const toastHasDOMFocus = isAncestor(document.activeElement, notificationToast.container);
			if (toastHasDOMFocus) {
				focusEditor = !(this.focusNext() || this.focusPrevious()); // focus next if any, otherwise focus editor
			}
222 223 224 225 226 227 228 229

			// Listeners
			dispose(notificationToast.disposeables);

			// Remove from Map
			this.mapNotificationToToast.delete(item);
		}

230 231 232
		// Layout if we still have toasts
		if (this.mapNotificationToToast.size > 0) {
			this.layout(this.workbenchDimensions);
233 234
		}

235 236 237
		// Otherwise hide if no more toasts to show
		else {
			this.doHide();
238

239 240 241
			// Move focus to editor as needed
			if (focusEditor) {
				this.focusEditor();
242 243
			}
		}
244 245
	}

246 247 248 249 250 251 252
	private focusEditor(): void {
		const editor = this.editorService.getActiveEditor();
		if (editor) {
			editor.focus();
		}
	}

253 254 255 256
	private removeToasts(): void {
		this.mapNotificationToToast.forEach(toast => dispose(toast.disposeables));
		this.mapNotificationToToast.clear();

257 258 259 260
		this.doHide();
	}

	private doHide(): void {
261 262 263
		if (this.notificationsToastsContainer) {
			removeClass(this.notificationsToastsContainer, 'visible');
		}
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279

		// Context Key
		this.notificationsToastsVisibleContextKey.set(false);
	}

	public hide(): void {
		const focusEditor = isAncestor(document.activeElement, this.notificationsToastsContainer);

		this.removeToasts();

		if (focusEditor) {
			this.focusEditor();
		}
	}

	public focus(): boolean {
B
Benjamin Pasero 已提交
280
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
281 282 283 284 285 286 287 288 289 290
		if (toasts.length > 0) {
			toasts[0].list.focusFirst();

			return true;
		}

		return false;
	}

	public focusNext(): boolean {
B
Benjamin Pasero 已提交
291
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
		for (let i = 0; i < toasts.length; i++) {
			const toast = toasts[i];
			if (toast.list.hasFocus()) {
				const nextToast = toasts[i + 1];
				if (nextToast) {
					nextToast.list.focusFirst();

					return true;
				}

				break;
			}
		}

		return false;
	}

	public focusPrevious(): boolean {
B
Benjamin Pasero 已提交
310
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
		for (let i = 0; i < toasts.length; i++) {
			const toast = toasts[i];
			if (toast.list.hasFocus()) {
				const previousToast = toasts[i - 1];
				if (previousToast) {
					previousToast.list.focusFirst();

					return true;
				}

				break;
			}
		}

		return false;
326 327
	}

B
Benjamin Pasero 已提交
328
	public focusFirst(): boolean {
B
Benjamin Pasero 已提交
329
		const toast = this.getToasts(ToastVisibility.VISIBLE)[0];
B
Benjamin Pasero 已提交
330 331 332 333 334 335 336 337 338 339
		if (toast) {
			toast.list.focusFirst();

			return true;
		}

		return false;
	}

	public focusLast(): boolean {
B
Benjamin Pasero 已提交
340
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
B
Benjamin Pasero 已提交
341 342 343 344 345 346 347 348 349
		if (toasts.length > 0) {
			toasts[toasts.length - 1].list.focusFirst();

			return true;
		}

		return false;
	}

350 351 352 353 354 355 356 357 358 359 360 361
	public update(isCenterVisible: boolean): void {
		if (this.isNotificationsCenterVisible !== isCenterVisible) {
			this.isNotificationsCenterVisible = isCenterVisible;

			// Hide all toasts when the notificationcenter gets visible
			if (this.isNotificationsCenterVisible) {
				this.removeToasts();
			}
		}
	}

	protected updateStyles(): void {
362
		this.mapNotificationToToast.forEach(t => {
363
			const widgetShadowColor = this.getColor(widgetShadow);
364
			t.toast.style.boxShadow = widgetShadowColor ? `0 0px 8px ${widgetShadowColor}` : null;
365 366 367

			const borderColor = this.getColor(NOTIFICATIONS_TOAST_BORDER);
			t.toast.style.border = borderColor ? `1px solid ${borderColor}` : null;
368 369 370
		});
	}

B
Benjamin Pasero 已提交
371 372
	private getToasts(state: ToastVisibility): INotificationToast[] {
		const notificationToasts: INotificationToast[] = [];
B
Benjamin Pasero 已提交
373 374

		this.mapNotificationToToast.forEach(toast => {
B
Benjamin Pasero 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388
			switch (state) {
				case ToastVisibility.HIDDEN_OR_VISIBLE:
					notificationToasts.push(toast);
					break;
				case ToastVisibility.HIDDEN:
					if (!this.isVisible(toast)) {
						notificationToasts.push(toast);
					}
					break;
				case ToastVisibility.VISIBLE:
					if (this.isVisible(toast)) {
						notificationToasts.push(toast);
					}
					break;
B
Benjamin Pasero 已提交
389 390 391
			}
		});

B
Benjamin Pasero 已提交
392
		return notificationToasts.reverse(); // from newest to oldest
393 394
	}

395 396 397
	public layout(dimension: Dimension): void {
		this.workbenchDimensions = dimension;

398 399 400
		const maxDimensions = this.computeMaxDimensions();

		// Hide toasts that exceed height
401 402 403
		if (maxDimensions.height) {
			this.layoutContainer(maxDimensions.height);
		}
404 405 406

		// Layout all lists of toasts
		this.layoutLists(maxDimensions.width);
407 408 409
	}

	private computeMaxDimensions(): Dimension {
410
		let maxWidth = NotificationsToasts.MAX_WIDTH;
411 412

		let availableWidth = maxWidth;
413
		let availableHeight: number;
414 415 416 417 418

		if (this.workbenchDimensions) {

			// Make sure notifications are not exceding available width
			availableWidth = this.workbenchDimensions.width;
B
Benjamin Pasero 已提交
419
			availableWidth -= (2 * 8); // adjust for paddings left and right
420 421 422 423 424 425 426 427 428 429 430 431 432 433

			// Make sure notifications are not exceeding available height
			availableHeight = this.workbenchDimensions.height;
			if (this.partService.isVisible(Parts.STATUSBAR_PART)) {
				availableHeight -= 22; // adjust for status bar
			}

			if (this.partService.isVisible(Parts.TITLEBAR_PART)) {
				availableHeight -= 22; // adjust for title bar
			}

			availableHeight -= (2 * 12); // adjust for paddings top and bottom
		}

434
		return new Dimension(Math.min(maxWidth, availableWidth), availableHeight);
435
	}
436

437 438 439 440 441
	private layoutLists(width: number): void {
		this.mapNotificationToToast.forEach(toast => toast.list.layout(width));
	}

	private layoutContainer(heightToGive: number): void {
B
Benjamin Pasero 已提交
442 443
		let visibleToasts = 0;
		this.getToasts(ToastVisibility.HIDDEN_OR_VISIBLE).forEach(toast => {
444 445 446

			// In order to measure the client height, the element cannot have display: none
			toast.container.style.opacity = '0';
B
Benjamin Pasero 已提交
447
			this.setVisibility(toast, true);
448

449
			heightToGive -= toast.container.offsetHeight;
450

B
Benjamin Pasero 已提交
451 452 453 454 455 456 457 458 459
			let makeVisible = false;
			if (visibleToasts === NotificationsToasts.MAX_NOTIFICATIONS) {
				makeVisible = false; // never show more than MAX_NOTIFICATIONS
			} else if (heightToGive >= 0) {
				makeVisible = true; // hide toast if available height is too little
			}

			// Hide or show toast based on context
			this.setVisibility(toast, makeVisible);
460
			toast.container.style.opacity = null;
B
Benjamin Pasero 已提交
461 462 463 464

			if (makeVisible) {
				visibleToasts++;
			}
465 466
		});
	}
B
Benjamin Pasero 已提交
467 468 469 470 471 472 473 474

	private setVisibility(toast: INotificationToast, visible: boolean): void {
		toast.container.style.display = visible ? 'block' : 'none';
	}

	private isVisible(toast: INotificationToast): boolean {
		return toast.container.style.display === 'block';
	}
475
}