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

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

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

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

40 41
export class NotificationsToasts extends Themable {

42
	private static MAX_WIDTH = 450;
43
	private static MAX_NOTIFICATIONS = 3;
44

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

		return intervals;
	})();

54 55
	private notificationsToastsContainer: HTMLElement;
	private workbenchDimensions: Dimension;
B
Benjamin Pasero 已提交
56
	private windowHasFocus: boolean;
57 58
	private isNotificationsCenterVisible: boolean;
	private mapNotificationToToast: Map<INotificationViewItem, INotificationToast>;
59
	private notificationsToastsVisibleContextKey: IContextKey<boolean>;
60 61 62 63 64 65

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

		this.mapNotificationToToast = new Map<INotificationViewItem, INotificationToast>();
75
		this.notificationsToastsVisibleContextKey = NotificationsToastsVisibleContext.bindTo(contextKeyService);
76

B
Benjamin Pasero 已提交
77 78
		this.windowService.isFocused().then(isFocused => this.windowHasFocus = isFocused);

79 80 81 82
		this.registerListeners();
	}

	private registerListeners(): void {
B
Benjamin Pasero 已提交
83 84

		// Wait for the running phase to ensure we can draw notifications properly
B
Benjamin Pasero 已提交
85
		this.lifecycleService.when(LifecyclePhase.Ready).then(() => {
B
Benjamin Pasero 已提交
86 87 88 89 90 91 92

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

			// Update toasts on notification changes
			this._register(this.model.onDidNotificationChange(e => this.onDidNotificationChange(e)));
		});
B
Benjamin Pasero 已提交
93 94 95

		// Track window focus
		this.windowService.onDidChangeFocus(hasFocus => this.windowHasFocus = hasFocus);
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	}

	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
		}

112 113 114 115
		if (item.silent) {
			return; // do not show toats for silenced notifications
		}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
		// 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');
131
		addClass(notificationToastContainer, 'notification-toast-container');
132 133 134 135 136 137 138 139

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

140 141 142 143 144
		// Toast
		const notificationToast = document.createElement('div');
		addClass(notificationToast, 'notification-toast');
		notificationToastContainer.appendChild(notificationToast);

145
		// Create toast with item and show
146
		const notificationList = this.instantiationService.createInstance(NotificationsList, notificationToast, {
147 148 149
			ariaLabel: localize('notificationsToast', "Notification Toast"),
			verticalScrollMode: ScrollbarVisibility.Hidden
		});
150
		itemDisposeables.push(notificationList);
B
Benjamin Pasero 已提交
151 152 153 154 155 156 157 158 159

		const toast: INotificationToast = { item, list: notificationList, container: notificationToastContainer, toast: notificationToast, disposeables: itemDisposeables };
		this.mapNotificationToToast.set(item, toast);

		itemDisposeables.push(toDisposable(() => {
			if (this.isVisible(toast)) {
				this.notificationsToastsContainer.removeChild(toast.container);
			}
		}));
160 161 162 163

		// Make visible
		notificationList.show();

164 165 166
		// Layout lists
		const maxDimensions = this.computeMaxDimensions();
		this.layoutLists(maxDimensions.width);
167 168 169 170

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

171 172 173 174
		// 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);

175 176
		// Update when item height changes due to expansion
		itemDisposeables.push(item.onDidExpansionChange(() => {
177 178 179
			notificationList.updateNotificationsList(0, 1, [item]);
		}));

180 181 182 183 184 185 186
		// 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]);
			}
		}));

187 188
		// Remove when item gets closed
		once(item.onDidClose)(() => {
189 190 191
			this.removeToast(item);
		});

B
Benjamin Pasero 已提交
192 193
		// Automatically purge non-sticky notifications
		this.purgeNotification(item, notificationToastContainer, notificationList, itemDisposeables);
194

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

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

B
Benjamin Pasero 已提交
201 202 203 204
		// Animate in
		addClass(notificationToast, 'notification-fade-in');
		itemDisposeables.push(addDisposableListener(notificationToast, 'transitionend', () => {
			removeClass(notificationToast, 'notification-fade-in');
205
			addClass(notificationToast, 'notification-fade-in-done');
B
Benjamin Pasero 已提交
206
		}));
