compositeBar.ts 18.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*---------------------------------------------------------------------------------------------
 *  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 nls = require('vs/nls');
import { Action } from 'vs/base/common/actions';
import { illegalArgument } from 'vs/base/common/errors';
import * as dom from 'vs/base/browser/dom';
import * as arrays from 'vs/base/common/arrays';
import { Dimension } from 'vs/base/browser/builder';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
I
isidor 已提交
15
import { IBadge } from 'vs/workbench/services/activity/common/activity';
16 17 18 19
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ActionBar, IActionItem, ActionsOrientation } from 'vs/base/browser/ui/actionbar/actionbar';
import Event, { Emitter } from 'vs/base/common/event';
I
isidor 已提交
20
import { CompositeActionItem, CompositeOverflowActivityAction, ICompositeActivity, CompositeOverflowActivityActionItem, ActivityAction, ICompositeBar, ICompositeBarColors } from 'vs/workbench/browser/parts/compositebar/compositeBarActions';
21
import { TPromise } from 'vs/base/common/winjs.base';
22 23

export interface ICompositeBarOptions {
I
isidor 已提交
24
	icon: boolean;
25 26
	storageId: string;
	orientation: ActionsOrientation;
27
	composites: { id: string, name: string, order: number }[];
I
isidor 已提交
28
	colors: ICompositeBarColors;
I
isidor 已提交
29
	overflowActionSize: number;
30 31
	getActivityAction: (compositeId: string) => ActivityAction;
	getCompositePinnedAction: (compositeId: string) => Action;
32 33 34 35
	getOnCompositeClickAction: (compositeId: string) => Action;
	openComposite: (compositeId: string) => TPromise<any>;
	getDefaultCompositeId: () => string;
	hidePart: () => TPromise<any>;
36 37
}

38
export class CompositeBar implements ICompositeBar {
39 40 41 42 43 44 45 46 47 48 49 50 51

	private _onDidContextMenu: Emitter<MouseEvent>;

	private dimension: Dimension;
	private toDispose: IDisposable[];

	private compositeSwitcherBar: ActionBar;
	private compositeOverflowAction: CompositeOverflowActivityAction;
	private compositeOverflowActionItem: CompositeOverflowActivityActionItem;

	private compositeIdToActions: { [compositeId: string]: ActivityAction; };
	private compositeIdToActionItems: { [compositeId: string]: IActionItem; };
	private compositeIdToActivityStack: { [compositeId: string]: ICompositeActivity[]; };
52
	private compositeSizeInBar: Map<string, number>;
53 54 55 56 57 58 59 60 61 62 63 64 65 66

	private pinnedComposites: string[];
	private activeCompositeId: string;
	private activeUnpinnedCompositeId: string;

	constructor(
		private options: ICompositeBarOptions,
		@IInstantiationService private instantiationService: IInstantiationService,
		@IStorageService private storageService: IStorageService,
	) {
		this.toDispose = [];
		this.compositeIdToActionItems = Object.create(null);
		this.compositeIdToActions = Object.create(null);
		this.compositeIdToActivityStack = Object.create(null);
67
		this.compositeSizeInBar = new Map<string, number>();
68 69 70 71 72

		this._onDidContextMenu = new Emitter<MouseEvent>();

		const pinnedComposites = JSON.parse(this.storageService.get(this.options.storageId, StorageScope.GLOBAL, null)) as string[];
		if (pinnedComposites) {
73 74
			const compositeIds = this.options.composites.map(c => c.id);
			this.pinnedComposites = pinnedComposites.filter(pcid => compositeIds.indexOf(pcid) >= 0);
75 76 77 78 79 80 81 82 83
		} else {
			this.pinnedComposites = this.options.composites.map(c => c.id);
		}
	}

	public get onDidContextMenu(): Event<MouseEvent> {
		return this._onDidContextMenu.event;
	}

84
	public addComposite(compositeData: { id: string; name: string, order: number }): void {
85 86 87
		if (this.options.composites.filter(c => c.id === compositeData.id).length) {
			return;
		}
88 89 90 91
		let i = 0;
		while (i < this.options.composites.length && this.options.composites[i].order < compositeData.order) {
			i++;
		}
92
		this.options.composites.push(compositeData);
93
		this.pin(compositeData.id, true, i);
94 95 96
	}

