listWidget.ts 48.9 KB
Newer Older
J
Joao Moreno 已提交
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!./list';
J
Joao Moreno 已提交
7
import { localize } from 'vs/nls';
J
Joao Moreno 已提交
8
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
J
Joao Moreno 已提交
9
import { isNumber } from 'vs/base/common/types';
J
Joao Moreno 已提交
10
import { range, firstIndex } from 'vs/base/common/arrays';
J
Joao Moreno 已提交
11
import { memoize } from 'vs/base/common/decorators';
J
Joao Moreno 已提交
12
import * as DOM from 'vs/base/browser/dom';
J
Joao Moreno 已提交
13
import * as platform from 'vs/base/common/platform';
J
Joao Moreno 已提交
14
import { Gesture } from 'vs/base/browser/touch';
15
import { KeyCode } from 'vs/base/common/keyCodes';
16
import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
J
Joao Moreno 已提交
17
import { Event, Emitter, EventBufferer } from 'vs/base/common/event';
J
Joao Moreno 已提交
18
import { domEvent } from 'vs/base/browser/event';
19
import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole } from './list';
J
Joao Moreno 已提交
20
import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaSetProvider } from './listView';
21
import { Color } from 'vs/base/common/color';
J
Joao Moreno 已提交
22
import { mixin } from 'vs/base/common/objects';
23
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
J
Joao Moreno 已提交
24
import { ISpliceable } from 'vs/base/common/sequence';
J
Joao Moreno 已提交
25
import { CombinedSpliceable } from 'vs/base/browser/ui/list/splice';
J
Joao Moreno 已提交
26
import { clamp } from 'vs/base/common/numbers';
J
Joao Moreno 已提交
27
import { matchesPrefix } from 'vs/base/common/filters';
J
Joao Moreno 已提交
28
import { IDragAndDropData } from 'vs/base/browser/dnd';
J
Joao Moreno 已提交
29

J
Joao Moreno 已提交
30 31
interface ITraitChangeEvent {
	indexes: number[];
32
	browserEvent?: UIEvent;
J
Joao Moreno 已提交
33 34
}

J
Joao Moreno 已提交
35
type ITraitTemplateData = HTMLElement;
J
Joao Moreno 已提交
36

J
Joao Moreno 已提交
37
interface IRenderedContainer {
J
Joao Moreno 已提交
38 39
	templateData: ITraitTemplateData;
	index: number;
J
Joao Moreno 已提交
40 41
}

J
Joao Moreno 已提交
42
class TraitRenderer<T> implements IListRenderer<T, ITraitTemplateData>
J
Joao Moreno 已提交
43
{
J
Joao Moreno 已提交
44
	private renderedElements: IRenderedContainer[] = [];
J
Joao Moreno 已提交
45 46

	constructor(private trait: Trait<T>) { }
J
Joao Moreno 已提交
47

J
Joao Moreno 已提交
48
	get templateId(): string {
J
Joao Moreno 已提交
49 50 51 52
		return `template:${this.trait.trait}`;
	}

	renderTemplate(container: HTMLElement): ITraitTemplateData {
J
Joao Moreno 已提交
53
		return container;
J
Joao Moreno 已提交
54 55 56
	}

	renderElement(element: T, index: number, templateData: ITraitTemplateData): void {
J
Joao Moreno 已提交
57
		const renderedElementIndex = firstIndex(this.renderedElements, el => el.templateData === templateData);
J
Joao Moreno 已提交
58

J
Joao Moreno 已提交
59 60 61 62 63 64 65 66
		if (renderedElementIndex >= 0) {
			const rendered = this.renderedElements[renderedElementIndex];
			this.trait.unrender(templateData);
			rendered.index = index;
		} else {
			const rendered = { index, templateData };
			this.renderedElements.push(rendered);
		}
J
Joao Moreno 已提交
67

J
Joao Moreno 已提交
68
		this.trait.renderIndex(index, templateData);
J
Joao Moreno 已提交
69 70
	}

J
Joao Moreno 已提交
71 72
	splice(start: number, deleteCount: number, insertCount: number): void {
		const rendered: IRenderedContainer[] = [];
J
Joao Moreno 已提交
73

74
		for (const renderedElement of this.renderedElements) {
A
Alex Dima 已提交
75

J
Joao Moreno 已提交
76 77 78 79 80 81 82
			if (renderedElement.index < start) {
				rendered.push(renderedElement);
			} else if (renderedElement.index >= start + deleteCount) {
				rendered.push({
					index: renderedElement.index + insertCount - deleteCount,
					templateData: renderedElement.templateData
				});
J
Joao Moreno 已提交
83 84
			}
		}
J
Joao Moreno 已提交
85 86

		this.renderedElements = rendered;
J
Joao Moreno 已提交
87 88
	}

J
Joao Moreno 已提交
89 90 91 92
	renderIndexes(indexes: number[]): void {
		for (const { index, templateData } of this.renderedElements) {
			if (indexes.indexOf(index) > -1) {
				this.trait.renderIndex(index, templateData);
J
Joao Moreno 已提交
93 94
			}
		}
J
Joao Moreno 已提交
95 96
	}

J
Joao Moreno 已提交
97
	disposeTemplate(templateData: ITraitTemplateData): void {
J
Joao Moreno 已提交
98 99 100 101 102 103 104
		const index = firstIndex(this.renderedElements, el => el.templateData === templateData);

		if (index < 0) {
			return;
		}

		this.renderedElements.splice(index, 1);
J
Joao Moreno 已提交
105 106 107
	}
}

108
class Trait<T> implements ISpliceable<boolean>, IDisposable {
J
Joao Moreno 已提交
109

J
Joao Moreno 已提交
110 111 112
	/**
	 * Sorted indexes which have this trait.
	 */
J
Joao Moreno 已提交
113
	private indexes: number[];
J
Joao Moreno 已提交
114

J
Joao Moreno 已提交
115
	private _onChange = new Emitter<ITraitChangeEvent>();
J
Joao Moreno 已提交
116 117 118 119 120
	get onChange(): Event<ITraitChangeEvent> { return this._onChange.event; }

	get trait(): string { return this._trait; }

	@memoize
M
Matt Bierner 已提交
121 122
	get renderer(): TraitRenderer<T> {
		return new TraitRenderer<T>(this);
J
Joao Moreno 已提交
123
	}
J
Joao Moreno 已提交
124

J
Joao Moreno 已提交
125 126 127 128
	constructor(private _trait: string) {
		this.indexes = [];
	}

J
Joao Moreno 已提交
129 130
	splice(start: number, deleteCount: number, elements: boolean[]): void {
		const diff = elements.length - deleteCount;
J
Joao Moreno 已提交
131
		const end = start + deleteCount;
J
Joao Moreno 已提交
132 133
		const indexes = [
			...this.indexes.filter(i => i < start),
134
			...elements.map((hasTrait, i) => hasTrait ? i + start : -1).filter(i => i !== -1),
J
Joao Moreno 已提交
135 136
			...this.indexes.filter(i => i >= end).map(i => i + diff)
		];
J
Joao Moreno 已提交
137

J
Joao Moreno 已提交
138
		this.renderer.splice(start, deleteCount, elements.length);
J
Joao Moreno 已提交
139
		this.set(indexes);
J
Joao Moreno 已提交
140 141
	}

J
Joao Moreno 已提交
142
	renderIndex(index: number, container: HTMLElement): void {
A
Alex Dima 已提交
143
		DOM.toggleClass(container, this._trait, this.contains(index));
J
Joao Moreno 已提交
144 145
	}

J
Joao Moreno 已提交
146 147 148 149
	unrender(container: HTMLElement): void {
		DOM.removeClass(container, this._trait);
	}

J
Joao Moreno 已提交
150 151 152 153 154 155
	/**
	 * Sets the indexes which should have this trait.
	 *
	 * @param indexes Indexes which should have this trait.
	 * @return The old indexes which had this trait.
	 */
156
	set(indexes: number[], browserEvent?: UIEvent): number[] {
J
Joao Moreno 已提交
157 158
		const result = this.indexes;
		this.indexes = indexes;
J
Joao Moreno 已提交
159 160 161 162

		const toRender = disjunction(result, indexes);
		this.renderer.renderIndexes(toRender);

163
		this._onChange.fire({ indexes, browserEvent });
J
Joao Moreno 已提交
164
		return result;
J
Joao Moreno 已提交
165 166
	}

J
Joao Moreno 已提交
167 168 169 170
	get(): number[] {
		return this.indexes;
	}

J
Joao Moreno 已提交
171 172
	contains(index: number): boolean {
		return this.indexes.some(i => i === index);
J
Joao Moreno 已提交
173 174
	}

J
Joao Moreno 已提交
175 176 177
	dispose() {
		this._onChange = dispose(this._onChange);
	}
J
Joao Moreno 已提交
178 179
}