207 208
	}

B
Benjamin Pasero 已提交
209 210 211 212 213 214 215
	private purgeNotification(item: INotificationViewItem, notificationToastContainer: HTMLElement, notificationList: NotificationsList, disposables: IDisposable[]): void {

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

216
		// Install Timers to Purge Notification
217
		let purgeTimeoutHandle: any;
218 219
		let listener: IDisposable;

B
Benjamin Pasero 已提交
220
		const hideAfterTimeout = () => {
221

222
			purgeTimeoutHandle = setTimeout(() => {
223 224 225 226 227 228 229

				// If the notification is sticky or prompting and the window does not have
				// focus, we wait for the window to gain focus again before triggering
				// the timeout again. This prevents an issue where focussing the window
				// could immediately hide the notification because the timeout was triggered
				// again.
				if ((item.sticky || item.hasPrompt()) && !this.windowHasFocus) {
230 231 232 233 234 235 236 237
					if (!listener) {
						listener = this.windowService.onDidChangeFocus(focus => {
							if (focus) {
								hideAfterTimeout();
							}
						});
						disposables.push(listener);
					}
238 239 240
				}

				// Otherwise...
B
Benjamin Pasero 已提交
241
				else if (
242 243
					item.sticky ||								// never hide sticky notifications
					notificationList.hasFocus() ||				// never hide notifications with focus
244
					isMouseOverToast							// never hide notifications under mouse
B
Benjamin Pasero 已提交
245
				) {
246
					hideAfterTimeout();
B
Benjamin Pasero 已提交
247 248 249 250 251 252 253 254
				} else {
					this.removeToast(item);
				}
			}, NotificationsToasts.PURGE_TIMEOUT[item.severity]);
		};

		hideAfterTimeout();

255
		disposables.push(toDisposable(() => clearTimeout(purgeTimeoutHandle)));
B
Benjamin Pasero 已提交
256 257
	}

