quickOpenWidget.ts 24.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  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!./quickopen';
B
Benjamin Pasero 已提交
8
import nls = require('vs/nls');
9
import {TPromise} from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
10 11 12 13 14 15
import platform = require('vs/base/common/platform');
import browser = require('vs/base/browser/browser');
import {EventType} from 'vs/base/common/events';
import types = require('vs/base/common/types');
import errors = require('vs/base/common/errors');
import uuid = require('vs/base/common/uuid');
16
import {IQuickNavigateConfiguration, IAutoFocus, IContext, IModel, Mode} from 'vs/base/parts/quickopen/common/quickOpen';
17
import {Filter, Renderer, DataSource, IModelProvider, AccessibilityProvider} from 'vs/base/parts/quickopen/browser/quickOpenViewer';
E
Erich Gamma 已提交
18
import {Dimension, Builder, $} from 'vs/base/browser/builder';
J
Joao Moreno 已提交
19
import {ISelectionEvent, IFocusEvent, ITree, ContextMenuEvent} from 'vs/base/parts/tree/browser/tree';
20 21
import {InputBox, MessageType} from 'vs/base/browser/ui/inputbox/inputBox';
import Severity from 'vs/base/common/severity';
E
Erich Gamma 已提交
22 23 24 25 26 27 28
import {Tree} from 'vs/base/parts/tree/browser/treeImpl';
import {ProgressBar} from 'vs/base/browser/ui/progressbar/progressbar';
import {StandardKeyboardEvent} from 'vs/base/browser/keyboardEvent';
import {DefaultController, ClickBehavior} from 'vs/base/parts/tree/browser/treeDefaults';
import DOM = require('vs/base/browser/dom');
import {IActionProvider} from 'vs/base/parts/tree/browser/actionsRenderer';
import {KeyCode} from 'vs/base/common/keyCodes';
J
Joao Moreno 已提交
29
import {IDisposable,dispose} from 'vs/base/common/lifecycle';
A
Alex Dima 已提交
30
import {ScrollbarVisibility} from 'vs/base/browser/ui/scrollbar/scrollableElementOptions';
E
Erich Gamma 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

export interface IQuickOpenCallbacks {
	onOk: () => void;
	onCancel: () => void;
	onType: (value: string) => void;
	onShow?: () => void;
	onHide?: () => void;
	onFocusLost?: () => boolean /* veto close */;
}

export interface IQuickOpenOptions {
	minItemsToShow?: number;
	maxItemsToShow?: number;
	inputPlaceHolder: string;
	inputAriaLabel?: string;
	actionProvider?: IActionProvider;
	enableAnimations?: boolean;
}

export interface IQuickOpenUsageLogger {
	publicLog(eventName: string, data?: any): void;
}

54 55
export class QuickOpenController extends DefaultController {

56
	public onContextMenu(tree: ITree, element: any, event: ContextMenuEvent): boolean {
57 58 59 60 61 62 63 64
		if (platform.isMacintosh) {
			return this.onLeftClick(tree, element, event); // https://github.com/Microsoft/vscode/issues/1011
		}

		return super.onContextMenu(tree, element, event);
	}
}

65 66
const DEFAULT_INPUT_ARIA_LABEL = nls.localize('quickOpenAriaLabel', "Quick picker. Type to narrow down results.");

E
Erich Gamma 已提交
67 68 69
export class QuickOpenWidget implements IModelProvider {

	public static MAX_WIDTH = 600;				// Max total width of quick open widget
I
isidor 已提交
70
	public static MAX_ITEMS_HEIGHT = 20 * 22;	// Max height of item list below input field
E
Erich Gamma 已提交
71 72 73 74 75 76 77 78 79 80 81 82

	private options: IQuickOpenOptions;
	private builder: Builder;
	private tree: ITree;
	private inputBox: InputBox;
	private inputContainer: Builder;
	private helpText: Builder;
	private treeContainer: Builder;
	private progressBar: ProgressBar;
	private visible: boolean;
	private isLoosingFocus: boolean;
	private callbacks: IQuickOpenCallbacks;
A
Alex Dima 已提交
83
	private toUnbind: IDisposable[];
E
Erich Gamma 已提交
84 85 86
	private currentInputToken: string;
	private quickNavigateConfiguration: IQuickNavigateConfiguration;
	private container: HTMLElement;
87 88
	private treeElement: HTMLElement;
	private inputElement: HTMLElement;
E
Erich Gamma 已提交
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
	private usageLogger: IQuickOpenUsageLogger;
	private layoutDimensions: Dimension;
	private model: IModel<any>;

