notificationsToasts.ts 16.1 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 85 86 87 88 89 90 91 92

		// Wait for the running phase to ensure we can draw notifications properly
		this.lifecycleService.when(LifecyclePhase.Running).then(() => {

			// 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 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
	}

	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');
127
		addClass(notificationToastContainer, 'notification-toast-container');
128 129 130 131 132 133 134 135

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

136 137 138 139 140
		// Toast
		const notificationToast = document.createElement('div');
		addClass(notificationToast, 'notification-toast');
		notificationToastContainer.appendChild(notificationToast);

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

		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);
			}
		}));
156 157 158 159

		// Make visible
		notificationList.show();

160 161 162
		// Layout lists
		const maxDimensions = this.computeMaxDimensions();
		this.layoutLists(maxDimensions.width);
163 164 165 166

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

167 168 169 170
		// 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);

171 172
		// Update when item height changes due to expansion
		itemDisposeables.push(item.onDidExpansionChange(() => {
173 174 175
			notificationList.updateNotificationsList(0, 1, [item]);
		}));

176 177 178 179 180 181 182
		// 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]);
			}
		}));

183 184
		// Remove when item gets closed
		once(item.onDidClose)(() => {
185 186 187
			this.removeToast(item);
		});

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

191 192
		// Theming
		this.updateStyles();
193 194 195

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

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

B
Benjamin Pasero 已提交
205 206 207 208 209 210 211
	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));

212
		// Install Timers to Purge Notification
213
		let purgeTimeoutHandle: any;
214 215
		let listener: IDisposable;

B
Benjamin Pasero 已提交
216
		const hideAfterTimeout = () => {
217

218
			purgeTimeoutHandle = setTimeout(() => {
219 220 221 222 223 224 225

				// 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) {
226 227 228 229 230 231 232 233
					if (!listener) {
						listener = this.windowService.onDidChangeFocus(focus => {
							if (focus) {
								hideAfterTimeout();
							}
						});
						disposables.push(listener);
					}
234 235 236
				}

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

		hideAfterTimeout();

251
		disposables.push(toDisposable(() => clearTimeout(purgeTimeoutHandle)));
B
Benjamin Pasero 已提交
252 253
	}

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

			// Listeners
			dispose(notificationToast.disposeables);

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

270 271 272
		// Layout if we still have toasts
		if (this.mapNotificationToToast.size > 0) {
			this.layout(this.workbenchDimensions);
273 274
		}

275 276 277
		// Otherwise hide if no more toasts to show
		else {
			this.doHide();
278

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

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

290 291 292 293
		this.doHide();
	}

	private doHide(): void {
294 295 296
		if (this.notificationsToastsContainer) {
			removeClass(this.notificationsToastsContainer, 'visible');
		}
297 298 299 300 301

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

B
Benjamin Pasero 已提交
302
	hide(): void {
B
Benjamin Pasero 已提交
303
		const focusGroup = isAncestor(document.activeElement, this.notificationsToastsContainer);
304 305 306

		this.removeToasts();

B
Benjamin Pasero 已提交
307 308
		if (focusGroup) {
			this.editorGroupService.activeGroup.focus();
309 310 311
		}
	}

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

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
323
	focusNext(): boolean {
B
Benjamin Pasero 已提交
324
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
		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 已提交
342
	focusPrevious(): boolean {
B
Benjamin Pasero 已提交
343
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
		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;
359 360
	}

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

			return true;
		}

		return false;
	}

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

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
383
	update(isCenterVisible: boolean): void {
384 385 386 387 388 389 390 391 392 393 394
		if (this.isNotificationsCenterVisible !== isCenterVisible) {
			this.isNotificationsCenterVisible = isCenterVisible;

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

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

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

B
Benjamin Pasero 已提交
404 405
	private getToasts(state: ToastVisibility): INotificationToast[] {
		const notificationToasts: INotificationToast[] = [];
B
Benjamin Pasero 已提交
406 407

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

B
Benjamin Pasero 已提交
425
		return notificationToasts.reverse(); // from newest to oldest
426 427
	}

B
Benjamin Pasero 已提交
428
	layout(dimension: Dimension): void {
429 430
		this.workbenchDimensions = dimension;

431 432 433
		const maxDimensions = this.computeMaxDimensions();

		// Hide toasts that exceed height
434 435 436
		if (maxDimensions.height) {
			this.layoutContainer(maxDimensions.height);
		}
437 438 439

		// Layout all lists of toasts
		this.layoutLists(maxDimensions.width);
440 441 442
	}

	private computeMaxDimensions(): Dimension {
443
		let maxWidth = NotificationsToasts.MAX_WIDTH;
444 445

		let availableWidth = maxWidth;
446
		let availableHeight: number;
447 448 449 450 451

		if (this.workbenchDimensions) {

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

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

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

469
		return new Dimension(Math.min(maxWidth, availableWidth), availableHeight);
470
	}
471

472 473 474 475 476
	private layoutLists(width: number): void {
		this.mapNotificationToToast.forEach(toast => toast.list.layout(width));
	}

	private layoutContainer(heightToGive: number): void {
B
Benjamin Pasero 已提交
477 478
		let visibleToasts = 0;
		this.getToasts(ToastVisibility.HIDDEN_OR_VISIBLE).forEach(toast => {
479 480 481

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

484
			heightToGive -= toast.container.offsetHeight;
485

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

			if (makeVisible) {
				visibleToasts++;
			}
500 501
		});
	}
B
Benjamin Pasero 已提交
502 503

	private setVisibility(toast: INotificationToast, visible: boolean): void {
504 505 506 507 508 509 510 511 512
		if (this.isVisible(toast) === visible) {
			return;
		}

		if (visible) {
			this.notificationsToastsContainer.appendChild(toast.container);
		} else {
			this.notificationsToastsContainer.removeChild(toast.container);
		}
B
Benjamin Pasero 已提交
513 514 515
	}

	private isVisible(toast: INotificationToast): boolean {
516
		return !!toast.container.parentElement;
B
Benjamin Pasero 已提交
517
	}
518
}