• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2023 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {Disposable} from '../base/disposable';
16import {FuzzyFinder, FuzzySegment} from '../base/fuzzy';
17import {Registry} from '../base/registry';
18import {Command} from '../public';
19
20export interface CommandWithMatchInfo extends Command {
21  segments: FuzzySegment[];
22}
23
24export class CommandManager {
25  private readonly registry = new Registry<Command>((cmd) => cmd.id);
26
27  get commands(): Command[] {
28    return Array.from(this.registry.values());
29  }
30
31  registerCommand(cmd: Command): Disposable {
32    return this.registry.register(cmd);
33  }
34
35  // eslint-disable-next-line @typescript-eslint/no-explicit-any
36  runCommand(id: string, ...args: any[]): any {
37    const cmd = this.registry.get(id);
38    return cmd.callback(...args);
39  }
40
41  // Returns a list of commands that match the search term, along with a list
42  // of segments which describe which parts of the command name match and
43  // which don't.
44  fuzzyFilterCommands(searchTerm: string): CommandWithMatchInfo[] {
45    const finder = new FuzzyFinder(this.commands, ({name}) => name);
46    return finder.find(searchTerm).map((result) => {
47      return {segments: result.segments, ...result.item};
48    });
49  }
50}
51