	constructor(container: HTMLElement, callbacks: IQuickOpenCallbacks, options: IQuickOpenOptions, usageLogger?: IQuickOpenUsageLogger) {
		this.toUnbind = [];
		this.container = container;
		this.callbacks = callbacks;
		this.options = options;
		this.usageLogger = usageLogger;
		this.model = null;
	}

	getModel(): IModel<any> {
		return this.model;
	}

	public setCallbacks(callbacks: IQuickOpenCallbacks): void {
		this.callbacks = callbacks;
	}

	public create(): void {
		this.builder = $().div((div: Builder) => {

			// Eventing
114
			div.on(DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
E
Erich Gamma 已提交
115 116 117 118 119 120 121
				let keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);
				if (keyboardEvent.keyCode === KeyCode.Escape) {
					DOM.EventHelper.stop(e, true);

					this.hide(true);
				}
			})
122 123 124
			.on(DOM.EventType.CONTEXT_MENU, (e: Event) => DOM.EventHelper.stop(e, true)) // Do this to fix an issue on Mac where the menu goes into the way
			.on(DOM.EventType.FOCUS, (e: Event) => this.gainingFocus(), null, true)
			.on(DOM.EventType.BLUR, (e: Event) => this.loosingFocus(e), null, true);
E
Erich Gamma 已提交
125 126 127 128 129 130 131 132 133 134

			// Progress Bar
			this.progressBar = new ProgressBar(div.clone());
			this.progressBar.getContainer().hide();

			// Input Field
			div.div({ 'class': 'quick-open-input' }, (inputContainer) => {
				this.inputContainer = inputContainer;
				this.inputBox = new InputBox(inputContainer.getHTMLElement(), null, {
					placeholder: this.options.inputPlaceHolder || '',
135
					ariaLabel: DEFAULT_INPUT_ARIA_LABEL
E
Erich Gamma 已提交
136
				});
137 138 139 140 141 142 143

				// ARIA
				this.inputElement = this.inputBox.inputElement;
				this.inputElement.setAttribute('role', 'combobox');
				this.inputElement.setAttribute('aria-haspopup', 'false');
				this.inputElement.setAttribute('aria-autocomplete', 'list');

E
Erich Gamma 已提交
144 145 146
				DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
					let keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);

147 148 149 150 151
					// Do not handle Tab: It is used to navigate between elements without mouse
					if (keyboardEvent.keyCode === KeyCode.Tab) {
						return;
					}

E
Erich Gamma 已提交
152
					// Pass tree navigation keys to the tree but leave focus in input field
153
					else if (keyboardEvent.keyCode === KeyCode.Tab || keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) {
E
Erich Gamma 已提交
154 155 156 157 158 159
						DOM.EventHelper.stop(e, true);

						this.navigateInTree(keyboardEvent.keyCode, keyboardEvent.shiftKey);
					}

					// Select element on Enter
160
					else if (keyboardEvent.keyCode === KeyCode.Enter) {
E
Erich Gamma 已提交
161 162 163 164 165 166 167
						DOM.EventHelper.stop(e, true);

						let focus = this.tree.getFocus();
						if (focus) {
							this.elementSelected(focus, e);
						}
					}
168 169 170 171 172

					// Bug in IE 9: onInput is not fired for Backspace or Delete keys
					else if (browser.isIE9 && (keyboardEvent.keyCode === KeyCode.Backspace || keyboardEvent.keyCode === KeyCode.Delete)) {
						this.onType();
					}
E
Erich Gamma 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185
				});