	public removeComposite(id: string): void {
97 98 99 100 101 102
		if (this.options.composites.filter(c => c.id === id).length === 0) {
			return;
		}

		this.options.composites = this.options.composites.filter(c => c.id !== id);
		this.unpin(id);
103 104
	}

105 106
	public activateComposite(id: string): void {
		if (this.compositeIdToActions[id]) {
107 108 109
			if (this.compositeIdToActions[this.activeCompositeId]) {
				this.compositeIdToActions[this.activeCompositeId].deactivate();
			}
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
			this.compositeIdToActions[id].activate();
		}
		this.activeCompositeId = id;

		const activeUnpinnedCompositeShouldClose = this.activeUnpinnedCompositeId && this.activeUnpinnedCompositeId !== id;
		const activeUnpinnedCompositeShouldShow = !this.pinnedComposites.some(pid => pid === id);
		if (activeUnpinnedCompositeShouldShow || activeUnpinnedCompositeShouldClose) {
			this.updateCompositeSwitcher();
		}
	}

	public deactivateComposite(id: string): void {
		if (this.compositeIdToActions[id]) {
			this.compositeIdToActions[id].deactivate();
		}
	}

J
Joao Moreno 已提交
127
	public showActivity(compositeId: string, badge: IBadge, clazz?: string, priority?: number): IDisposable {
128 129 130 131
		if (!badge) {
			throw illegalArgument('badge');
		}

J
Joao Moreno 已提交
132 133 134 135 136
		if (typeof priority !== 'number') {
			priority = 0;
		}

		const activity: ICompositeActivity = { badge, clazz, priority };
137
		const stack = this.compositeIdToActivityStack[compositeId] || (this.compositeIdToActivityStack[compositeId] = []);
J
Joao Moreno 已提交
138 139 140 141 142 143 144 145 146 147

		for (let i = 0; i <= stack.length; i++) {
			if (i === stack.length) {
				stack.push(activity);
				break;
			} else if (stack[i].priority <= priority) {
				stack.splice(i, 0, activity);
				break;
			}
		}
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

		this.updateActivity(compositeId);

		return {
			dispose: () => {
				const stack = this.compositeIdToActivityStack[compositeId];
				if (!stack) {
					return;
				}

				const idx = stack.indexOf(activity);
				if (idx < 0) {
					return;
				}

				stack.splice(idx, 1);
				if (stack.length === 0) {
					delete this.compositeIdToActivityStack[compositeId];
				}

				this.updateActivity(compositeId);
			}
		};
	}

	private updateActivity(compositeId: string) {
		const action = this.compositeIdToActions[compositeId];
		if (!action) {
			return;
		}

		const stack = this.compositeIdToActivityStack[compositeId];

		// reset
		if (!stack || !stack.length) {
			action.setBadge(undefined);
		}

		// update
		else {
			const [{ badge, clazz }] = stack;
			action.setBadge(badge);
			if (clazz) {
				action.class = clazz;
			}
		}
	}

I
isidor 已提交
196 197
	public create(parent: HTMLElement): HTMLElement {
		const actionBarDiv = parent.appendChild(dom.$('.composite-bar'));
I
isidor 已提交
198
		this.compositeSwitcherBar = new ActionBar(actionBarDiv, {
199 200 201
			actionItemProvider: (action: Action) => action instanceof CompositeOverflowActivityAction ? this.compositeOverflowActionItem : this.compositeIdToActionItems[action.id],
			orientation: this.options.orientation,
			ariaLabel: nls.localize('activityBarAriaLabel', "Active View Switcher"),
I
isidor 已提交
202
			animated: false,
203
		});
B
Benjamin Pasero 已提交
204
		this.toDispose.push(this.compositeSwitcherBar);
205 206

		// Contextmenu for composites
I
isidor 已提交
207
		this.toDispose.push(dom.addDisposableListener(parent, dom.EventType.CONTEXT_MENU, (e: MouseEvent) => {
208 209 210 211 212
			dom.EventHelper.stop(e, true);
			this._onDidContextMenu.fire(e);
		}));

		// Allow to drop at the end to move composites to the end
I
isidor 已提交
213
		this.toDispose.push(dom.addDisposableListener(parent, dom.EventType.DROP, (e: DragEvent) => {
214 215 216 217 218 219 220
			const draggedCompositeId = CompositeActionItem.getDraggedCompositeId();
			if (draggedCompositeId) {
				dom.EventHelper.stop(e, true);
				CompositeActionItem.clearDraggedComposite();

				const targetId = this.pinnedComposites[this.pinnedComposites.length - 1];
				if (targetId !== draggedCompositeId) {
221
					this.move(draggedCompositeId, this.pinnedComposites[this.pinnedComposites.length - 1]);
222 223 224
				}
			}
		}));
I
isidor 已提交
225 226 227 228 229 230

		return actionBarDiv;
	}

