UNPKG

2.22 kBPlain TextView Raw
1// *****************************************************************************
2// Copyright (C) 2022 Ericsson 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 { inject, injectable } from 'inversify';
18import { Emitter, Event } from '../../common';
19import { Tree, TreeNode } from './tree';
20import { SelectableTreeNode } from './tree-selection';
21
22export interface TreeFocusService {
23 readonly focusedNode: SelectableTreeNode | undefined;
24 readonly onDidChangeFocus: Event<SelectableTreeNode | undefined>;
25 setFocus(node?: SelectableTreeNode): void;
26 hasFocus(node?: TreeNode): boolean;
27}
28export const TreeFocusService = Symbol('TreeFocusService');
29
30@injectable()
31export class TreeFocusServiceImpl implements TreeFocusService {
32 protected focusedId: string | undefined;
33 protected onDidChangeFocusEmitter = new Emitter<SelectableTreeNode | undefined>();
34 get onDidChangeFocus(): Event<SelectableTreeNode | undefined> { return this.onDidChangeFocusEmitter.event; }
35
36 @inject(Tree) protected readonly tree: Tree;
37
38 get focusedNode(): SelectableTreeNode | undefined {
39 const candidate = this.tree.getNode(this.focusedId);
40 if (SelectableTreeNode.is(candidate)) {
41 return candidate;
42 }
43 }
44
45 setFocus(node?: SelectableTreeNode): void {
46 if (node?.id !== this.focusedId) {
47 this.focusedId = node?.id;
48 this.onDidChangeFocusEmitter.fire(node);
49 }
50 }
51
52 hasFocus(node?: TreeNode): boolean {
53 return !!node && node?.id === this.focusedId;
54 }
55}