				DOM.addDisposableListener(this.inputBox.inputElement, DOM.EventType.INPUT, (e: Event) => {
					this.onType();
				});
			});

			// Tree
			this.treeContainer = div.div({
				'class': 'quick-open-tree'
			}, (div: Builder) => {
				this.tree = new Tree(div.getHTMLElement(), {
					dataSource: new DataSource(this),
186
					controller: new QuickOpenController({ clickBehavior: ClickBehavior.ON_MOUSE_UP }),
E
Erich Gamma 已提交
187
					renderer: new Renderer(this),
188 189
					filter: new Filter(this),
					accessibilityProvider: new AccessibilityProvider(this)
E
Erich Gamma 已提交
190
				}, {
B
Benjamin Pasero 已提交
191 192 193
					twistiePixels: 11,
					indentPixels: 0,
					alwaysFocused: true,
A
Alex Dima 已提交
194
					verticalScrollMode: ScrollbarVisibility.Visible,
B
Benjamin Pasero 已提交
195 196
					ariaLabel: nls.localize('treeAriaLabel', "Quick Picker")
				});
E
Erich Gamma 已提交
197

198 199
				this.treeElement = this.tree.getHTMLElement();

E
Erich Gamma 已提交
200
				// Handle Focus and Selection event
A
Alex Dima 已提交
201
				this.toUnbind.push(this.tree.addListener2(EventType.FOCUS, (event: IFocusEvent) => {
E
Erich Gamma 已提交
202 203 204
					this.elementFocused(event.focus, event);
				}));

A
Alex Dima 已提交
205
				this.toUnbind.push(this.tree.addListener2(EventType.SELECTION, (event: ISelectionEvent) => {
E
Erich Gamma 已提交
206 207 208 209 210
					if (event.selection && event.selection.length > 0) {
						this.elementSelected(event.selection[0], event);
					}
				}));
			}).
211 212
			on(DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => {
				let keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);
E
Erich Gamma 已提交
213

214 215 216 217
				// Only handle when in quick navigation mode
				if (!this.quickNavigateConfiguration) {
					return;
				}
E
Erich Gamma 已提交
218

219 220 221
				// Support keyboard navigation in quick navigation mode
				if (keyboardEvent.keyCode === KeyCode.DownArrow || keyboardEvent.keyCode === KeyCode.UpArrow || keyboardEvent.keyCode === KeyCode.PageDown || keyboardEvent.keyCode === KeyCode.PageUp) {
					DOM.EventHelper.stop(e, true);
E
Erich Gamma 已提交
222

223 224 225 226 227 228
					this.navigateInTree(keyboardEvent.keyCode);
				}
			}).
			on(DOM.EventType.KEY_UP, (e: KeyboardEvent) => {
				let keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e);
				let keyCode = keyboardEvent.keyCode;
E
Erich Gamma 已提交
229

230 231 232 233 234 235 236 237 238 239 240 241 242 243
				// Only handle when in quick navigation mode
				if (!this.quickNavigateConfiguration) {
					return;
				}

				// Select element when keys are pressed that signal it
				let quickNavKeys = this.quickNavigateConfiguration.keybindings;
				let wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some((k) => {
					if (k.hasShift() && keyCode === KeyCode.Shift) {
						if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
							return false; // this is an optimistic check for the shift key being used to navigate back in quick open
						}

						return true;
E
Erich Gamma 已提交
244 245
					}

246 247 248
					if (k.hasAlt() && keyCode === KeyCode.Alt) {
						return true;
					}
249

250 251 252
					// Mac is a bit special
					if (platform.isMacintosh) {
						if (k.hasCtrlCmd() && keyCode === KeyCode.Meta) {
E
Erich Gamma 已提交
253 254 255
							return true;
						}

256
						if (k.hasWinCtrl() && keyCode === KeyCode.Ctrl) {
E
Erich Gamma 已提交
257 258
							return true;
						}
259
					}
E
Erich Gamma 已提交
260

261 262 263 264
					// Windows/Linux are not :)
					else {
						if (k.hasCtrlCmd() && keyCode === KeyCode.Ctrl) {
							return true;
E
Erich Gamma 已提交
265 266
						}

267 268
						if (k.hasWinCtrl() && keyCode === KeyCode.Meta) {
							return true;
E
Erich Gamma 已提交
269
						}
270
					}
E
Erich Gamma 已提交
271

272 273
					return false;
				});
E
Erich Gamma 已提交
274

275 276 277 278
				if (wasTriggerKeyPressed) {
					let focus = this.tree.getFocus();
					if (focus) {
						this.elementSelected(focus, e);
E
Erich Gamma 已提交
279
					}
280 281 282
				}
			}).
			clone();
E
Erich Gamma 已提交
283 284
		})

285 286 287 288
		// Widget Attributes
		.addClass('quick-open-widget')
		.addClass((browser.isIE10orEarlier) ? ' no-shadow' : '')
		.build(this.container);