A
Alex Dima 已提交
180 181
class FocusTrait<T> extends Trait<T> {

J
Joao Moreno 已提交
182
	constructor() {
A
Alex Dima 已提交
183 184 185
		super('focused');
	}

J
Joao Moreno 已提交
186 187
	renderIndex(index: number, container: HTMLElement): void {
		super.renderIndex(index, container);
J
Joao Moreno 已提交
188 189 190 191 192 193

		if (this.contains(index)) {
			container.setAttribute('aria-selected', 'true');
		} else {
			container.removeAttribute('aria-selected');
		}
A
Alex Dima 已提交
194 195 196
	}
}

197 198 199 200 201 202 203 204 205 206
/**
 * The TraitSpliceable is used as a util class to be able
 * to preserve traits across splice calls, given an identity
 * provider.
 */
class TraitSpliceable<T> implements ISpliceable<T> {

	constructor(
		private trait: Trait<T>,
		private view: ListView<T>,
J
Joao Moreno 已提交
207
		private identityProvider?: IIdentityProvider<T>
208 209 210
	) { }

	splice(start: number, deleteCount: number, elements: T[]): void {
J
Joao Moreno 已提交
211
		if (!this.identityProvider) {
J
Joao Moreno 已提交
212
			return this.trait.splice(start, deleteCount, elements.map(() => false));
213 214
		}

J
Joao Moreno 已提交
215 216
		const pastElementsWithTrait = this.trait.get().map(i => this.identityProvider!.getId(this.view.element(i)).toString());
		const elementsWithTrait = elements.map(e => pastElementsWithTrait.indexOf(this.identityProvider!.getId(e).toString()) > -1);
217 218 219 220 221

		this.trait.splice(start, deleteCount, elementsWithTrait);
	}
}

J
Joao Moreno 已提交
222 223 224 225
function isInputElement(e: HTMLElement): boolean {
	return e.tagName === 'INPUT' || e.tagName === 'TEXTAREA';
}

226
class KeyboardController<T> implements IDisposable {
227

228
	private disposables: IDisposable[];
229
	private openController: IOpenController;
J
Joao Moreno 已提交
230 231 232

	constructor(
		private list: List<T>,
J
Joao Moreno 已提交
233 234
		private view: ListView<T>,
		options: IListOptions<T>
J
Joao Moreno 已提交
235
	) {
J
Joao Moreno 已提交
236
		const multipleSelectionSupport = !(options.multipleSelectionSupport === false);
237 238
		this.disposables = [];

239 240
		this.openController = options.openController || DefaultOpenController;

J
Joao Moreno 已提交
241
		const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown'))
J
Joao Moreno 已提交
242
			.filter(e => !isInputElement(e.target as HTMLElement))
J
Joao Moreno 已提交
243 244 245 246 247 248 249
			.map(e => new StandardKeyboardEvent(e));

		onKeyDown.filter(e => e.keyCode === KeyCode.Enter).on(this.onEnter, this, this.disposables);
		onKeyDown.filter(e => e.keyCode === KeyCode.UpArrow).on(this.onUpArrow, this, this.disposables);
		onKeyDown.filter(e => e.keyCode === KeyCode.DownArrow).on(this.onDownArrow, this, this.disposables);
		onKeyDown.filter(e => e.keyCode === KeyCode.PageUp).on(this.onPageUpArrow, this, this.disposables);
		onKeyDown.filter(e => e.keyCode === KeyCode.PageDown).on(this.onPageDownArrow, this, this.disposables);
J
Joao Moreno 已提交
250
		onKeyDown.filter(e => e.keyCode === KeyCode.Escape).on(this.onEscape, this, this.disposables);
J
Joao Moreno 已提交
251 252 253 254

		if (multipleSelectionSupport) {
			onKeyDown.filter(e => (platform.isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === KeyCode.KEY_A).on(this.onCtrlA, this, this.disposables);
		}
J
Joao Moreno 已提交
255 256
	}

257 258 259
	private onEnter(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
260
		this.list.setSelection(this.list.getFocus(), e.browserEvent);
261 262 263 264

		if (this.openController.shouldOpen(e.browserEvent)) {
			this.list.open(this.list.getFocus(), e.browserEvent);
		}
265 266 267 268 269
	}

	private onUpArrow(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
270
		this.list.focusPrevious(1, false, e.browserEvent);
271 272 273 274 275 276 277
		this.list.reveal(this.list.getFocus()[0]);
		this.view.domNode.focus();
	}

	private onDownArrow(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
278
		this.list.focusNext(1, false, e.browserEvent);
279 280 281 282 283 284 285
		this.list.reveal(this.list.getFocus()[0]);
		this.view.domNode.focus();
	}

	private onPageUpArrow(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
286
		this.list.focusPreviousPage(e.browserEvent);
287 288 289 290 291 292 293
		this.list.reveal(this.list.getFocus()[0]);
		this.view.domNode.focus();
	}

	private onPageDownArrow(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
294
		this.list.focusNextPage(e.browserEvent);
295 296 297 298
		this.list.reveal(this.list.getFocus()[0]);
		this.view.domNode.focus();
	}

J
Joao Moreno 已提交
299 300 301
	private onCtrlA(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
302
		this.list.setSelection(range(this.list.length), e.browserEvent);
J
Joao Moreno 已提交
303 304 305 306 307 308
		this.view.domNode.focus();
	}

	private onEscape(e: StandardKeyboardEvent): void {
		e.preventDefault();
		e.stopPropagation();
309
		this.list.setSelection([], e.browserEvent);
J
Joao Moreno 已提交
310 311 312
		this.view.domNode.focus();
	}

J
Joao Moreno 已提交
313
	dispose() {
314
		this.disposables = dispose(this.disposables);
J
Joao Moreno 已提交
315 316 317
	}
}

J
Joao Moreno 已提交
318 319 320 321 322
enum TypeLabelControllerState {
	Idle,
	Typing
}

323 324 325 326
export function mightProducePrintableCharacter(event: IKeyboardEvent): boolean {
	if (event.ctrlKey || event.metaKey || event.altKey) {
		return false;
	}
J
Joao Moreno 已提交
327

328 329 330 331
	return (event.keyCode >= KeyCode.KEY_A && event.keyCode <= KeyCode.KEY_Z)
		|| (event.keyCode >= KeyCode.KEY_0 && event.keyCode <= KeyCode.KEY_9)
		|| (event.keyCode >= KeyCode.US_SEMICOLON && event.keyCode <= KeyCode.US_QUOTE);
}
332

333
class TypeLabelController<T> implements IDisposable {
334

335
	private enabled = false;
J
Joao Moreno 已提交
336
	private state: TypeLabelControllerState = TypeLabelControllerState.Idle;
J
Joao Moreno 已提交
337 338 339 340

	private automaticKeyboardNavigation = true;
	private triggered = false;

341
	private enabledDisposables: IDisposable[] = [];
J
Joao Moreno 已提交
342 343 344 345 346
	private disposables: IDisposable[] = [];

	constructor(
		private list: List<T>,
		private view: ListView<T>,
J
Joao Moreno 已提交
347
		private keyboardNavigationLabelProvider: IKeyboardNavigationLabelProvider<T>
J
Joao Moreno 已提交
348
	) {
J
Joao Moreno 已提交
349
		this.updateOptions(list.options);
350 351
	}

J
Joao Moreno 已提交
352
	updateOptions(options: IListOptions<T>): void {
J
Joao Moreno 已提交
353 354 355
		const enableKeyboardNavigation = typeof options.enableKeyboardNavigation === 'undefined' ? true : !!options.enableKeyboardNavigation;

		if (enableKeyboardNavigation) {
356 357 358 359
			this.enable();
		} else {
			this.disable();
		}
J
Joao Moreno 已提交
360 361 362 363 364 365 366 367

		if (typeof options.automaticKeyboardNavigation !== 'undefined') {
			this.automaticKeyboardNavigation = options.automaticKeyboardNavigation;
		}
	}

	toggle(): void {
		this.triggered = !this.triggered;
368 369 370 371 372 373 374 375
	}

