notificationsToasts.ts 16.5 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
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { NotificationsList } from 'vs/workbench/browser/parts/notifications/notificationsList';
J
Joao Moreno 已提交
12
import { Event } from 'vs/base/common/event';
13
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
import { timeout } from 'vs/base/common/async';
26 27

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

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

41 42
export class NotificationsToasts extends Themable {

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

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

		return intervals;
	})();

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

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

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

		this.registerListeners();
	}

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

82 83
		// Delay some tasks until after we can show notifications
		this.onCanShowNotifications().then(() => {
B
Benjamin Pasero 已提交
84 85 86 87 88 89 90

			// 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)));
		});
91 92
	}

J
Johannes Rieken 已提交
93
	private onCanShowNotifications(): Promise<void> {
94 95 96 97 98 99 100 101 102 103 104 105 106

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

			// Push notificiations out until either workbench is restored
			// or some time has ellapsed to reduce pressure on the startup
			return Promise.race([
				this.lifecycleService.when(LifecyclePhase.Restored),
				timeout(2000)
			]);
		});
	}

107 108 109 110 111 112 113 114 115 116 117 118 119 120
	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
		}

121 122 123 124
		if (item.silent) {
			return; // do not show toats for silenced notifications
		}

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
		// 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');
140
		addClass(notificationToastContainer, 'notification-toast-container');
141 142 143 144 145 146 147 148

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

149 150 151 152 153
		// Toast
		const notificationToast = document.createElement('div');
		addClass(notificationToast, 'notification-toast');
		notificationToastContainer.appendChild(notificationToast);

154
		// Create toast with item and show
155
		const notificationList = this.instantiationService.createInstance(NotificationsList, notificationToast, {
156 157 158
			ariaLabel: localize('notificationsToast', "Notification Toast"),
			verticalScrollMode: ScrollbarVisibility.Hidden
		});
159
		itemDisposeables.push(notificationList);
B
Benjamin Pasero 已提交
160 161 162 163 164 165 166 167 168

		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);
			}
		}));
169 170 171 172

		// Make visible
		notificationList.show();

173 174 175
		// Layout lists
		const maxDimensions = this.computeMaxDimensions();
		this.layoutLists(maxDimensions.width);
176 177 178 179

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

180 181 182 183
		// 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);

184 185
		// Update when item height changes due to expansion
		itemDisposeables.push(item.onDidExpansionChange(() => {
186 187 188
			notificationList.updateNotificationsList(0, 1, [item]);
		}));

189 190 191 192 193 194 195
		// 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]);
			}
		}));

196
		// Remove when item gets closed
J
Joao Moreno 已提交
197
		Event.once(item.onDidClose)(() => {
198 199 200
			this.removeToast(item);
		});

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

204 205
		// Theming
		this.updateStyles();
206 207 208

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

B
Benjamin Pasero 已提交
210 211 212 213
		// Animate in
		addClass(notificationToast, 'notification-fade-in');
		itemDisposeables.push(addDisposableListener(notificationToast, 'transitionend', () => {
			removeClass(notificationToast, 'notification-fade-in');
214
			addClass(notificationToast, 'notification-fade-in-done');
B
Benjamin Pasero 已提交
215
		}));
216 217
	}

B
Benjamin Pasero 已提交
218 219 220 221 222 223 224
	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));

225
		// Install Timers to Purge Notification
226
		let purgeTimeoutHandle: any;
227 228
		let listener: IDisposable;

B
Benjamin Pasero 已提交
229
		const hideAfterTimeout = () => {
230

231
			purgeTimeoutHandle = setTimeout(() => {
232 233 234 235 236 237

				// 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.
238
				if ((item.sticky || item.hasPrompt()) && !this.windowService.hasFocus) {
239 240 241 242 243 244 245 246
					if (!listener) {
						listener = this.windowService.onDidChangeFocus(focus => {
							if (focus) {
								hideAfterTimeout();
							}
						});
						disposables.push(listener);
					}
247 248 249
				}

				// Otherwise...
B
Benjamin Pasero 已提交
250
				else if (
251 252
					item.sticky ||								// never hide sticky notifications
					notificationList.hasFocus() ||				// never hide notifications with focus
253
					isMouseOverToast							// never hide notifications under mouse
B
Benjamin Pasero 已提交
254
				) {
255
					hideAfterTimeout();
B
Benjamin Pasero 已提交
256 257 258 259 260 261 262 263
				} else {
					this.removeToast(item);
				}
			}, NotificationsToasts.PURGE_TIMEOUT[item.severity]);
		};

		hideAfterTimeout();

264
		disposables.push(toDisposable(() => clearTimeout(purgeTimeoutHandle)));
B
Benjamin Pasero 已提交
265 266
	}