	public getAction(compositeId): ActivityAction {
		return this.compositeIdToActions[compositeId];
231 232 233
	}

	private updateCompositeSwitcher(): void {
I
isidor 已提交
234
		if (!this.compositeSwitcherBar || !this.dimension) {
235 236 237
			return; // We have not been rendered yet so there is nothing to update.
		}

238
		let compositesToShow = this.pinnedComposites.slice(0); // never modify original array
239 240 241 242

		// Always show the active composite even if it is marked to be hidden
		if (this.activeCompositeId && !compositesToShow.some(id => id === this.activeCompositeId)) {
			this.activeUnpinnedCompositeId = this.activeCompositeId;
I
isidor 已提交
243
			compositesToShow = compositesToShow.concat(this.activeUnpinnedCompositeId);
244 245 246 247 248 249
		} else {
			this.activeUnpinnedCompositeId = void 0;
		}

		// Ensure we are not showing more composites than we have height for
		let overflows = false;
I
isidor 已提交
250 251 252 253 254 255 256
		let maxVisible = compositesToShow.length;
		let size = 0;
		const limit = this.options.orientation === ActionsOrientation.VERTICAL ? this.dimension.height : this.dimension.width;
		for (let i = 0; i < compositesToShow.length && size <= limit; i++) {
			size += this.compositeSizeInBar.get(compositesToShow[i]);
			if (size > limit) {
				maxVisible = i;
I
isidor 已提交
257
			}
I
isidor 已提交
258 259
		}
		overflows = compositesToShow.length > maxVisible;
260

I
isidor 已提交
261 262 263
		if (overflows) {
			size -= this.compositeSizeInBar.get(compositesToShow[maxVisible]);
			compositesToShow = compositesToShow.slice(0, maxVisible);
I
isidor 已提交
264
			size += this.options.overflowActionSize;
I
isidor 已提交
265 266
		}
		// Check if we need to make extra room for the overflow action
I
isidor 已提交
267 268
		if (size > limit) {
			size -= this.compositeSizeInBar.get(compositesToShow.pop());
I
isidor 已提交
269
		}
I
isidor 已提交
270
		// We always try show the active composite
I
isidor 已提交
271
		if (this.activeCompositeId && compositesToShow.length && compositesToShow.indexOf(this.activeCompositeId) === -1) {
I
isidor 已提交
272 273
			const removedComposite = compositesToShow.pop();
			size = size - this.compositeSizeInBar.get(removedComposite) + this.compositeSizeInBar.get(this.activeCompositeId);
I
isidor 已提交
274
			compositesToShow.push(this.activeCompositeId);
275
		}
I
isidor 已提交
276 277 278 279
		// The active composite might have bigger size than the removed composite, check for overflow again
		if (size > limit) {
			compositesToShow.length ? compositesToShow.splice(compositesToShow.length - 2, 1) : compositesToShow.pop();
		}
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

		const visibleComposites = Object.keys(this.compositeIdToActions);
		const visibleCompositesChange = !arrays.equals(compositesToShow, visibleComposites);

		// Pull out overflow action if there is a composite change so that we can add it to the end later
		if (this.compositeOverflowAction && visibleCompositesChange) {
			this.compositeSwitcherBar.pull(this.compositeSwitcherBar.length() - 1);

			this.compositeOverflowAction.dispose();
			this.compositeOverflowAction = null;

			this.compositeOverflowActionItem.dispose();
			this.compositeOverflowActionItem = null;
		}

295 296 297
		// Pull out composites that overflow, got hidden or changed position
		visibleComposites.forEach((compositeId, index) => {
			if (compositesToShow.indexOf(compositeId) !== index) {
298 299 300 301 302 303 304 305 306 307 308 309 310
				this.pullComposite(compositeId);
			}
		});

		// Built actions for composites to show
		const newCompositesToShow = compositesToShow
			.filter(compositeId => !this.compositeIdToActions[compositeId])
			.map(compositeId => this.toAction(compositeId));

		// Update when we have new composites to show
		if (newCompositesToShow.length) {

			// Add to composite switcher
I
isidor 已提交
311
			this.compositeSwitcherBar.push(newCompositesToShow, { label: true, icon: this.options.icon });
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

			// Make sure to activate the active one
			if (this.activeCompositeId) {
				const activeCompositeEntry = this.compositeIdToActions[this.activeCompositeId];
				if (activeCompositeEntry) {
					activeCompositeEntry.activate();
				}
			}

			// Make sure to restore activity
			Object.keys(this.compositeIdToActions).forEach(compositeId => {
				this.updateActivity(compositeId);
			});
		}

		// Add overflow action as needed
I
isidor 已提交
328
		if ((visibleCompositesChange && overflows) || this.compositeSwitcherBar.length() === 0) {
329 330 331 332 333 334 335
			this.compositeOverflowAction = this.instantiationService.createInstance(CompositeOverflowActivityAction, () => this.compositeOverflowActionItem.showMenu());
			this.compositeOverflowActionItem = this.instantiationService.createInstance(
				CompositeOverflowActivityActionItem,
				this.compositeOverflowAction,
				() => this.getOverflowingComposites(),
				() => this.activeCompositeId,
				(compositeId: string) => this.compositeIdToActivityStack[compositeId] && this.compositeIdToActivityStack[compositeId][0].badge,
I
isidor 已提交
336
				this.options.getOnCompositeClickAction,
I
isidor 已提交
337
				this.options.colors
338 339
			);

I
isidor 已提交
340
			this.compositeSwitcherBar.push(this.compositeOverflowAction, { label: false, icon: true });
341 342 343 344 345 346 347 348 349 350 351 352 353 354
		}
	}