258 259
	private removeToast(item: INotificationViewItem): void {
		const notificationToast = this.mapNotificationToToast.get(item);
B
Benjamin Pasero 已提交
260
		let focusGroup = false;
261
		if (notificationToast) {
262 263
			const toastHasDOMFocus = isAncestor(document.activeElement, notificationToast.container);
			if (toastHasDOMFocus) {
B
Benjamin Pasero 已提交
264
				focusGroup = !(this.focusNext() || this.focusPrevious()); // focus next if any, otherwise focus editor
265
			}
266 267 268 269 270 271 272 273

			// Listeners
			dispose(notificationToast.disposeables);

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

274 275 276
		// Layout if we still have toasts
		if (this.mapNotificationToToast.size > 0) {
			this.layout(this.workbenchDimensions);
277 278
		}

279 280 281
		// Otherwise hide if no more toasts to show
		else {
			this.doHide();
282

B
Benjamin Pasero 已提交
283 284 285
			// Move focus back to editor group as needed
			if (focusGroup) {
				this.editorGroupService.activeGroup.focus();
286 287
			}
		}
288 289 290 291 292 293
	}

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

294 295 296 297
		this.doHide();
	}

	private doHide(): void {
298 299 300
		if (this.notificationsToastsContainer) {
			removeClass(this.notificationsToastsContainer, 'visible');
		}
301 302 303 304 305

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

B
Benjamin Pasero 已提交
306
	hide(): void {
B
Benjamin Pasero 已提交
307
		const focusGroup = isAncestor(document.activeElement, this.notificationsToastsContainer);
308 309 310

		this.removeToasts();

B
Benjamin Pasero 已提交
311 312
		if (focusGroup) {
			this.editorGroupService.activeGroup.focus();
313 314 315
		}
	}

B
Benjamin Pasero 已提交
316
	focus(): boolean {
B
Benjamin Pasero 已提交
317
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
318 319 320 321 322 323 324 325 326
		if (toasts.length > 0) {
			toasts[0].list.focusFirst();

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
327
	focusNext(): boolean {
B
Benjamin Pasero 已提交
328
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
		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;
	}

B
Benjamin Pasero 已提交
346
	focusPrevious(): boolean {
B
Benjamin Pasero 已提交
347
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
		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;
363 364
	}

B
Benjamin Pasero 已提交
365
	focusFirst(): boolean {
B
Benjamin Pasero 已提交
366
		const toast = this.getToasts(ToastVisibility.VISIBLE)[0];
B
Benjamin Pasero 已提交
367 368 369 370 371 372 373 374 375
		if (toast) {
			toast.list.focusFirst();

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
376
	focusLast(): boolean {
B
Benjamin Pasero 已提交
377
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
B
Benjamin Pasero 已提交
378 379 380 381 382 383 384 385 386
		if (toasts.length > 0) {
			toasts[toasts.length - 1].list.focusFirst();

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
387
	update(isCenterVisible: boolean): void {
388 389 390 391 392 393 394 395 396 397 398
		if (this.isNotificationsCenterVisible !== isCenterVisible) {
			this.isNotificationsCenterVisible = isCenterVisible;

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

	protected updateStyles(): void {
399
		this.mapNotificationToToast.forEach(t => {
400
			const widgetShadowColor = this.getColor(widgetShadow);
401
			t.toast.style.boxShadow = widgetShadowColor ? `0 0px 8px ${widgetShadowColor}` : null;
402 403 404

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

B
Benjamin Pasero 已提交
408 409
	private getToasts(state: ToastVisibility): INotificationToast[] {
		const notificationToasts: INotificationToast[] = [];
B
Benjamin Pasero 已提交
410 411

		this.mapNotificationToToast.forEach(toast => {
B
Benjamin Pasero 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425
			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 已提交
426 427 428
			}
		});

B
Benjamin Pasero 已提交
429
		return notificationToasts.reverse(); // from newest to oldest
430 431
	}

B
Benjamin Pasero 已提交
432
	layout(dimension: Dimension): void {
433 434
		this.workbenchDimensions = dimension;

435 436 437
		const maxDimensions = this.computeMaxDimensions();

		// Hide toasts that exceed height
438 439 440
		if (maxDimensions.height) {
			this.layoutContainer(maxDimensions.height);
		}
441 442 443

		// Layout all lists of toasts
		this.layoutLists(maxDimensions.width);
444 445 446
	}

	private computeMaxDimensions(): Dimension {
447
		let maxWidth = NotificationsToasts.MAX_WIDTH;
448 449

		let availableWidth = maxWidth;
450
		let availableHeight: number;
451 452 453 454 455

		if (this.workbenchDimensions) {

			// Make sure notifications are not exceding available width
			availableWidth = this.workbenchDimensions.width;
B
Benjamin Pasero 已提交
456
			availableWidth -= (2 * 8); // adjust for paddings left and right
457 458 459 460 461 462 463 464 465 466 467 468 469 470

			// 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
		}

471 472
		availableHeight = Math.round(availableHeight * 0.618); // try to not cover the full height for stacked toasts

473
		return new Dimension(Math.min(maxWidth, availableWidth), availableHeight);
474
	}
475

476 477 478 479 480
	private layoutLists(width: number): void {
		this.mapNotificationToToast.forEach(toast => toast.list.layout(width));
	}

	private layoutContainer(heightToGive: number): void {
B
Benjamin Pasero 已提交
481 482
		let visibleToasts = 0;
		this.getToasts(ToastVisibility.HIDDEN_OR_VISIBLE).forEach(toast => {
483 484 485

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

488
			heightToGive -= toast.container.offsetHeight;
489

B
Benjamin Pasero 已提交
490 491 492 493 494 495 496 497 498
			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);
499
			toast.container.style.opacity = null;
B
Benjamin Pasero 已提交
500 501 502 503

			if (makeVisible) {
				visibleToasts++;
			}
504 505
		});
	}
B
Benjamin Pasero 已提交
506 507

	private setVisibility(toast: INotificationToast, visible: boolean): void {
508 509 510 511 512 513 514 515 516
		if (this.isVisible(toast) === visible) {
			return;
		}

		if (visible) {
			this.notificationsToastsContainer.appendChild(toast.container);
		} else {
			this.notificationsToastsContainer.removeChild(toast.container);
		}
B
Benjamin Pasero 已提交
517 518 519
	}

	private isVisible(toast: INotificationToast): boolean {
520
		return !!toast.container.parentElement;
B
Benjamin Pasero 已提交
521
	}
522
}