UNPKG

2.26 kBPlain TextView Raw
1// *****************************************************************************
2// Copyright (C) 2019 TypeFox and others.
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License v. 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0.
7//
8// This Source Code may also be made available under the following Secondary
9// Licenses when the conditions for such availability set forth in the Eclipse
10// Public License v. 2.0 are satisfied: GNU General Public License, version 2
11// with the GNU Classpath Exception which is available at
12// https://www.gnu.org/software/classpath/license.html.
13//
14// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15// *****************************************************************************
16
17import { TreeWidget } from './tree-widget';
18import { SelectableTreeNode } from './tree-selection';
19
20export type TreeWidgetSelection = ReadonlyArray<Readonly<SelectableTreeNode>> & {
21 source: TreeWidget
22};
23export namespace TreeWidgetSelection {
24 export function isSource(selection: unknown, source: TreeWidget): selection is TreeWidgetSelection {
25 return getSource(selection) === source;
26 }
27 export function getSource(selection: unknown): TreeWidget | undefined {
28 return is(selection) ? selection.source : undefined;
29 }
30 export function is(selection: unknown): selection is TreeWidgetSelection {
31 return Array.isArray(selection) && ('source' in selection) && (selection as TreeWidgetSelection).source instanceof TreeWidget;
32 }
33
34 export function create(source: TreeWidget): TreeWidgetSelection {
35 const focusedNode = source.model.getFocusedNode();
36 const selectedNodes = source.model.selectedNodes;
37 const focusedIndex = selectedNodes.indexOf(focusedNode as SelectableTreeNode);
38 // Ensure that the focused node is at index 0 - used as default single selection.
39 if (focusedNode && focusedIndex > 0) {
40 const selection = [focusedNode, ...selectedNodes.slice(0, focusedIndex), ...selectedNodes.slice(focusedIndex + 1)];
41 return Object.assign(selection, { source });
42 }
43 return Object.assign(selectedNodes, { source });
44 }
45}