	private getOverflowingComposites(): { id: string, name: string }[] {
		let overflowingIds = this.pinnedComposites;
		if (this.activeUnpinnedCompositeId) {
			overflowingIds = overflowingIds.concat(this.activeUnpinnedCompositeId);
		}
		const visibleComposites = Object.keys(this.compositeIdToActions);

		overflowingIds = overflowingIds.filter(compositeId => visibleComposites.indexOf(compositeId) === -1);
		return this.options.composites.filter(c => overflowingIds.indexOf(c.id) !== -1);
	}

355
	private getVisibleComposites(): string[] {
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
		return Object.keys(this.compositeIdToActions);
	}

	private pullComposite(compositeId: string): void {
		const index = Object.keys(this.compositeIdToActions).indexOf(compositeId);
		if (index >= 0) {
			this.compositeSwitcherBar.pull(index);

			const action = this.compositeIdToActions[compositeId];
			action.dispose();
			delete this.compositeIdToActions[compositeId];

			const actionItem = this.compositeIdToActionItems[action.id];
			actionItem.dispose();
			delete this.compositeIdToActionItems[action.id];
		}
	}

	private toAction(compositeId: string): ActivityAction {
375 376 377 378
		if (this.compositeIdToActions[compositeId]) {
			return this.compositeIdToActions[compositeId];
		}

379 380
		const compositeActivityAction = this.options.getActivityAction(compositeId);
		const pinnedAction = this.options.getCompositePinnedAction(compositeId);
381
		this.compositeIdToActionItems[compositeId] = this.instantiationService.createInstance(CompositeActionItem, compositeActivityAction, pinnedAction, this.options.colors, this.options.icon, this);
382 383 384 385 386 387
		this.compositeIdToActions[compositeId] = compositeActivityAction;

		return compositeActivityAction;
	}

