notificationsToasts.ts 15.0 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';
11
import { addClass, removeClass, isAncestor, addDisposableListener, EventType, Dimension } from 'vs/base/browser/dom';
12 13 14 15
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';
16
import { Themable, NOTIFICATIONS_TOAST_BORDER } from 'vs/workbench/common/theme';
17 18
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { widgetShadow } from 'vs/platform/theme/common/colorRegistry';
19
import { INextEditorGroupsService } from 'vs/workbench/services/group/common/editorGroupsService';
20
import { NotificationsToastsVisibleContext } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
21
import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey';
22
import { localize } from 'vs/nls';
23
import { Severity } from 'vs/platform/notification/common/notification';
24
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
B
Benjamin Pasero 已提交
25
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
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
		intervals[Severity.Info] = 10000;
		intervals[Severity.Warning] = 12000;
50 51 52 53 54
		intervals[Severity.Error] = 15000;

		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 64 65

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

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

		// 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');
115
		addClass(notificationToastContainer, 'notification-toast-container');
116 117 118 119 120 121 122 123

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

124 125 126 127 128
		// Toast
		const notificationToast = document.createElement('div');
		addClass(notificationToast, 'notification-toast');
		notificationToastContainer.appendChild(notificationToast);

129
		// Create toast with item and show
130
		const notificationList = this.instantiationService.createInstance(NotificationsList, notificationToast, {
131 132 133
			ariaLabel: localize('notificationsToast', "Notification Toast"),
			verticalScrollMode: ScrollbarVisibility.Hidden
		});
134
		itemDisposeables.push(notificationList);
B
Benjamin Pasero 已提交
135 136 137 138 139 140 141 142 143

		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);
			}
		}));
144 145 146 147

		// Make visible
		notificationList.show();

148 149 150
		// Layout lists
		const maxDimensions = this.computeMaxDimensions();
		this.layoutLists(maxDimensions.width);
151 152 153 154

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

155 156 157 158
		// 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);

159 160
		// Update when item height changes due to expansion
		itemDisposeables.push(item.onDidExpansionChange(() => {
161 162 163
			notificationList.updateNotificationsList(0, 1, [item]);
		}));

164 165 166 167 168 169 170
		// 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]);
			}
		}));

171 172
		// Remove when item gets closed
		once(item.onDidClose)(() => {
173 174 175
			this.removeToast(item);
		});

B
Benjamin Pasero 已提交
176 177
		// Automatically hide collapsed notifications
		if (!item.expanded) {
B
Benjamin Pasero 已提交
178 179 180 181 182 183 184

			// 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
185 186 187
			let timeoutHandle: number;
			const hideAfterTimeout = () => {
				timeoutHandle = setTimeout(() => {
B
Benjamin Pasero 已提交
188 189
					const showsProgress = item.progress && !item.progress.state.done;
					if (!notificationList.hasFocus() && !item.expanded && !isMouseOverToast && !showsProgress) {
B
Benjamin Pasero 已提交
190
						this.removeToast(item);
191
					} else {
B
Benjamin Pasero 已提交
192
						hideAfterTimeout(); // push out disposal if item has focus or is expanded
193 194 195 196 197
					}
				}, NotificationsToasts.PURGE_TIMEOUT[item.severity]);
			};

			hideAfterTimeout();
198 199 200 201

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

202 203
		// Theming
		this.updateStyles();
204 205 206

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

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

	private removeToast(item: INotificationViewItem): void {
		const notificationToast = this.mapNotificationToToast.get(item);
B
Benjamin Pasero 已提交
222
		let focusGroup = false;
223
		if (notificationToast) {
224 225
			const toastHasDOMFocus = isAncestor(document.activeElement, notificationToast.container);
			if (toastHasDOMFocus) {
B
Benjamin Pasero 已提交
226
				focusGroup = !(this.focusNext() || this.focusPrevious()); // focus next if any, otherwise focus editor
227
			}
228 229 230 231 232 233 234 235

			// Listeners
			dispose(notificationToast.disposeables);

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

236 237 238
		// Layout if we still have toasts
		if (this.mapNotificationToToast.size > 0) {
			this.layout(this.workbenchDimensions);
239 240
		}

241 242 243
		// Otherwise hide if no more toasts to show
		else {
			this.doHide();
244

B
Benjamin Pasero 已提交
245 246 247
			// Move focus back to editor group as needed
			if (focusGroup) {
				this.editorGroupService.activeGroup.focus();
248 249
			}
		}
250 251 252 253 254 255
	}

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

256 257 258 259
		this.doHide();
	}

	private doHide(): void {
260 261 262
		if (this.notificationsToastsContainer) {
			removeClass(this.notificationsToastsContainer, 'visible');
		}
263 264 265 266 267 268

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

	public hide(): void {
B
Benjamin Pasero 已提交
269
		const focusGroup = isAncestor(document.activeElement, this.notificationsToastsContainer);
270 271 272

		this.removeToasts();

B
Benjamin Pasero 已提交
273 274
		if (focusGroup) {
			this.editorGroupService.activeGroup.focus();
275 276 277 278
		}
	}

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

			return true;
		}

		return false;
	}

	public focusNext(): boolean {
B
Benjamin Pasero 已提交
290
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
		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 已提交
309
		const toasts = this.getToasts(ToastVisibility.VISIBLE);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
		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;
325 326
	}

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

			return true;
		}

		return false;
	}

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

			return true;
		}

		return false;
	}

349 350 351 352 353 354 355 356 357 358 359 360
	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 {
361
		this.mapNotificationToToast.forEach(t => {
362
			const widgetShadowColor = this.getColor(widgetShadow);
363
			t.toast.style.boxShadow = widgetShadowColor ? `0 0px 8px ${widgetShadowColor}` : null;
364 365 366

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

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

		this.mapNotificationToToast.forEach(toast => {
B
Benjamin Pasero 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387
			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 已提交
388 389 390
			}
		});

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

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

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

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

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

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

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

		if (this.workbenchDimensions) {

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

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

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

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

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

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

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

450
			heightToGive -= toast.container.offsetHeight;
451

B
Benjamin Pasero 已提交
452 453 454 455 456 457 458 459 460
			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);
461
			toast.container.style.opacity = null;
B
Benjamin Pasero 已提交
462 463 464 465

			if (makeVisible) {
				visibleToasts++;
			}
466 467
		});
	}
B
Benjamin Pasero 已提交
468 469

	private setVisibility(toast: INotificationToast, visible: boolean): void {
470 471 472 473 474 475 476 477 478
		if (this.isVisible(toast) === visible) {
			return;
		}

		if (visible) {
			this.notificationsToastsContainer.appendChild(toast.container);
		} else {
			this.notificationsToastsContainer.removeChild(toast.container);
		}
B
Benjamin Pasero 已提交
479 480 481
	}

	private isVisible(toast: INotificationToast): boolean {
482
		return !!toast.container.parentElement;
B
Benjamin Pasero 已提交
483
	}
484
}