notificationsToasts.ts 12.5 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 } from 'vs/base/browser/dom';
12 13 14 15 16 17 18 19
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';
import { Themable } from 'vs/workbench/common/theme';
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 29 30

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

export class NotificationsToasts extends Themable {

B
Benjamin Pasero 已提交
37
	private static MAX_DIMENSIONS = new Dimension(450, 300);
38

39 40 41 42 43 44 45 46 47
	private static PURGE_TIMEOUT: { [severity: number]: number } = (() => {
		const intervals = Object.create(null);
		intervals[Severity.Info] = 8000;
		intervals[Severity.Warning] = 12000;
		intervals[Severity.Error] = 15000;

		return intervals;
	})();

48 49 50 51
	private notificationsToastsContainer: HTMLElement;
	private workbenchDimensions: Dimension;
	private isNotificationsCenterVisible: boolean;
	private mapNotificationToToast: Map<INotificationViewItem, INotificationToast>;
52
	private notificationsToastsVisibleContextKey: IContextKey<boolean>;
53 54 55 56 57 58

	constructor(
		private container: HTMLElement,
		private model: INotificationsModel,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IPartService private partService: IPartService,
59
		@IThemeService themeService: IThemeService,
60
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
B
Benjamin Pasero 已提交
61 62
		@IContextKeyService contextKeyService: IContextKeyService,
		@ILifecycleService private lifecycleService: ILifecycleService
63 64 65 66
	) {
		super(themeService);

		this.mapNotificationToToast = new Map<INotificationViewItem, INotificationToast>();
67
		this.notificationsToastsVisibleContextKey = NotificationsToastsVisibleContext.bindTo(contextKeyService);
68 69 70 71 72 73 74 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

		// 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');
108
		addClass(notificationToastContainer, 'notification-toast-container');
109
		this.notificationsToastsContainer.appendChild(notificationToastContainer);
110
		itemDisposeables.push(toDisposable(() => this.notificationsToastsContainer.removeChild(notificationToastContainer)));
111

112 113 114 115 116
		// Toast
		const notificationToast = document.createElement('div');
		addClass(notificationToast, 'notification-toast');
		notificationToastContainer.appendChild(notificationToast);

117
		// Create toast with item and show
118
		const notificationList = this.instantiationService.createInstance(NotificationsList, notificationToast, {
119 120 121
			ariaLabel: localize('notificationsToast', "Notification Toast"),
			verticalScrollMode: ScrollbarVisibility.Hidden
		});
122
		itemDisposeables.push(notificationList);
123
		this.mapNotificationToToast.set(item, { list: notificationList, container: notificationToastContainer, toast: notificationToast, disposeables: itemDisposeables });
124 125 126 127

		// Make visible
		notificationList.show();

128 129 130
		// Layout lists
		const maxDimensions = this.computeMaxDimensions();
		this.layoutLists(maxDimensions.width);
131 132 133 134

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

135 136 137 138
		// 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);

139 140
		// Update when item height changes due to expansion
		itemDisposeables.push(item.onDidExpansionChange(() => {
141 142 143
			notificationList.updateNotificationsList(0, 1, [item]);
		}));

144 145 146 147 148 149 150
		// 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]);
			}
		}));

151 152 153 154 155
		// Remove when item gets disposed
		once(item.onDidDispose)(() => {
			this.removeToast(item);
		});