	public unpin(compositeId: string): void {
388 389 390
		if (!this.isPinned(compositeId)) {
			return;
		}
391

392 393 394 395
		const defaultCompositeId = this.options.getDefaultCompositeId();
		const visibleComposites = this.getVisibleComposites();

		let unpinPromise: TPromise<any>;
396

I
isidor 已提交
397 398 399
		// remove from pinned
		const index = this.pinnedComposites.indexOf(compositeId);
		this.pinnedComposites.splice(index, 1);
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427

		// Case: composite is not the active one or the active one is a different one
		// Solv: we do nothing
		if (!this.activeCompositeId || this.activeCompositeId !== compositeId) {
			unpinPromise = TPromise.as(null);
		}

		// Case: composite is not the default composite and default composite is still showing
		// Solv: we open the default composite
		else if (defaultCompositeId !== compositeId && this.isPinned(defaultCompositeId)) {
			unpinPromise = this.options.openComposite(defaultCompositeId);
		}

		// Case: we closed the last visible composite
		// Solv: we hide the part
		else if (visibleComposites.length === 1) {
			unpinPromise = this.options.hidePart();
		}

		// Case: we closed the default composite
		// Solv: we open the next visible composite from top
		else {
			unpinPromise = this.options.openComposite(visibleComposites.filter(cid => cid !== compositeId)[0]);
		}

		unpinPromise.then(() => {
			this.updateCompositeSwitcher();
		});
428 429 430

		// Persist
		this.savePinnedComposites();
431 432 433 434 435 436
	}

	public isPinned(compositeId: string): boolean {
		return this.pinnedComposites.indexOf(compositeId) >= 0;
	}

437
	public pin(compositeId: string, update = true, index = this.pinnedComposites.length): void {
438 439
		if (this.isPinned(compositeId)) {
			return;
440
		}
441 442

		this.options.openComposite(compositeId).then(() => {
443
			this.pinnedComposites.splice(index, 0, compositeId);
444 445 446 447 448
			this.pinnedComposites = arrays.distinct(this.pinnedComposites);

			if (update) {
				this.updateCompositeSwitcher();
			}
449 450 451

			// Persist
			this.savePinnedComposites();
452
		});
453 454 455
	}

	public move(compositeId: string, toCompositeId: string): void {
456 457 458 459
		// Make sure both composites are known to this composite bar
		if (this.options.composites.filter(c => c.id === compositeId || c.id === toCompositeId).length !== 2) {
			return;
		}
460 461 462 463
		// Make sure a moved composite gets pinned
		if (!this.isPinned(compositeId)) {
			this.pin(compositeId, false /* defer update, we take care of it */);
		}
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480

		const fromIndex = this.pinnedComposites.indexOf(compositeId);
		const toIndex = this.pinnedComposites.indexOf(toCompositeId);

		this.pinnedComposites.splice(fromIndex, 1);
		this.pinnedComposites.splice(toIndex, 0, compositeId);

		// Clear composites that are impacted by the move
		const visibleComposites = Object.keys(this.compositeIdToActions);
		for (let i = Math.min(fromIndex, toIndex); i < visibleComposites.length; i++) {
			this.pullComposite(visibleComposites[i]);
		}

		// timeout helps to prevent artifacts from showing up
		setTimeout(() => {
			this.updateCompositeSwitcher();
		}, 0);
481 482 483

		// Persist
		this.savePinnedComposites();
484 485 486 487
	}

	public layout(dimension: Dimension): void {
		this.dimension = dimension;
488 489 490 491 492
		if (dimension.height === 0 || dimension.width === 0) {
			// Do not layout if not visible. Otherwise the size measurment would be computed wrongly
			return;
		}

493 494 495 496 497 498 499 500 501 502 503
		if (this.compositeSizeInBar.size === 0) {
			// Compute size of each composite by getting the size from the css renderer
			// Size is later used for overflow computation
			this.compositeSwitcherBar.clear();
			this.compositeSwitcherBar.push(this.options.composites.map(c => this.options.getActivityAction(c.id)));
			this.options.composites.map((c, index) => this.compositeSizeInBar.set(c.id, this.options.orientation === ActionsOrientation.VERTICAL
				? this.compositeSwitcherBar.getHeight(index)
				: this.compositeSwitcherBar.getWidth(index)
			));
			this.compositeSwitcherBar.clear();
		}
504 505 506
		this.updateCompositeSwitcher();
	}

507
	private savePinnedComposites(): void {
508 509 510 511 512 513 514
		this.storageService.store(this.options.storageId, JSON.stringify(this.pinnedComposites), StorageScope.GLOBAL);
	}

	public dispose(): void {
		this.toDispose = dispose(this.toDispose);
	}
}