	private enable(): void {
		if (this.enabled) {
			return;
		}

		const onChar = Event.chain(domEvent(this.view.domNode, 'keydown'))
J
Joao Moreno 已提交
376
			.filter(e => !isInputElement(e.target as HTMLElement))
J
Joao Moreno 已提交
377
			.filter(() => this.automaticKeyboardNavigation || this.triggered)
J
Joao Moreno 已提交
378
			.map(event => new StandardKeyboardEvent(event))
379
			.filter(this.keyboardNavigationLabelProvider.mightProducePrintableCharacter ? e => this.keyboardNavigationLabelProvider.mightProducePrintableCharacter!(e) : e => mightProducePrintableCharacter(e))
J
Joao Moreno 已提交
380
			.forEach(e => { e.stopPropagation(); e.preventDefault(); })
J
Joao Moreno 已提交
381 382 383
			.map(event => event.browserEvent.key)
			.event;

J
Joao Moreno 已提交
384 385
		const onClear = Event.debounce<string, null>(onChar, () => null, 800);
		const onInput = Event.reduce<string | null, string | null>(Event.any(onChar, onClear), (r, i) => i === null ? null : ((r || '') + i));
J
Joao Moreno 已提交
386

387 388 389
		onInput(this.onInput, this, this.enabledDisposables);

		this.enabled = true;
J
Joao Moreno 已提交
390
		this.triggered = false;
391 392 393 394 395 396 397 398 399
	}

	private disable(): void {
		if (!this.enabled) {
			return;
		}

		this.enabledDisposables = dispose(this.enabledDisposables);
		this.enabled = false;
J
Joao Moreno 已提交
400
		this.triggered = false;
J
Joao Moreno 已提交
401 402 403 404 405
	}

	private onInput(word: string | null): void {
		if (!word) {
			this.state = TypeLabelControllerState.Idle;
J
Joao Moreno 已提交
406
			this.triggered = false;
J
Joao Moreno 已提交
407 408 409 410 411 412 413 414 415 416
			return;
		}

		const focus = this.list.getFocus();
		const start = focus.length > 0 ? focus[0] : 0;
		const delta = this.state === TypeLabelControllerState.Idle ? 1 : 0;
		this.state = TypeLabelControllerState.Typing;

		for (let i = 0; i < this.list.length; i++) {
			const index = (start + i + delta) % this.list.length;
J
Joao Moreno 已提交
417
			const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index));
418
			const labelStr = label && label.toString();
J
Joao Moreno 已提交
419

420
			if (typeof labelStr === 'undefined' || matchesPrefix(word, labelStr)) {
J
Joao Moreno 已提交
421 422 423 424 425 426 427 428
				this.list.setFocus([index]);
				this.list.reveal(index);
				return;
			}
		}
	}

	dispose() {
429
		this.disable();
J
Joao Moreno 已提交
430 431 432 433
		this.disposables = dispose(this.disposables);
	}
}

J
Joao Moreno 已提交
434 435 436 437 438 439 440 441 442 443
class DOMFocusController<T> implements IDisposable {

	private disposables: IDisposable[] = [];

	constructor(
		private list: List<T>,
		private view: ListView<T>
	) {
		this.disposables = [];

J
Joao Moreno 已提交
444
		const onKeyDown = Event.chain(domEvent(view.domNode, 'keydown'))
J
Joao Moreno 已提交
445 446 447
			.filter(e => !isInputElement(e.target as HTMLElement))
			.map(e => new StandardKeyboardEvent(e));

J
Joao Moreno 已提交
448 449
		onKeyDown.filter(e => e.keyCode === KeyCode.Tab && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey)
			.on(this.onTab, this, this.disposables);
J
Joao Moreno 已提交
450 451 452 453 454 455 456 457 458 459 460 461 462 463
	}

	private onTab(e: StandardKeyboardEvent): void {
		if (e.target !== this.view.domNode) {
			return;
		}

		const focus = this.list.getFocus();

		if (focus.length === 0) {
			return;
		}

		const focusedDomElement = this.view.domElement(focus[0]);
J
Joao Moreno 已提交
464 465 466 467 468

		if (!focusedDomElement) {
			return;
		}

J
Joao Moreno 已提交
469 470
		const tabIndexElement = focusedDomElement.querySelector('[tabIndex]');

471
		if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) {
I
isidor 已提交
472 473 474 475 476
			return;
		}

		const style = window.getComputedStyle(tabIndexElement);
		if (style.visibility === 'hidden' || style.display === 'none') {
J
Joao Moreno 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489
			return;
		}

		e.preventDefault();
		e.stopPropagation();
		tabIndexElement.focus();
	}

	dispose() {
		this.disposables = dispose(this.disposables);
	}
}

J
Joao Moreno 已提交
490
export function isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean {
J
Joao Moreno 已提交
491
	return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
J
Joao Moreno 已提交
492 493
}

J
Joao Moreno 已提交
494
export function isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean {
J
Joao Moreno 已提交
495
	return event.browserEvent.shiftKey;
J
Joao Moreno 已提交
496 497
}

498 499
function isMouseRightClick(event: UIEvent): boolean {
	return event instanceof MouseEvent && event.button === 2;
J
Joao Moreno 已提交
500 501
}

J
Joao Moreno 已提交
502 503 504 505 506
const DefaultMultipleSelectionContoller = {
	isSelectionSingleChangeEvent,
	isSelectionRangeChangeEvent
};

J
Joao Moreno 已提交
507
const DefaultOpenController: IOpenController = {
B
Benjamin Pasero 已提交
508 509
	shouldOpen: (event: UIEvent) => {
		if (event instanceof MouseEvent) {
510
			return !isMouseRightClick(event);
B
Benjamin Pasero 已提交
511 512 513 514
		}

		return true;
	}
J
Joao Moreno 已提交
515
};
516

517
export class MouseController<T> implements IDisposable {
J
Joao Moreno 已提交
518

J
Joao Moreno 已提交
519
	private multipleSelectionSupport: boolean;
J
Joao Moreno 已提交
520
	readonly multipleSelectionController: IMultipleSelectionController<T>;
521
	private openController: IOpenController;
J
Joao Moreno 已提交
522
	private mouseSupport: boolean;
J
Joao Moreno 已提交
523
	private disposables: IDisposable[] = [];
524

525 526
	constructor(protected list: List<T>) {
		this.multipleSelectionSupport = !(list.options.multipleSelectionSupport === false);
J
Joao Moreno 已提交
527 528

		if (this.multipleSelectionSupport) {
529
			this.multipleSelectionController = list.options.multipleSelectionController || DefaultMultipleSelectionContoller;
J
Joao Moreno 已提交
530
		}
J
Joao Moreno 已提交
531

532
		this.openController = list.options.openController || DefaultOpenController;
J
Joao Moreno 已提交
533 534 535 536 537 538 539 540 541
		this.mouseSupport = typeof list.options.mouseSupport === 'undefined' || !!list.options.mouseSupport;

		if (this.mouseSupport) {
			list.onMouseDown(this.onMouseDown, this, this.disposables);
			list.onContextMenu(this.onContextMenu, this, this.disposables);
			list.onMouseDblClick(this.onDoubleClick, this, this.disposables);
			list.onTouchStart(this.onMouseDown, this, this.disposables);
			Gesture.addTarget(list.getHTMLElement());
		}
J
Joao Moreno 已提交
542

543
		list.onMouseClick(this.onPointer, this, this.disposables);
544
		list.onMouseMiddleClick(this.onPointer, this, this.disposables);
545
		list.onTap(this.onPointer, this, this.disposables);
546 547
	}

J
Joao Moreno 已提交
548
	protected isSelectionSingleChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean {
J
Joao Moreno 已提交
549 550
		if (this.multipleSelectionController) {
			return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
551 552 553 554 555
		}

		return platform.isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
	}

J
Joao Moreno 已提交
556
	protected isSelectionRangeChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean {
J
Joao Moreno 已提交
557 558 559 560
		if (this.multipleSelectionController) {
			return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
		}

561 562 563 564 565 566 567
		return event.browserEvent.shiftKey;
	}