E
Erich Gamma 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

		// Support layout
		if (this.layoutDimensions) {
			this.layout(this.layoutDimensions);
		}
	}

	private onType(): void {
		let value = this.inputBox.value;

		// Adjust help text as needed if present
		if (this.helpText) {
			if (value) {
				this.helpText.hide();
			} else {
				this.helpText.show();
			}
		}

		// Send to callbacks
		this.callbacks.onType(value);
	}

	public quickNavigate(configuration: IQuickNavigateConfiguration, next: boolean): void {
		if (this.isVisible) {

			// Transition into quick navigate mode if not yet done
			if (!this.quickNavigateConfiguration) {
				this.quickNavigateConfiguration = configuration;
				this.tree.DOMFocus();
			}

			// Navigate
			this.navigateInTree(next ? KeyCode.DownArrow : KeyCode.UpArrow);
		}
	}

	private navigateInTree(keyCode: KeyCode, isShift?: boolean): void {
		const model: IModel<any> = this.tree.getInput();
		const entries = model ? model.entries : [];
		let focus = this.tree.getFocus();
		let cycled = false;
		let revealToTop = false;

		// Support cycle-through navigation
		if (entries.length > 1) {

			// Up from no entry or first entry goes down to last
			if ((keyCode === KeyCode.UpArrow || (keyCode === KeyCode.Tab && isShift)) && (focus === entries[0] || !focus)) { // TODO@Ben should not make ordering assumptions
				this.tree.focusLast();
				cycled = true;
			}

			// Down from last entry goes to up to first
			else if ((keyCode === KeyCode.DownArrow || keyCode === KeyCode.Tab && !isShift) && focus === entries[entries.length - 1]) { // TODO@Ben should not make ordering assumptions
				this.tree.focusFirst();
				cycled = true;
			}
		}

		// Normal Navigation
		if (!cycled) {
			switch (keyCode) {
				case KeyCode.DownArrow:
					this.tree.focusNext();
					break;

				case KeyCode.UpArrow:
					this.tree.focusPrevious();
					break;

				case KeyCode.PageDown:
					this.tree.focusNextPage();
					break;

				case KeyCode.PageUp:
					this.tree.focusPreviousPage();
					break;

				case KeyCode.Tab:
					if (isShift) {
						this.tree.focusPrevious();
					} else {
						this.tree.focusNext();
					}
					break;
			}
		}

		// Reveal
		focus = this.tree.getFocus();
		if (focus) {
381
			revealToTop ? this.tree.reveal(focus, 0).done(null, errors.onUnexpectedError) : this.tree.reveal(focus).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
382 383 384 385 386 387 388 389
		}
	}

	private elementFocused(value: any, event?: any): void {
		if (!value || !this.isVisible()) {
			return;
		}

390 391 392
		// ARIA
		this.inputElement.setAttribute('aria-activedescendant', this.treeElement.getAttribute('aria-activedescendant'));

E
Erich Gamma 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405
		const context: IContext = { event: event, quickNavigateConfiguration: this.quickNavigateConfiguration };
		this.model.runner.run(value, Mode.PREVIEW, context);
	}

	private elementSelected(value: any, event?: any): void {
		let hide = true;

		// Trigger open of element on selection
		if (this.isVisible()) {
			const context: IContext = { event: event, quickNavigateConfiguration: this.quickNavigateConfiguration };
			hide = this.model.runner.run(value, Mode.OPEN, context);
		}

P
Pascal Borreli 已提交
406
		// add telemetry when an item is accepted, logging the index of the item in the list and the length of the list
E
Erich Gamma 已提交
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		// to measure the rate of the success and the relevance of the order
		if (this.usageLogger) {
			let indexOfAcceptedElement = this.model.entries.indexOf(value);
			let entriesCount = this.model.entries.length;
			this.usageLogger.publicLog('quickOpenWidgetItemAccepted', { index: indexOfAcceptedElement, count: entriesCount, isQuickNavigate: this.quickNavigateConfiguration ? true : false });
		}

		// Hide if command was run successfully
		if (hide) {
			this.hide();
		}
	}

	public show(prefix: string): void;
	public show(input: IModel<any>, autoFocus?: IAutoFocus, quickNavigateConfiguration?: IQuickNavigateConfiguration): void;
	public show(param: any, autoFocus?: IAutoFocus, quickNavigateConfiguration?: IQuickNavigateConfiguration): void {
		if (types.isUndefined(autoFocus)) {
			autoFocus = {};
		}

		this.visible = true;
		this.isLoosingFocus = false;
		this.quickNavigateConfiguration = quickNavigateConfiguration;

		// Adjust UI for quick navigate mode
		if (this.quickNavigateConfiguration) {
			this.inputContainer.hide();
			if (this.options.enableAnimations) {
				this.treeContainer.removeClass('transition');
			}
			this.builder.show();
			this.tree.DOMFocus();
		}

		// Otherwise use normal UI
		else {
			this.inputContainer.show();
			if (this.options.enableAnimations) {
				this.treeContainer.addClass('transition');
			}
			this.builder.show();
			this.inputBox.focus();
		}

		// Adjust Help text for IE
		if (this.helpText) {
			if (this.quickNavigateConfiguration || types.isString(param)) {
				this.helpText.hide();
			} else {
				this.helpText.show();
			}
		}

		// Show based on param
		if (types.isString(param)) {
			this.doShowWithPrefix(param);
		} else {
			this.doShowWithInput(param, autoFocus);
		}

		if (this.callbacks.onShow) {
			this.callbacks.onShow();
		}
	}

	private doShowWithPrefix(prefix: string): void {
		this.inputBox.value = prefix;
		this.callbacks.onType(prefix);
	}

	private doShowWithInput(input: IModel<any>, autoFocus: IAutoFocus): void {
		this.setInput(input, autoFocus);
	}

	private setInputAndLayout(input: IModel<any>, autoFocus: IAutoFocus): void {

		// Use a generated token to avoid race conditions from setting input
		let currentInputToken = uuid.generateUuid();
		this.currentInputToken = currentInputToken;

		// setInput and Layout
		this.setTreeHeightForInput(input).then(() => {
			if (this.currentInputToken === currentInputToken) {
				this.tree.setInput(null).then(() => {
					this.model = input;
492 493 494 495

					// ARIA
					this.inputElement.setAttribute('aria-haspopup', String(input && input.entries && input.entries.length > 0));

E
Erich Gamma 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
					return this.tree.setInput(input);
				}).done(() => {
					// Indicate entries to tree
					this.tree.layout();

					// Handle auto focus
					if (input && input.entries.some(e => this.isElementVisible(input, e))) {
						this.autoFocus(input, autoFocus);
					}
				}, errors.onUnexpectedError);
			}
		});
	}

	private isElementVisible<T>(input: IModel<T>, e: T): boolean {
		if (!input.filter) {
			return true;
		}

		return input.filter.isVisible(e);
	}

	private autoFocus(input: IModel<any>, autoFocus: IAutoFocus = {}): void {
		const entries = input.entries.filter(e => this.isElementVisible(input, e));

		// First check for auto focus of prefix matches
		if (autoFocus.autoFocusPrefixMatch) {
			let caseSensitiveMatch: any;
			let caseInsensitiveMatch: any;
			let prefix = autoFocus.autoFocusPrefixMatch;
			let lowerCasePrefix = prefix.toLowerCase();
			for (let i = 0; i < entries.length; i++) {
				let entry = entries[i];
				const label = input.dataSource.getLabel(entry);

				if (!caseSensitiveMatch && label.indexOf(prefix) === 0) {
					caseSensitiveMatch = entry;
				} else if (!caseInsensitiveMatch && label.toLowerCase().indexOf(lowerCasePrefix) === 0) {
					caseInsensitiveMatch = entry;
				}

				if (caseSensitiveMatch && caseInsensitiveMatch) {
					break;
				}
			}

			let entryToFocus = caseSensitiveMatch || caseInsensitiveMatch;
			if (entryToFocus) {
				this.tree.setFocus(entryToFocus);
545
				this.tree.reveal(entryToFocus, 0).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
546 547 548 549 550 551 552 553

				return;
			}
		}

		// Second check for auto focus of first entry
		if (autoFocus.autoFocusFirstEntry) {
			this.tree.focusFirst();
554
			this.tree.reveal(this.tree.getFocus(), 0).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
555 556 557 558 559 560
		}

		// Third check for specific index option
		else if (typeof autoFocus.autoFocusIndex === 'number') {
			if (entries.length > autoFocus.autoFocusIndex) {
				this.tree.focusNth(autoFocus.autoFocusIndex);
561
				this.tree.reveal(this.tree.getFocus()).done(null, errors.onUnexpectedError);
E
Erich Gamma 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
			}
		}

		// Finally check for auto focus of second entry
		else if (autoFocus.autoFocusSecondEntry) {
			if (entries.length > 1) {
				this.tree.focusNth(1);
			}
		}
	}

	public refresh(input: IModel<any>, autoFocus: IAutoFocus): void {
		if (!this.isVisible()) {
			return;
		}

		// Apply height & Refresh
		this.setTreeHeightForInput(input).then(() => {
			this.tree.refresh().done(() => {

				// Indicate entries to tree
				this.tree.layout();

				// Handle auto focus
				if (!this.tree.getFocus() && input && input.entries.some(e => this.isElementVisible(input, e))) {
					this.autoFocus(input, autoFocus);
				}
			}, errors.onUnexpectedError);
		});
	}