267 268
	private removeToast(item: INotificationViewItem): void {
		const notificationToast = this.mapNotificationToToast.get(item);
B
Benjamin Pasero 已提交
269
		let focusGroup = false;
270
		if (notificationToast) {
271 272
			const toastHasDOMFocus = isAncestor(document.activeElement, notificationToast.container);
			if (toastHasDOMFocus) {
B
Benjamin Pasero 已提交
273
				focusGroup = !(this.focusNext() || this.focusPrevious()); // focus next if any, otherwise focus editor
274
			}
275 276 277 278 279 280 281 282

			// Listeners
			dispose(notificationToast.disposeables);

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

283 284 285
		// Layout if we still have toasts
		if (this.mapNotificationToToast.size > 0) {
			this.layout(this.workbenchDimensions);
286 287
		}

288 289 290
		// Otherwise hide if no more toasts to show
		else {
			this.doHide();
291

B
Benjamin Pasero 已提交
292 293 294
			// Move focus back to editor group as needed
			if (focusGroup) {
				this.editorGroupService.activeGroup.focus();
295 296
			}
		}
297 298 299 300 301 302
	}

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

303 304 305 306
		this.doHide();
	}

	private doHide(): void {
307 308 309
		if (this.notificationsToastsContainer) {
			removeClass(this.notificationsToastsContainer, 'visible');
		}
310 311 312 313 314

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

B
Benjamin Pasero 已提交
315
	hide(): void {
B
Benjamin Pasero 已提交
316
		const focusGroup = isAncestor(document.activeElement, this.notificationsToastsContainer);
317 318 319

		this.removeToasts();

B
Benjamin Pasero 已提交
320 321
		if (focusGroup) {
			this.editorGroupService.activeGroup.focus();
322 323 324
		}
	}

B
Benjamin Pasero 已提交
325
	focus(): boolean {
B
Benjamin Pasero 已提交
326
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
327 328 329 330 331 332 333 334 335
		if (toasts.length > 0) {
			toasts[0].list.focusFirst();

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
336
	focusNext(): boolean {
B
Benjamin Pasero 已提交
337
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
		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 已提交
355
	focusPrevious(): boolean {
B
Benjamin Pasero 已提交
356
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
		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;
372 373
	}

B
Benjamin Pasero 已提交
374
	focusFirst(): boolean {
B
Benjamin Pasero 已提交
375
		const toast = this.getToasts(ToastVisibility.VISIBLE)[0];
B
Benjamin Pasero 已提交
376 377 378 379 380 381 382 383 384
		if (toast) {
			toast.list.focusFirst();

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
385
	focusLast(): boolean {
B
Benjamin Pasero 已提交
386
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
B
Benjamin Pasero 已提交
387 388 389 390 391 392 393 394 395
		if (toasts.length > 0) {
			toasts[toasts.length - 1].list.focusFirst();

			return true;
		}

		return false;
	}

B
Benjamin Pasero 已提交
396
	update(isCenterVisible: boolean): void {
397 398 399 400 401 402 403 404 405 406 407
		if (this.isNotificationsCenterVisible !== isCenterVisible) {
			this.isNotificationsCenterVisible = isCenterVisible;

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

	protected updateStyles(): void {
408
		this.mapNotificationToToast.forEach(t => {
409
			const widgetShadowColor = this.getColor(widgetShadow);
410
			t.toast.style.boxShadow = widgetShadowColor ? `0 0px 8px ${widgetShadowColor}` : null;
411 412 413

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

B
Benjamin Pasero 已提交
417 418
	private getToasts(state: ToastVisibility): INotificationToast[] {
		const notificationToasts: INotificationToast[] = [];
B
Benjamin Pasero 已提交
419 420

		this.mapNotificationToToast.forEach(toast => {
B
Benjamin Pasero 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434
			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 已提交
435 436 437
			}
		});

B
Benjamin Pasero 已提交
438
		return notificationToasts.reverse(); // from newest to oldest
439 440
	}

B
Benjamin Pasero 已提交
441
	layout(dimension: Dimension): void {
442 443
		this.workbenchDimensions = dimension;

444 445 446
		const maxDimensions = this.computeMaxDimensions();

		// Hide toasts that exceed height
447 448 449
		if (maxDimensions.height) {
			this.layoutContainer(maxDimensions.height);
		}
450 451 452

		// Layout all lists of toasts
		this.layoutLists(maxDimensions.width);
453 454 455
	}

	private computeMaxDimensions(): Dimension {
456
		let maxWidth = NotificationsToasts.MAX_WIDTH;
457 458

		let availableWidth = maxWidth;
459
		let availableHeight: number;
460 461 462 463 464

		if (this.workbenchDimensions) {

			// Make sure notifications are not exceding available width
			availableWidth = this.workbenchDimensions.width;
B
Benjamin Pasero 已提交
465
			availableWidth -= (2 * 8); // adjust for paddings left and right
466 467 468 469 470 471 472 473 474 475 476 477 478 479

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

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

482
		return new Dimension(Math.min(maxWidth, availableWidth), availableHeight);
483
	}
484

485 486 487 488 489
	private layoutLists(width: number): void {
		this.mapNotificationToToast.forEach(toast => toast.list.layout(width));
	}

	private layoutContainer(heightToGive: number): void {
B
Benjamin Pasero 已提交
490 491
		let visibleToasts = 0;
		this.getToasts(ToastVisibility.HIDDEN_OR_VISIBLE).forEach(toast => {
492 493 494

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

497
			heightToGive -= toast.container.offsetHeight;
498

B
Benjamin Pasero 已提交
499 500 501 502 503 504 505 506 507
			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);
508
			toast.container.style.opacity = null;
B
Benjamin Pasero 已提交
509 510 511 512

			if (makeVisible) {
				visibleToasts++;
			}
513 514
		});
	}
B
Benjamin Pasero 已提交
515 516

	private setVisibility(toast: INotificationToast, visible: boolean): void {
517 518 519 520 521 522 523 524 525
		if (this.isVisible(toast) === visible) {
			return;
		}

		if (visible) {
			this.notificationsToastsContainer.appendChild(toast.container);
		} else {
			this.notificationsToastsContainer.removeChild(toast.container);
		}
B
Benjamin Pasero 已提交
526 527 528
	}

	private isVisible(toast: INotificationToast): boolean {
529
		return !!toast.container.parentElement;
B
Benjamin Pasero 已提交
530
	}
531
}