	private isSelectionChangeEvent(event: IListMouseEvent<any> | IListTouchEvent<any>): boolean {
		return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
	}

J
Joao Moreno 已提交
568
	private onMouseDown(e: IListMouseEvent<T> | IListTouchEvent<T>): void {
J
Joao Moreno 已提交
569
		if (document.activeElement !== e.browserEvent.target) {
570
			this.list.domFocus();
J
Joao Moreno 已提交
571
		}
J
Joao Moreno 已提交
572 573
	}

574
	private onContextMenu(e: IListContextMenuEvent<T>): void {
J
Joao Moreno 已提交
575 576 577
		const focus = typeof e.index === 'undefined' ? [] : [e.index];
		this.list.setFocus(focus, e.browserEvent);
	}
J
Joao Moreno 已提交
578

579
	protected onPointer(e: IListMouseEvent<T>): void {
J
Joao Moreno 已提交
580 581 582 583
		if (!this.mouseSupport) {
			return;
		}

584 585 586 587
		if (isInputElement(e.browserEvent.target as HTMLElement)) {
			return;
		}

J
Joao Moreno 已提交
588
		let reference = this.list.getFocus()[0];
589 590
		const selection = this.list.getSelection();
		reference = reference === undefined ? selection[0] : reference;
J
Joao Moreno 已提交
591

J
Joao Moreno 已提交
592 593 594 595 596 597 598 599
		const focus = e.index;

		if (typeof focus === 'undefined') {
			this.list.setFocus([], e.browserEvent);
			this.list.setSelection([], e.browserEvent);
			return;
		}

600
		if (this.multipleSelectionSupport && this.isSelectionRangeChangeEvent(e)) {
J
Joao Moreno 已提交
601 602 603
			return this.changeSelection(e, reference);
		}

604
		if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) {
J
Joao Moreno 已提交
605 606
			return this.changeSelection(e, reference);
		}
607

J
Joao Moreno 已提交
608 609
		this.list.setFocus([focus], e.browserEvent);

J
Joao Moreno 已提交
610
		if (!isMouseRightClick(e.browserEvent)) {
611
			this.list.setSelection([focus], e.browserEvent);
612 613 614 615

			if (this.openController.shouldOpen(e.browserEvent)) {
				this.list.open([focus], e.browserEvent);
			}
616
		}
J
Joao Moreno 已提交
617
	}
J
Joao Moreno 已提交
618

J
Joao Moreno 已提交
619
	private onDoubleClick(e: IListMouseEvent<T>): void {
620 621 622 623
		if (isInputElement(e.browserEvent.target as HTMLElement)) {
			return;
		}

624
		if (this.multipleSelectionSupport && this.isSelectionChangeEvent(e)) {
J
Joao Moreno 已提交
625 626
			return;
		}
627

J
Joao Moreno 已提交
628
		const focus = this.list.getFocus();
629
		this.list.setSelection(focus, e.browserEvent);
J
Joao Moreno 已提交
630
		this.list.pin(focus);
J
Joao Moreno 已提交
631
	}
632

J
Joao Moreno 已提交
633
	private changeSelection(e: IListMouseEvent<T> | IListTouchEvent<T>, reference: number | undefined): void {
J
Joao Moreno 已提交
634
		const focus = e.index!;
635

636
		if (this.isSelectionRangeChangeEvent(e) && reference !== undefined) {
J
Joao Moreno 已提交
637 638
			const min = Math.min(reference, focus);
			const max = Math.max(reference, focus);
J
Joao Moreno 已提交
639
			const rangeSelection = range(min, max + 1);
J
Joao Moreno 已提交
640 641
			const selection = this.list.getSelection();
			const contiguousRange = getContiguousRangeContaining(disjunction(selection, [reference]), reference);
642

J
Joao Moreno 已提交
643 644
			if (contiguousRange.length === 0) {
				return;
645 646
			}

J
Joao Moreno 已提交
647
			const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
648
			this.list.setSelection(newSelection, e.browserEvent);
J
Joao Moreno 已提交
649

650
		} else if (this.isSelectionSingleChangeEvent(e)) {
J
Joao Moreno 已提交
651 652 653 654
			const selection = this.list.getSelection();
			const newSelection = selection.filter(i => i !== focus);

			if (selection.length === newSelection.length) {
655
				this.list.setSelection([...newSelection, focus], e.browserEvent);
J
Joao Moreno 已提交
656
			} else {
657
				this.list.setSelection(newSelection, e.browserEvent);
J
Joao Moreno 已提交
658 659
			}
		}
660 661 662 663 664 665 666
	}

	dispose() {
		this.disposables = dispose(this.disposables);
	}
}

J
Joao Moreno 已提交
667 668 669
export interface IMultipleSelectionController<T> {
	isSelectionSingleChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean;
	isSelectionRangeChangeEvent(event: IListMouseEvent<T> | IListTouchEvent<T>): boolean;
670 671
}

672 673 674 675
export interface IOpenController {
	shouldOpen(event: UIEvent): boolean;
}

676 677 678 679
export interface IStyleController {
	style(styles: IListStyles): void;
}

680 681 682 683 684 685 686 687 688 689
export interface IAccessibilityProvider<T> {

	/**
	 * Given an element in the tree, return the ARIA label that should be associated with the
	 * item. This helps screen readers to provide a meaningful label for the currently focused
	 * tree element.
	 *
	 * Returning null will not disable ARIA for the element. Instead it is up to the screen reader
	 * to compute a meaningful label based on the contents of the element in the DOM
	 *
J
Joao Moreno 已提交
690
	 * See also: https://www.w3.org/TR/wai-aria/#aria-label
691 692
	 */
	getAriaLabel(element: T): string | null;
J
Joao Moreno 已提交
693 694 695 696 697

	/**
	 * https://www.w3.org/TR/wai-aria/#aria-level
	 */
	getAriaLevel?(element: T): number | undefined;
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
export class DefaultStyleController implements IStyleController {

	constructor(private styleElement: HTMLStyleElement, private selectorSuffix?: string) { }