593
	private setTreeHeightForInput(input: IModel<any>): TPromise<void> {
E
Erich Gamma 已提交
594 595 596 597 598 599
		let newHeight = this.getHeight(input) + 'px';
		let oldHeight = this.treeContainer.style('height');

		// Apply
		this.treeContainer.style({ height: newHeight });

P
Pascal Borreli 已提交
600
		// Return instantly if we don't CSS transition or the height is the same as old
E
Erich Gamma 已提交
601
		if (!this.treeContainer.hasClass('transition') || oldHeight === newHeight) {
602
			return TPromise.as(null);
E
Erich Gamma 已提交
603 604
		}

P
Pascal Borreli 已提交
605
		// Otherwise return promise that only fulfills when the CSS transition has ended
606
		return new TPromise<void>((c, e) => {
607
			let unbind: IDisposable[] = [];
E
Erich Gamma 已提交
608 609 610 611 612
			let complete = false;
			let completeHandler = () => {
				if (!complete) {
					complete = true;

J
Joao Moreno 已提交
613
					unbind = dispose(unbind);
E
Erich Gamma 已提交
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680

					c(null);
				}
			};

			this.treeContainer.once('webkitTransitionEnd', completeHandler, unbind);
			this.treeContainer.once('transitionend', completeHandler, unbind);
		});
	}

	private getHeight(input: IModel<any>): number {
		const renderer = input.renderer;

		if (!input) {
			let itemHeight = renderer.getHeight(null);

			return this.options.minItemsToShow ? this.options.minItemsToShow * itemHeight : 0;
		}

		let height = 0;

		let preferredItemsHeight: number;
		if (this.layoutDimensions && this.layoutDimensions.height) {
			preferredItemsHeight = (this.layoutDimensions.height - 50 /* subtract height of input field (30px) and some spacing (drop shadow) to fit */) * 0.40 /* max 40% of screen */;
		}

		if (!preferredItemsHeight || preferredItemsHeight > QuickOpenWidget.MAX_ITEMS_HEIGHT) {
			preferredItemsHeight = QuickOpenWidget.MAX_ITEMS_HEIGHT;
		}

		let entries = input.entries.filter(e => this.isElementVisible(input, e));
		let maxEntries = this.options.maxItemsToShow || entries.length;
		for (let i = 0; i < maxEntries && i < entries.length; i++) {
			let entryHeight = renderer.getHeight(entries[i]);
			if (height + entryHeight <= preferredItemsHeight) {
				height += entryHeight;
			} else {
				break;
			}
		}

		return height;
	}

	public hide(isCancel: boolean = false): void {
		if (!this.isVisible()) {
			return;
		}

		this.visible = false;
		this.builder.hide();
		this.builder.domBlur();

		// report failure cases
		if (isCancel) {
			if (this.model) {
				let entriesCount = this.model.entries.filter(e => this.isElementVisible(this.model, e)).length;
				if (this.usageLogger) {
					this.usageLogger.publicLog('quickOpenWidgetCancelled', { count: entriesCount, isQuickNavigate: this.quickNavigateConfiguration ? true : false });
				}
			}
		}

		// Clear input field and clear tree
		this.inputBox.value = '';
		this.tree.setInput(null);

681 682 683
		// ARIA
		this.inputElement.setAttribute('aria-haspopup', 'false');

E
Erich Gamma 已提交
684
		// Reset Tree Height
I
isidor 已提交
685
		this.treeContainer.style({ height: (this.options.minItemsToShow ? this.options.minItemsToShow * 22 : 0) + 'px' });
E
Erich Gamma 已提交
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

		// Clear any running Progress
		this.progressBar.stop().getContainer().hide();

		// Clear Focus
		if (this.tree.isDOMFocused()) {
			this.tree.DOMBlur();
		} else if (this.inputBox.hasFocus()) {
			this.inputBox.blur();
		}

		// Callbacks
		if (isCancel) {
			this.callbacks.onCancel();
		} else {
			this.callbacks.onOk();
		}

		if (this.callbacks.onHide) {
			this.callbacks.onHide();
		}
	}

	public setPlaceHolder(placeHolder: string): void {
		if (this.inputBox) {
			this.inputBox.setPlaceHolder(placeHolder);
		}
	}

	public setValue(value: string): void {
		if (this.inputBox) {
			this.inputBox.value = value;
			this.inputBox.select();
		}
	}

	public setPassword(isPassword: boolean): void {
		if (this.inputBox) {
			this.inputBox.inputElement.type = isPassword ? 'password' : 'text';
		}
	}

