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 {FuzzyFinder, FuzzySegment} from '../base/fuzzy'; 16import {Registry} from '../base/registry'; 17import {Command, CommandManager} from '../public/command'; 18import {raf} from './raf_scheduler'; 19 20export interface CommandWithMatchInfo extends Command { 21 segments: FuzzySegment[]; 22} 23 24export class CommandManagerImpl implements CommandManager { 25 private readonly registry = new Registry<Command>((cmd) => cmd.id); 26 27 getCommand(commandId: string): Command { 28 return this.registry.get(commandId); 29 } 30 31 hasCommand(commandId: string): boolean { 32 return this.registry.has(commandId); 33 } 34 35 get commands(): Command[] { 36 return Array.from(this.registry.values()); 37 } 38 39 registerCommand(cmd: Command): Disposable { 40 return this.registry.register(cmd); 41 } 42 43 runCommand(id: string, ...args: unknown[]): unknown { 44 const cmd = this.registry.get(id); 45 const res = cmd.callback(...args); 46 Promise.resolve(res).finally(() => raf.scheduleFullRedraw()); 47 return res; 48 } 49 50 // Returns a list of commands that match the search term, along with a list 51 // of segments which describe which parts of the command name match and 52 // which don't. 53 fuzzyFilterCommands(searchTerm: string): CommandWithMatchInfo[] { 54 const finder = new FuzzyFinder(this.commands, ({name}) => name); 55 return finder.find(searchTerm).map((result) => { 56 return {segments: result.segments, ...result.item}; 57 }); 58 } 59} 60