	style(styles: IListStyles): void {
		const suffix = this.selectorSuffix ? `.${this.selectorSuffix}` : '';
		const content: string[] = [];

		if (styles.listFocusBackground) {
			content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
			content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case!
		}

		if (styles.listFocusForeground) {
			content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
		}

		if (styles.listActiveSelectionBackground) {
			content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
			content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case!
		}

		if (styles.listActiveSelectionForeground) {
			content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
		}

		if (styles.listFocusAndSelectionBackground) {
J
Joao Moreno 已提交
727
			content.push(`
J
Joao Moreno 已提交
728
				.monaco-drag-image,
J
Joao Moreno 已提交
729 730
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
731 732 733
		}

		if (styles.listFocusAndSelectionForeground) {
J
Joao Moreno 已提交
734
			content.push(`
J
Joao Moreno 已提交
735
				.monaco-drag-image,
J
Joao Moreno 已提交
736 737
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
738 739
		}

740 741 742 743 744
		if (styles.listInactiveFocusBackground) {
			content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
			content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case!
		}

745 746 747 748 749 750 751 752 753 754
		if (styles.listInactiveSelectionBackground) {
			content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
			content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case!
		}

		if (styles.listInactiveSelectionForeground) {
			content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
		}

		if (styles.listHoverBackground) {
J
Joao Moreno 已提交
755
			content.push(`.monaco-list${suffix}:not(.drop-target) .monaco-list-row:hover:not(.selected):not(.focused) { background-color:  ${styles.listHoverBackground}; }`);
756 757 758
		}

		if (styles.listHoverForeground) {
J
Joao Moreno 已提交
759
			content.push(`.monaco-list${suffix} .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
760 761 762 763 764 765 766
		}

		if (styles.listSelectionOutline) {
			content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
		}

		if (styles.listFocusOutline) {
J
Joao Moreno 已提交
767
			content.push(`
J
Joao Moreno 已提交
768
				.monaco-drag-image,
J
Joao Moreno 已提交
769 770
				.monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
771 772 773 774 775 776 777 778 779 780
		}

		if (styles.listInactiveFocusOutline) {
			content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
		}

		if (styles.listHoverOutline) {
			content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
		}

J
Joao Moreno 已提交
781 782 783 784 785 786
		if (styles.listDropBackground) {
			content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; }
			`);
		}
J
Joao Moreno 已提交
787

J
Joao Moreno 已提交
788 789
		if (styles.listFilterWidgetBackground) {
			content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`);
J
Joao Moreno 已提交
790 791
		}

J
Joao Moreno 已提交
792 793
		if (styles.listFilterWidgetOutline) {
			content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`);
J
Joao Moreno 已提交
794 795
		}

J
Joao Moreno 已提交
796 797
		if (styles.listFilterWidgetNoMatchesOutline) {
			content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`);
798 799
		}

J
Joao Moreno 已提交
800
		if (styles.listMatchesShadow) {
J
Joao Moreno 已提交
801
			content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`);
J
Joao Moreno 已提交
802 803
		}

804 805 806 807 808 809 810
		const newStyles = content.join('\n');
		if (newStyles !== this.styleElement.innerHTML) {
			this.styleElement.innerHTML = newStyles;
		}
	}
}

J
Joao Moreno 已提交
811 812
export interface IListOptions<T> extends IListStyles {
	readonly identityProvider?: IIdentityProvider<T>;
813
	readonly dnd?: IListDragAndDrop<T>;
814
	readonly enableKeyboardNavigation?: boolean;
J
Joao Moreno 已提交
815
	readonly automaticKeyboardNavigation?: boolean;
J
Joao Moreno 已提交
816
	readonly keyboardNavigationLabelProvider?: IKeyboardNavigationLabelProvider<T>;
817
	readonly ariaRole?: ListAriaRootRole;
J
Joao Moreno 已提交
818 819 820 821 822 823 824 825 826 827 828 829 830 831
	readonly ariaLabel?: string;
	readonly keyboardSupport?: boolean;
	readonly multipleSelectionSupport?: boolean;
	readonly multipleSelectionController?: IMultipleSelectionController<T>;
	readonly openController?: IOpenController;
	readonly styleController?: IStyleController;
	readonly accessibilityProvider?: IAccessibilityProvider<T>;

	// list view options
	readonly useShadows?: boolean;
	readonly verticalScrollMode?: ScrollbarVisibility;
	readonly setRowLineHeight?: boolean;
	readonly supportDynamicHeights?: boolean;
	readonly mouseSupport?: boolean;
832
	readonly horizontalScrolling?: boolean;
J
Joao Moreno 已提交
833
	readonly ariaSetProvider?: IAriaSetProvider<T>;
J
Joao Moreno 已提交
834 835
}

836 837
export interface IListStyles {
	listFocusBackground?: Color;
838
	listFocusForeground?: Color;
839 840 841 842 843
	listActiveSelectionBackground?: Color;
	listActiveSelectionForeground?: Color;
	listFocusAndSelectionBackground?: Color;
	listFocusAndSelectionForeground?: Color;
	listInactiveSelectionBackground?: Color;
844
	listInactiveSelectionForeground?: Color;
M
Martin Aeschlimann 已提交
845
	listInactiveFocusBackground?: Color;
846
	listHoverBackground?: Color;
847
	listHoverForeground?: Color;
848 849
	listDropBackground?: Color;
	listFocusOutline?: Color;
850 851 852
	listInactiveFocusOutline?: Color;
	listSelectionOutline?: Color;
	listHoverOutline?: Color;
J
Joao Moreno 已提交
853 854 855
	listFilterWidgetBackground?: Color;
	listFilterWidgetOutline?: Color;
	listFilterWidgetNoMatchesOutline?: Color;
J
Joao Moreno 已提交
856
	listMatchesShadow?: Color;
857 858 859 860 861 862 863 864 865 866 867 868 869
}

const defaultStyles: IListStyles = {
	listFocusBackground: Color.fromHex('#073655'),
	listActiveSelectionBackground: Color.fromHex('#0E639C'),
	listActiveSelectionForeground: Color.fromHex('#FFFFFF'),
	listFocusAndSelectionBackground: Color.fromHex('#094771'),
	listFocusAndSelectionForeground: Color.fromHex('#FFFFFF'),
	listInactiveSelectionBackground: Color.fromHex('#3F3F46'),
	listHoverBackground: Color.fromHex('#2A2D2E'),
	listDropBackground: Color.fromHex('#383B3D')
};

J
Joao Moreno 已提交
870
const DefaultOptions = {
871
	keyboardSupport: true,
I
isidor 已提交
872
	mouseSupport: true,
J
Joao Moreno 已提交
873 874 875 876 877 878
	multipleSelectionSupport: true,
	dnd: {
		getDragURI() { return null; },
		onDragStart(): void { },
		onDragOver() { return false; },
		drop() { }
879 880
	},
	ariaRootRole: ListAriaRootRole.TREE
881
};
J
Joao Moreno 已提交
882

J
Joao Moreno 已提交
883 884
// TODO@Joao: move these utils into a SortedArray class

885 886 887 888 889 890 891
function getContiguousRangeContaining(range: number[], value: number): number[] {
	const index = range.indexOf(value);

	if (index === -1) {
		return [];
	}

M
Matt Bierner 已提交
892
	const result: number[] = [];
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
	let i = index - 1;
	while (i >= 0 && range[i] === value - (index - i)) {
		result.push(range[i--]);
	}

	result.reverse();
	i = index;
	while (i < range.length && range[i] === value + (i - index)) {
		result.push(range[i++]);
	}

	return result;
}

/**
 * Given two sorted collections of numbers, returns the intersection
 * betweem them (OR).
 */
function disjunction(one: number[], other: number[]): number[] {
M
Matt Bierner 已提交
912
	const result: number[] = [];
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
	let i = 0, j = 0;

	while (i < one.length || j < other.length) {
		if (i >= one.length) {
			result.push(other[j++]);
		} else if (j >= other.length) {
			result.push(one[i++]);
		} else if (one[i] === other[j]) {
			result.push(one[i]);
			i++;
			j++;
			continue;
		} else if (one[i] < other[j]) {
			result.push(one[i++]);
		} else {
			result.push(other[j++]);
		}
	}

	return result;
}

/**
 * Given two sorted collections of numbers, returns the relative
 * complement between them (XOR).
 */
function relativeComplement(one: number[], other: number[]): number[] {
M
Matt Bierner 已提交
940
	const result: number[] = [];
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
	let i = 0, j = 0;

	while (i < one.length || j < other.length) {
		if (i >= one.length) {
			result.push(other[j++]);
		} else if (j >= other.length) {
			result.push(one[i++]);
		} else if (one[i] === other[j]) {
			i++;
			j++;
			continue;
		} else if (one[i] < other[j]) {
			result.push(one[i++]);
		} else {
			j++;
		}
	}

	return result;
}

962 963
const numericSort = (a: number, b: number) => a - b;

J
Joao Moreno 已提交
964
class PipelineRenderer<T> implements IListRenderer<T, any> {
J
Joao Moreno 已提交
965 966 967

	constructor(
		private _templateId: string,
J
Joao Moreno 已提交
968
		private renderers: IListRenderer<any /* TODO@joao */, any>[]
J
Joao Moreno 已提交
969 970 971 972 973 974 975 976 977 978 979
	) { }

	get templateId(): string {
		return this._templateId;
	}

	renderTemplate(container: HTMLElement): any[] {
		return this.renderers.map(r => r.renderTemplate(container));
	}

	renderElement(element: T, index: number, templateData: any[]): void {
J
Joao Moreno 已提交
980 981 982 983 984
		let i = 0;

		for (const renderer of this.renderers) {
			renderer.renderElement(element, index, templateData[i++]);
		}
J
Joao Moreno 已提交
985 986
	}

J
Joao Moreno 已提交
987 988 989 990
	disposeElement(element: T, index: number, templateData: any[]): void {
		let i = 0;

		for (const renderer of this.renderers) {
J
Joao Moreno 已提交
991
			if (renderer.disposeElement) {
J
fix npe  
Joao Moreno 已提交
992
				renderer.disposeElement(element, index, templateData[i]);
J
Joao Moreno 已提交
993
			}
J
fix npe  
Joao Moreno 已提交
994 995

			i += 1;
J
Joao Moreno 已提交
996 997 998
		}
	}

J
Joao Moreno 已提交
999
	disposeTemplate(templateData: any[]): void {
J
Joao Moreno 已提交
1000 1001 1002
		let i = 0;

		for (const renderer of this.renderers) {
J
Joao Moreno 已提交
1003
			renderer.disposeTemplate(templateData[i++]);
J
Joao Moreno 已提交
1004
		}
J
Joao Moreno 已提交
1005 1006 1007
	}
}

1008 1009 1010 1011
class AccessibiltyRenderer<T> implements IListRenderer<T, HTMLElement> {

	templateId: string = 'a18n';

J
Joao Moreno 已提交
1012
	constructor(private accessibilityProvider: IAccessibilityProvider<T>) { }
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

	renderTemplate(container: HTMLElement): HTMLElement {
		return container;
	}

	renderElement(element: T, index: number, container: HTMLElement): void {
		const ariaLabel = this.accessibilityProvider.getAriaLabel(element);

		if (ariaLabel) {
			container.setAttribute('aria-label', ariaLabel);
		} else {
			container.removeAttribute('aria-label');
		}
J
Joao Moreno 已提交
1026 1027 1028 1029 1030 1031 1032 1033

		const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);

		if (typeof ariaLevel === 'number') {
			container.setAttribute('aria-level', `${ariaLevel}`);
		} else {
			container.removeAttribute('aria-level');
		}
1034 1035 1036 1037 1038 1039 1040
	}

	disposeTemplate(templateData: any): void {
		// noop
	}
}

J
Joao Moreno 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
class ListViewDragAndDrop<T> implements IListViewDragAndDrop<T> {

	constructor(private list: List<T>, private dnd: IListDragAndDrop<T>) { }

	getDragElements(element: T): T[] {
		const selection = this.list.getSelectedElements();
		const elements = selection.indexOf(element) > -1 ? selection : [element];
		return elements;
	}

	getDragURI(element: T): string | null {
		return this.dnd.getDragURI(element);
	}

	getDragLabel?(elements: T[]): string | undefined {
J
Joao Moreno 已提交
1056 1057 1058 1059 1060
		if (this.dnd.getDragLabel) {
			return this.dnd.getDragLabel(elements);
		}

		return undefined;
J
Joao Moreno 已提交
1061 1062 1063
	}

	onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void {
J
Joao Moreno 已提交
1064 1065 1066
		if (this.dnd.onDragStart) {
			this.dnd.onDragStart(data, originalEvent);
		}
J
Joao Moreno 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
	}

	onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | IListDragOverReaction {
		return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent);
	}

	drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void {
		this.dnd.drop(data, targetElement, targetIndex, originalEvent);
	}
}

1078 1079
export interface IListOptionsUpdate {
	readonly enableKeyboardNavigation?: boolean;
J
Joao Moreno 已提交
1080
	readonly automaticKeyboardNavigation?: boolean;
1081 1082
}

1083
export class List<T> implements ISpliceable<T>, IDisposable {
J
Joao Moreno 已提交
1084

A
Alex Dima 已提交
1085 1086
	private focus: Trait<T>;
	private selection: Trait<T>;
J
Joao Moreno 已提交
1087
	private eventBufferer = new EventBufferer();
J
Joao Moreno 已提交
1088
	private view: ListView<T>;
1089
	private spliceable: ISpliceable<T>;
1090
	private styleElement: HTMLStyleElement;
1091
	private styleController: IStyleController;
J
Joao Moreno 已提交
1092
	private typeLabelController?: TypeLabelController<T>;
1093

J
Joao Moreno 已提交
1094 1095
	protected disposables: IDisposable[];

J
Joao Moreno 已提交
1096
	@memoize get onFocusChange(): Event<IListEvent<T>> {
J
Joao Moreno 已提交
1097
		return Event.map(this.eventBufferer.wrapEvent(this.focus.onChange), e => this.toListEvent(e));
J
Joao Moreno 已提交
1098 1099
	}

J
Joao Moreno 已提交
1100
	@memoize get onSelectionChange(): Event<IListEvent<T>> {
J
Joao Moreno 已提交
1101
		return Event.map(this.eventBufferer.wrapEvent(this.selection.onChange), e => this.toListEvent(e));
J
Joao Moreno 已提交
1102 1103
	}

J
Joao Moreno 已提交
1104 1105
	private _onDidOpen = new Emitter<IListEvent<T>>();
	readonly onDidOpen: Event<IListEvent<T>> = this._onDidOpen.event;
J
Joao Moreno 已提交
1106

J
Joao Moreno 已提交
1107 1108
	private _onPin = new Emitter<number[]>();
	@memoize get onPin(): Event<IListEvent<T>> {
J
Joao Moreno 已提交
1109
		return Event.map(this._onPin.event, indexes => this.toListEvent({ indexes }));
J
Joao Moreno 已提交
1110 1111
	}

J
Joao Moreno 已提交
1112
	get onDidScroll(): Event<void> { return this.view.onDidScroll; }
J
Joao Moreno 已提交
1113 1114
	get onMouseClick(): Event<IListMouseEvent<T>> { return this.view.onMouseClick; }
	get onMouseDblClick(): Event<IListMouseEvent<T>> { return this.view.onMouseDblClick; }
1115
	get onMouseMiddleClick(): Event<IListMouseEvent<T>> { return this.view.onMouseMiddleClick; }
J
Joao Moreno 已提交
1116 1117 1118 1119 1120 1121 1122 1123
	get onMouseUp(): Event<IListMouseEvent<T>> { return this.view.onMouseUp; }
	get onMouseDown(): Event<IListMouseEvent<T>> { return this.view.onMouseDown; }
	get onMouseOver(): Event<IListMouseEvent<T>> { return this.view.onMouseOver; }
	get onMouseMove(): Event<IListMouseEvent<T>> { return this.view.onMouseMove; }
	get onMouseOut(): Event<IListMouseEvent<T>> { return this.view.onMouseOut; }
	get onTouchStart(): Event<IListTouchEvent<T>> { return this.view.onTouchStart; }
	get onTap(): Event<IListGestureEvent<T>> { return this.view.onTap; }

J
Joao Moreno 已提交
1124 1125
	private didJustPressContextMenuKey: boolean = false;
	@memoize get onContextMenu(): Event<IListContextMenuEvent<T>> {
J
Joao Moreno 已提交
1126
		const fromKeydown = Event.chain(domEvent(this.view.domNode, 'keydown'))
J
Joao Moreno 已提交
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
			.map(e => new StandardKeyboardEvent(e))
			.filter(e => this.didJustPressContextMenuKey = e.keyCode === KeyCode.ContextMenu || (e.shiftKey && e.keyCode === KeyCode.F10))
			.filter(e => { e.preventDefault(); e.stopPropagation(); return false; })
			.map(event => {
				const index = this.getFocus()[0];
				const element = this.view.element(index);
				const anchor = this.view.domElement(index) || undefined;
				return { index, element, anchor, browserEvent: event.browserEvent };
			})
			.event;

J
Joao Moreno 已提交
1138
		const fromKeyup = Event.chain(domEvent(this.view.domNode, 'keyup'))
J
Joao Moreno 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
			.filter(() => {
				const didJustPressContextMenuKey = this.didJustPressContextMenuKey;
				this.didJustPressContextMenuKey = false;
				return didJustPressContextMenuKey;
			})
			.filter(() => this.getFocus().length > 0)
			.map(browserEvent => {
				const index = this.getFocus()[0];
				const element = this.view.element(index);
				const anchor = this.view.domElement(index) || undefined;
				return { index, element, anchor, browserEvent };
			})
			.filter(({ anchor }) => !!anchor)
			.event;

J
Joao Moreno 已提交
1154
		const fromMouse = Event.chain(this.view.onContextMenu)
J
Joao Moreno 已提交
1155 1156 1157 1158
			.filter(() => !this.didJustPressContextMenuKey)
			.map(({ element, index, browserEvent }) => ({ element, index, anchor: { x: browserEvent.clientX + 1, y: browserEvent.clientY }, browserEvent }))
			.event;

J
Joao Moreno 已提交
1159
		return Event.any<IListContextMenuEvent<T>>(fromKeydown, fromKeyup, fromMouse);
J
Joao Moreno 已提交
1160 1161
	}

J
Joao Moreno 已提交
1162 1163 1164
	get onKeyDown(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keydown'); }
	get onKeyUp(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keyup'); }
	get onKeyPress(): Event<KeyboardEvent> { return domEvent(this.view.domNode, 'keypress'); }
J
Joao Moreno 已提交
1165

1166 1167
	readonly onDidFocus: Event<void>;
	readonly onDidBlur: Event<void>;
1168

1169 1170
	private _onDidDispose = new Emitter<void>();
	get onDidDispose(): Event<void> { return this._onDidDispose.event; }
1171

J
Joao Moreno 已提交
1172 1173
	constructor(
		container: HTMLElement,
J
Joao Moreno 已提交
1174
		virtualDelegate: IListVirtualDelegate<T>,
J
Joao Moreno 已提交
1175
		renderers: IListRenderer<any /* TODO@joao */, any>[],
1176
		private _options: IListOptions<T> = DefaultOptions
J
Joao Moreno 已提交
1177
	) {
J
Joao Moreno 已提交
1178
		this.focus = new FocusTrait();
J
Joao Moreno 已提交
1179
		this.selection = new Trait('selected');
1180

1181
		mixin(_options, defaultStyles, false);
J
Joao Moreno 已提交
1182

1183 1184
		const baseRenderers: IListRenderer<T, ITraitTemplateData>[] = [this.focus.renderer, this.selection.renderer];

1185 1186
		if (_options.accessibilityProvider) {
			baseRenderers.push(new AccessibiltyRenderer<T>(_options.accessibilityProvider));
1187 1188 1189
		}

		renderers = renderers.map(r => new PipelineRenderer(r.templateId, [...baseRenderers, r]));
J
Joao Moreno 已提交
1190

J
Joao Moreno 已提交
1191
		const viewOptions: IListViewOptions<T> = {
1192 1193
			..._options,
			dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd)
J
Joao Moreno 已提交
1194 1195 1196
		};

		this.view = new ListView(container, virtualDelegate, renderers, viewOptions);
1197 1198 1199 1200 1201 1202 1203

		if (typeof _options.ariaRole !== 'string') {
			this.view.domNode.setAttribute('role', ListAriaRootRole.TREE);
		} else {
			this.view.domNode.setAttribute('role', _options.ariaRole);
		}

1204 1205
		this.styleElement = DOM.createStyleSheet(this.view.domNode);

J
Joao Moreno 已提交
1206
		this.styleController = _options.styleController || new DefaultStyleController(this.styleElement, this.view.domId);
1207

1208
		this.spliceable = new CombinedSpliceable([
1209 1210
			new TraitSpliceable(this.focus, this.view, _options.identityProvider),
			new TraitSpliceable(this.selection, this.view, _options.identityProvider),
1211 1212 1213
			this.view
		]);

1214
		this.disposables = [this.focus, this.selection, this.view, this._onDidDispose];
1215

J
Joao Moreno 已提交
1216 1217
		this.onDidFocus = Event.map(domEvent(this.view.domNode, 'focus', true), () => null!);
		this.onDidBlur = Event.map(domEvent(this.view.domNode, 'blur', true), () => null!);
1218

J
Joao Moreno 已提交
1219 1220
		this.disposables.push(new DOMFocusController(this, this.view));

1221 1222
		if (typeof _options.keyboardSupport !== 'boolean' || _options.keyboardSupport) {
			const controller = new KeyboardController(this, this.view, _options);
1223
			this.disposables.push(controller);
1224 1225
		}

1226
		if (_options.keyboardNavigationLabelProvider) {
J
Joao Moreno 已提交
1227 1228
			this.typeLabelController = new TypeLabelController(this, this.view, _options.keyboardNavigationLabelProvider);
			this.disposables.push(this.typeLabelController);
J
Joao Moreno 已提交
1229 1230
		}

J
Joao Moreno 已提交
1231
		this.disposables.push(this.createMouseController(_options));
1232

J
Joao Moreno 已提交
1233
		this.onFocusChange(this._onFocusChange, this, this.disposables);
1234
		this.onSelectionChange(this._onSelectionChange, this, this.disposables);
J
João Moreno 已提交
1235

1236 1237
		if (_options.ariaLabel) {
			this.view.domNode.setAttribute('aria-label', localize('aria list', "{0}. Use the navigation keys to navigate.", _options.ariaLabel));
J
João Moreno 已提交
1238
		}
1239

1240 1241 1242
		this.style(_options);
	}

1243 1244 1245 1246
	protected createMouseController(options: IListOptions<T>): MouseController<T> {
		return new MouseController(this);
	}

1247 1248
	updateOptions(optionsUpdate: IListOptionsUpdate = {}): void {
		this._options = { ...this._options, ...optionsUpdate };
J
Joao Moreno 已提交
1249 1250 1251 1252

		if (this.typeLabelController) {
			this.typeLabelController.updateOptions(this._options);
		}
1253 1254 1255 1256
	}

	get options(): IListOptions<T> {
		return this._options;
J
Joao Moreno 已提交
1257 1258
	}

J
Joao Moreno 已提交
1259
	splice(start: number, deleteCount: number, elements: T[] = []): void {
J
Joao Moreno 已提交
1260 1261 1262 1263 1264 1265 1266 1267
		if (start < 0 || start > this.view.length) {
			throw new Error(`Invalid start index: ${start}`);
		}

		if (deleteCount < 0) {
			throw new Error(`Invalid delete count: ${deleteCount}`);
		}

J
Joao Moreno 已提交
1268 1269 1270 1271
		if (deleteCount === 0 && elements.length === 0) {
			return;
		}

1272
		this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements));
J
Joao Moreno 已提交
1273 1274
	}

J
Joao Moreno 已提交
1275 1276 1277 1278
	updateWidth(index: number): void {
		this.view.updateWidth(index);
	}

J
Joao Moreno 已提交
1279 1280 1281 1282
	element(index: number): T {
		return this.view.element(index);
	}

J
Joao Moreno 已提交
1283 1284 1285 1286
	get length(): number {
		return this.view.length;
	}

J
Joao Moreno 已提交
1287
	get contentHeight(): number {
J
Joao Moreno 已提交
1288 1289 1290 1291 1292
		return this.view.contentHeight;
	}

	get onDidChangeContentHeight(): Event<number> {
		return this.view.onDidChangeContentHeight;
J
Joao Moreno 已提交
1293 1294
	}

J
Joao Moreno 已提交
1295 1296 1297 1298
	get scrollTop(): number {
		return this.view.getScrollTop();
	}

J
Joao Moreno 已提交
1299 1300 1301 1302
	set scrollTop(scrollTop: number) {
		this.view.setScrollTop(scrollTop);
	}

J
Joao Moreno 已提交
1303 1304 1305 1306
	get scrollHeight(): number {
		return this.view.scrollHeight;
	}

I
isidor 已提交
1307 1308 1309 1310
	get renderHeight(): number {
		return this.view.renderHeight;
	}

J
Joao Moreno 已提交
1311 1312 1313 1314 1315 1316 1317 1318
	get firstVisibleIndex(): number {
		return this.view.firstVisibleIndex;
	}

	get lastVisibleIndex(): number {
		return this.view.lastVisibleIndex;
	}

J
Joao Moreno 已提交
1319 1320 1321 1322
	domFocus(): void {
		this.view.domNode.focus();
	}

1323 1324
	layout(height?: number, width?: number): void {
		this.view.layout(height, width);
J
Joao Moreno 已提交
1325 1326
	}

J
Joao Moreno 已提交
1327 1328 1329 1330 1331 1332
	toggleKeyboardNavigation(): void {
		if (this.typeLabelController) {
			this.typeLabelController.toggle();
		}
	}

1333
	setSelection(indexes: number[], browserEvent?: UIEvent): void {
J
Joao Moreno 已提交
1334 1335 1336 1337 1338 1339
		for (const index of indexes) {
			if (index < 0 || index >= this.length) {
				throw new Error(`Invalid index ${index}`);
			}
		}

1340
		indexes = indexes.sort(numericSort);
1341
		this.selection.set(indexes, browserEvent);
J
Joao Moreno 已提交
1342 1343
	}

J
Joao Moreno 已提交
1344 1345 1346 1347
	getSelection(): number[] {
		return this.selection.get();
	}

1348 1349 1350 1351
	getSelectedElements(): T[] {
		return this.getSelection().map(i => this.view.element(i));
	}

1352
	setFocus(indexes: number[], browserEvent?: UIEvent): void {
J
Joao Moreno 已提交
1353 1354 1355 1356 1357 1358
		for (const index of indexes) {
			if (index < 0 || index >= this.length) {
				throw new Error(`Invalid index ${index}`);
			}
		}

1359
		indexes = indexes.sort(numericSort);
1360
		this.focus.set(indexes, browserEvent);
J
Joao Moreno 已提交
1361 1362
	}

J
Joao Moreno 已提交
1363
	focusNext(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void {
J
Joao Moreno 已提交
1364
		if (this.length === 0) { return; }
J
Joao Moreno 已提交
1365

J
Joao Moreno 已提交
1366
		const focus = this.focus.get();
J
Joao Moreno 已提交
1367 1368 1369 1370 1371
		const index = this.findNextIndex(focus.length > 0 ? focus[0] + n : 0, loop, filter);

		if (index > -1) {
			this.setFocus([index], browserEvent);
		}
J
Joao Moreno 已提交
1372 1373
	}

J
Joao Moreno 已提交
1374
	focusPrevious(n = 1, loop = false, browserEvent?: UIEvent, filter?: (element: T) => boolean): void {
J
Joao Moreno 已提交
1375
		if (this.length === 0) { return; }
J
Joao Moreno 已提交
1376

J
Joao Moreno 已提交
1377
		const focus = this.focus.get();
J
Joao Moreno 已提交
1378 1379 1380 1381 1382
		const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n : 0, loop, filter);

		if (index > -1) {
			this.setFocus([index], browserEvent);
		}
J
Joao Moreno 已提交
1383 1384
	}

J
Joao Moreno 已提交
1385
	focusNextPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void {
J
Joao Moreno 已提交
1386 1387 1388
		let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
		lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
		const lastPageElement = this.view.element(lastPageIndex);
J
Joao Moreno 已提交
1389
		const currentlyFocusedElement = this.getFocusedElements()[0];
J
Joao Moreno 已提交
1390 1391

		if (currentlyFocusedElement !== lastPageElement) {
J
Joao Moreno 已提交
1392 1393 1394 1395 1396 1397 1398
			const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter);

			if (lastGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(lastGoodPageIndex)) {
				this.setFocus([lastGoodPageIndex], browserEvent);
			} else {
				this.setFocus([lastPageIndex], browserEvent);
			}
J
Joao Moreno 已提交
1399 1400
		} else {
			const previousScrollTop = this.view.getScrollTop();
J
Joao Moreno 已提交
1401
			this.view.setScrollTop(previousScrollTop + this.view.renderHeight - this.view.elementHeight(lastPageIndex));
J
Joao Moreno 已提交
1402 1403 1404

			if (this.view.getScrollTop() !== previousScrollTop) {
				// Let the scroll event listener run
J
Joao Moreno 已提交
1405
				setTimeout(() => this.focusNextPage(browserEvent, filter), 0);
J
Joao Moreno 已提交
1406 1407 1408 1409
			}
		}
	}

J
Joao Moreno 已提交
1410
	focusPreviousPage(browserEvent?: UIEvent, filter?: (element: T) => boolean): void {
J
Johannes Rieken 已提交
1411
		let firstPageIndex: number;
J
Joao Moreno 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420
		const scrollTop = this.view.getScrollTop();

		if (scrollTop === 0) {
			firstPageIndex = this.view.indexAt(scrollTop);
		} else {
			firstPageIndex = this.view.indexAfter(scrollTop - 1);
		}

		const firstPageElement = this.view.element(firstPageIndex);
J
Joao Moreno 已提交
1421
		const currentlyFocusedElement = this.getFocusedElements()[0];
J
Joao Moreno 已提交
1422 1423

		if (currentlyFocusedElement !== firstPageElement) {
J
Joao Moreno 已提交
1424 1425 1426 1427 1428 1429 1430
			const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter);

			if (firstGoodPageIndex > -1 && currentlyFocusedElement !== this.view.element(firstGoodPageIndex)) {
				this.setFocus([firstGoodPageIndex], browserEvent);
			} else {
				this.setFocus([firstPageIndex], browserEvent);
			}
J
Joao Moreno 已提交
1431 1432 1433 1434 1435 1436
		} else {
			const previousScrollTop = scrollTop;
			this.view.setScrollTop(scrollTop - this.view.renderHeight);

			if (this.view.getScrollTop() !== previousScrollTop) {
				// Let the scroll event listener run
J
Joao Moreno 已提交
1437
				setTimeout(() => this.focusPreviousPage(browserEvent, filter), 0);
J
Joao Moreno 已提交
1438 1439 1440 1441
			}
		}
	}

J
Joao Moreno 已提交
1442
	focusLast(browserEvent?: UIEvent, filter?: (element: T) => boolean): void {
1443
		if (this.length === 0) { return; }
J
Joao Moreno 已提交
1444 1445 1446 1447 1448 1449

		const index = this.findPreviousIndex(this.length - 1, false, filter);

		if (index > -1) {
			this.setFocus([index], browserEvent);
		}
1450 1451
	}

J
Joao Moreno 已提交
1452
	focusFirst(browserEvent?: UIEvent, filter?: (element: T) => boolean): void {
1453
		if (this.length === 0) { return; }
J
Joao Moreno 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495

		const index = this.findNextIndex(0, false, filter);

		if (index > -1) {
			this.setFocus([index], browserEvent);
		}
	}

	private findNextIndex(index: number, loop = false, filter?: (element: T) => boolean): number {
		for (let i = 0; i < this.length; i++) {
			if (index >= this.length && !loop) {
				return -1;
			}

			index = index % this.length;

			if (!filter || filter(this.element(index))) {
				return index;
			}

			index++;
		}

		return -1;
	}

	private findPreviousIndex(index: number, loop = false, filter?: (element: T) => boolean): number {
		for (let i = 0; i < this.length; i++) {
			if (index < 0 && !loop) {
				return -1;
			}

			index = (this.length + (index % this.length)) % this.length;

			if (!filter || filter(this.element(index))) {
				return index;
			}

			index--;
		}

		return -1;
1496 1497
	}

J
Joao Moreno 已提交
1498 1499 1500 1501 1502 1503
	getFocus(): number[] {
		return this.focus.get();
	}

	getFocusedElements(): T[] {
		return this.getFocus().map(i => this.view.element(i));
J
Joao Moreno 已提交
1504 1505
	}

J
Joao Moreno 已提交
1506
	reveal(index: number, relativeTop?: number): void {
J
Joao Moreno 已提交
1507 1508 1509 1510
		if (index < 0 || index >= this.length) {
			throw new Error(`Invalid index ${index}`);
		}

J
Joao Moreno 已提交
1511 1512 1513 1514 1515 1516
		const scrollTop = this.view.getScrollTop();
		const elementTop = this.view.elementTop(index);
		const elementHeight = this.view.elementHeight(index);

		if (isNumber(relativeTop)) {
			// y = mx + b
J
Joao Moreno 已提交
1517
			const m = elementHeight - this.view.renderHeight;
J
Joao Moreno 已提交
1518
			this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop);
J
Joao Moreno 已提交
1519
		} else {
J
Joao Moreno 已提交
1520
			const viewItemBottom = elementTop + elementHeight;
J
Joao Moreno 已提交
1521
			const wrapperBottom = scrollTop + this.view.renderHeight;
J
Joao Moreno 已提交
1522 1523 1524 1525

			if (elementTop < scrollTop) {
				this.view.setScrollTop(elementTop);
			} else if (viewItemBottom >= wrapperBottom) {
J
Joao Moreno 已提交
1526
				this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
J
Joao Moreno 已提交
1527 1528 1529 1530
			}
		}
	}

J
Joao Moreno 已提交
1531 1532 1533 1534 1535
	/**
	 * Returns the relative position of an element rendered in the list.
	 * Returns `null` if the element isn't *entirely* in the visible viewport.
	 */
	getRelativeTop(index: number): number | null {
J
Joao Moreno 已提交
1536 1537 1538 1539
		if (index < 0 || index >= this.length) {
			throw new Error(`Invalid index ${index}`);
		}

J
Joao Moreno 已提交
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
		const scrollTop = this.view.getScrollTop();
		const elementTop = this.view.elementTop(index);
		const elementHeight = this.view.elementHeight(index);

		if (elementTop < scrollTop || elementTop + elementHeight > scrollTop + this.view.renderHeight) {
			return null;
		}

		// y = mx + b
		const m = elementHeight - this.view.renderHeight;
		return Math.abs((scrollTop - elementTop) / m);
	}

1553 1554 1555 1556
	isDOMFocused(): boolean {
		return this.view.domNode === document.activeElement;
	}

1557 1558 1559 1560
	getHTMLElement(): HTMLElement {
		return this.view.domNode;
	}

1561
	open(indexes: number[], browserEvent?: UIEvent): void {
J
Joao Moreno 已提交
1562 1563 1564 1565 1566 1567
		for (const index of indexes) {
			if (index < 0 || index >= this.length) {
				throw new Error(`Invalid index ${index}`);
			}
		}

J
Joao Moreno 已提交
1568
		this._onDidOpen.fire({ indexes, elements: indexes.map(i => this.view.element(i)), browserEvent });
J
Joao Moreno 已提交
1569 1570
	}

J
Joao Moreno 已提交
1571
	pin(indexes: number[]): void {
J
Joao Moreno 已提交
1572 1573 1574 1575 1576 1577
		for (const index of indexes) {
			if (index < 0 || index >= this.length) {
				throw new Error(`Invalid index ${index}`);
			}
		}

J
Joao Moreno 已提交
1578 1579 1580
		this._onPin.fire(indexes);
	}

1581
	style(styles: IListStyles): void {
1582
		this.styleController.style(styles);
1583 1584
	}

1585 1586
	private toListEvent({ indexes, browserEvent }: ITraitChangeEvent) {
		return { indexes, elements: indexes.map(i => this.view.element(i)), browserEvent };
J
Joao Moreno 已提交
1587 1588
	}

J
Joao Moreno 已提交
1589
	private _onFocusChange(): void {
J
João Moreno 已提交
1590 1591 1592
		const focus = this.focus.get();

		if (focus.length > 0) {
J
Joao Moreno 已提交
1593
			this.view.domNode.setAttribute('aria-activedescendant', this.view.getElementDomId(focus[0]));
J
João Moreno 已提交
1594 1595 1596 1597 1598 1599
		} else {
			this.view.domNode.removeAttribute('aria-activedescendant');
		}

		this.view.domNode.setAttribute('role', 'tree');
		DOM.toggleClass(this.view.domNode, 'element-focused', focus.length > 0);
J
Joao Moreno 已提交
1600 1601
	}

1602 1603 1604 1605 1606 1607 1608 1609
	private _onSelectionChange(): void {
		const selection = this.selection.get();

		DOM.toggleClass(this.view.domNode, 'selection-none', selection.length === 0);
		DOM.toggleClass(this.view.domNode, 'selection-single', selection.length === 1);
		DOM.toggleClass(this.view.domNode, 'selection-multiple', selection.length > 1);
	}

J
Joao Moreno 已提交
1610
	dispose(): void {
1611
		this._onDidDispose.fire();
J
Joao Moreno 已提交
1612
		this.disposables = dispose(this.disposables);
1613

J
Joao Moreno 已提交
1614
		this._onDidOpen.dispose();
1615 1616
		this._onPin.dispose();
		this._onDidDispose.dispose();
J
Joao Moreno 已提交
1617 1618
	}
}