728
	public setInput(input: IModel<any>, autoFocus: IAutoFocus, ariaLabel?: string): void {
E
Erich Gamma 已提交
729 730 731 732 733 734
		if (!this.isVisible()) {
			return;
		}

		// Adapt tree height to entries and apply input
		this.setInputAndLayout(input, autoFocus);
735 736 737 738 739

		// Apply ARIA
		if (this.inputBox) {
			this.inputBox.setAriaLabel(ariaLabel || DEFAULT_INPUT_ARIA_LABEL);
		}
E
Erich Gamma 已提交
740 741 742 743 744 745
	}

	public getInput(): IModel<any> {
		return this.tree.getInput();
	}

746 747 748 749 750 751 752 753 754 755 756 757
	public showInputDecoration(decoration: Severity): void {
		if (this.inputBox) {
			this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' });
		}
	}

	public clearInputDecoration(): void {
		if (this.inputBox) {
			this.inputBox.hideMessage();
		}
	}

E
Erich Gamma 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
	public runFocus(): boolean {
		let focus = this.tree.getFocus();
		if (focus) {
			this.elementSelected(focus);
			return true;
		}

		return false;
	}

	public getProgressBar(): ProgressBar {
		return this.progressBar;
	}

	public setExtraClass(clazz: string): void {
		let previousClass = this.builder.getProperty('extra-class');
		if (previousClass) {
			this.builder.removeClass(previousClass);
		}

		if (clazz) {
			this.builder.addClass(clazz);
			this.builder.setProperty('extra-class', clazz);
		} else if (previousClass) {
			this.builder.removeProperty('extra-class');
		}
	}

	public isVisible(): boolean {
		return this.visible;
	}

	public layout(dimension: Dimension): void {
		this.layoutDimensions = dimension;

		// Apply to quick open width (height is dynamic by number of items to show)
		let quickOpenWidth = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickOpenWidget.MAX_WIDTH);
		if (this.builder) {

			// quick open
			this.builder.style({
				width: quickOpenWidth + 'px',
				marginLeft: '-' + (quickOpenWidth / 2) + 'px'
			});

			// input field
			this.inputContainer.style({
				width: (quickOpenWidth - 12) + 'px'
			});
		}
	}

	private gainingFocus(): void {
		this.isLoosingFocus = false;
	}

	private loosingFocus(e: Event): void {
		if (!this.isVisible()) {
			return;
		}

		const relatedTarget = (<any>e).relatedTarget;
		if (!this.quickNavigateConfiguration && DOM.isAncestor(relatedTarget, this.builder.getHTMLElement())) {
821
			return; // user clicked somewhere into quick open widget, do not close thereby
E
Erich Gamma 已提交
822 823 824
		}

		this.isLoosingFocus = true;
825
		TPromise.timeout(0).then(() => {
E
Erich Gamma 已提交
826 827 828 829 830 831 832 833 834 835 836 837
			if (!this.isLoosingFocus) {
				return;
			}

			const veto = this.callbacks.onFocusLost && this.callbacks.onFocusLost();
			if (!veto) {
				this.hide(false /* Do not treat loosing focus as cancel! */);
			}
		});
	}

	public dispose(): void {
A
Alex Dima 已提交
838
		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
839 840 841 842 843 844

		this.progressBar.dispose();
		this.inputBox.dispose();
		this.tree.dispose();
	}
}