B
Benjamin Pasero 已提交
156 157
		// Automatically hide collapsed notifications
		if (!item.expanded) {
158 159 160
			let timeoutHandle: number;
			const hideAfterTimeout = () => {
				timeoutHandle = setTimeout(() => {
B
Benjamin Pasero 已提交
161 162
					if (!notificationList.hasFocus() && !item.expanded) {
						this.removeToast(item);
163
					} else {
B
Benjamin Pasero 已提交
164
						hideAfterTimeout(); // push out disposal if item has focus or is expanded
165 166 167 168 169
					}
				}, NotificationsToasts.PURGE_TIMEOUT[item.severity]);
			};

			hideAfterTimeout();
170 171 172 173

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

174 175
		// Theming
		this.updateStyles();
176 177 178

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

B
Benjamin Pasero 已提交
180 181
		// Animate In if we are in a running session (otherwise just show directly)
		if (this.lifecycleService.phase >= LifecyclePhase.Running) {
182 183 184 185
			addClass(notificationToast, 'notification-fade-in');
			itemDisposeables.push(addDisposableListener(notificationToast, 'transitionend', () => {
				removeClass(notificationToast, 'notification-fade-in');
				addClass(notificationToast, 'notification-fade-in-done');
B
Benjamin Pasero 已提交
186 187
			}));
		} else {
188
			addClass(notificationToast, 'notification-fade-in-done');
B
Benjamin Pasero 已提交
189
		}
190 191 192 193
	}

	private removeToast(item: INotificationViewItem): void {
		const notificationToast = this.mapNotificationToToast.get(item);
194
		let focusEditor = false;
195
		if (notificationToast) {
196 197 198 199
			const toastHasDOMFocus = isAncestor(document.activeElement, notificationToast.container);
			if (toastHasDOMFocus) {
				focusEditor = !(this.focusNext() || this.focusPrevious()); // focus next if any, otherwise focus editor
			}
200 201 202 203 204 205 206 207

			// Listeners
			dispose(notificationToast.disposeables);

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

208 209 210
		// Layout if we still have toasts
		if (this.mapNotificationToToast.size > 0) {
			this.layout(this.workbenchDimensions);
211 212
		}

213 214 215
		// Otherwise hide if no more toasts to show
		else {
			this.doHide();
216

217 218 219
			// Move focus to editor as needed
			if (focusEditor) {
				this.focusEditor();
220 221
			}
		}
222 223
	}

224 225 226 227 228 229 230
	private focusEditor(): void {
		const editor = this.editorService.getActiveEditor();
		if (editor) {
			editor.focus();
		}
	}

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

235 236 237 238
		this.doHide();
	}

	private doHide(): void {
239
		removeClass(this.notificationsToastsContainer, 'visible');
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301

		// 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 {
		const toasts = this.getVisibleToasts();
		if (toasts.length > 0) {
			toasts[0].list.focusFirst();

			return true;
		}

		return false;
	}

	public focusNext(): boolean {
		const toasts = this.getVisibleToasts();
		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 {
		const toasts = this.getVisibleToasts();
		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;
302 303 304 305 306 307 308 309 310 311 312 313 314 315
	}

	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 {
316
		this.mapNotificationToToast.forEach(t => {
317
			const widgetShadowColor = this.getColor(widgetShadow);
318
			t.toast.style.boxShadow = widgetShadowColor ? `0 0px 8px ${widgetShadowColor}` : null;
319 320 321
		});
	}

322 323 324 325 326 327 328 329
	private getVisibleToasts(): INotificationToast[] {
		let notificationToasts: INotificationToast[] = [];
		this.mapNotificationToToast.forEach(toast => notificationToasts.push(toast));
		notificationToasts = notificationToasts.reverse(); // from newest to oldest

		return notificationToasts;
	}

330 331 332
	public layout(dimension: Dimension): void {
		this.workbenchDimensions = dimension;

333 334 335 336 337 338 339 340 341 342
		const maxDimensions = this.computeMaxDimensions();

		// Layout all lists of toasts
		this.layoutLists(maxDimensions.width);

		// Hide toasts that exceed height
		this.layoutContainer(maxDimensions.height);
	}

	private computeMaxDimensions(): Dimension {
343 344 345 346 347 348 349 350 351 352
		let maxWidth = NotificationsToasts.MAX_DIMENSIONS.width;
		let maxHeight = NotificationsToasts.MAX_DIMENSIONS.height;

		let availableWidth = maxWidth;
		let availableHeight = maxHeight;

		if (this.workbenchDimensions) {

			// Make sure notifications are not exceding available width
			availableWidth = this.workbenchDimensions.width;
B
Benjamin Pasero 已提交
353
			availableWidth -= (2 * 8); // adjust for paddings left and right
354 355 356 357 358 359 360 361 362 363 364 365 366 367

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

368 369
		return new Dimension(Math.min(maxWidth, availableWidth), Math.min(maxHeight, availableHeight));
	}
370

371 372 373 374 375
	private layoutLists(width: number): void {
		this.mapNotificationToToast.forEach(toast => toast.list.layout(width));
	}

	private layoutContainer(heightToGive: number): void {
376
		this.getVisibleToasts().forEach(toast => {
377 378 379 380 381 382 383 384 385 386 387 388 389

			// In order to measure the client height, the element cannot have display: none
			toast.container.style.opacity = '0';
			toast.container.style.display = 'block';

			heightToGive -= toast.container.clientHeight;

			// Hide or show toast based on available height
			toast.container.style.display = heightToGive >= 0 ? 'block' : 'none';
			toast.container.style.opacity = null;
		});
	}
}