All files / platform/core/src/classes CommandsManager.ts

73.03% Statements 65/89
60.46% Branches 26/43
88.23% Functions 15/17
71.95% Lines 59/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271                                                60x     60x                             290x       290x       290x   290x                     15433x   15433x 290x     15143x                                                     9224x         9224x 18448x     9224x       9224x 9224x       9224x     9224x       60x                   1261x   1261x 5856x 3x 3x 3x 3x       4696x                     1296x   35x     1261x 1261x         1261x 1261x           1261x       1261x         957x 565x   392x 150x   242x 35x   207x 5x 5x   202x 203x             773x 24x 24x       749x 749x         750x                                                         773x   773x 773x 750x 750x 750x     773x                                      
import log from '../log.js';
import { Command, Commands, ComplexCommand } from '../types/Command';
 
export type RunInput = Command | Commands | Command[] | string | undefined;
 
/**
 * The definition of a command
 *
 * @typedef {Object} CommandDefinition
 * @property {Function} commandFn - Command to call
 * @property {Object} options - Object of params to pass action
 */
 
/**
 * The Commands Manager tracks named commands (or functions) that are scoped to
 * a context. When we attempt to run a command with a given name, we look for it
 * in our active contexts. If found, we run the command, passing in any application
 * or call specific data specified in the command's definition.
 *
 * NOTE: A more robust version of the CommandsManager lives in v1. If you're looking
 * to extend this class, please check it's source before adding new methods.
 */
export class CommandsManager {
  private contexts = {};
  // Has the reverse order in which contexts are created, used for the default ordering
  private contextOrder = new Array<string>();
 
  constructor(_options = {}) {
    // No-op
  }
 
  /**
   * Allows us to create commands "per context". An example would be the "Cornerstone"
   * context having a `SaveImage` command, and the "VTK" context having a `SaveImage`
   * command. The distinction of a context allows us to call the command in either
   * context, and have faith that the correct command will be run.
   *
   * @method
   * @param {string} contextName - Namespace for commands
   * @returns {undefined}
   */
  createContext(contextName, priority?: number) {
    Iif (!contextName) {
      return;
    }
 
    Iif (this.contexts[contextName]) {
      return this.clearContext(contextName);
    }
 
    this.contexts[contextName] = {};
    // Add the context name to the start of the list.
    this.contextOrder.splice(0, 0, contextName);
  }
 
  /**
   * Returns all command definitions for a given context
   *
   * @method
   * @param {string} contextName - Namespace for commands
   * @returns {Object} - the matched context
   */
  getContext(contextName) {
    const context = this.contexts[contextName];
 
    if (!context) {
      return;
    }
 
    return context;
  }
 
  /**
   * Clears all registered commands for a given context.
   *
   * @param {string} contextName - Namespace for commands
   * @returns {undefined}
   */
  clearContext(contextName) {
    Iif (!contextName) {
      return;
    }
 
    this.contexts[contextName] = {};
  }
 
  /**
   * Register a new command with the command manager. Scoped to a context, and
   * with a definition to assist command callers w/ providing the necessary params
   *
   * @method
   * @param {string} contextName - Namespace for command; often scoped to the extension that added it
   * @param {string} commandName - Unique name identifying the command
   * @param {CommandDefinition} definition - {@link CommandDefinition}
   */
  registerCommand(contextName, commandName, definition) {
    Iif (typeof definition !== 'object' && typeof definition !== 'function') {
      return;
    }
 
    // Validate and restrict keys to prevent prototype pollution
    const isSafeKey = key => {
      return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
    };
 
    Iif (!isSafeKey(contextName) || !isSafeKey(commandName)) {
      throw new Error('Invalid key name to prevent prototype pollution');
    }
 
    const context = this.getContext(contextName);
    Iif (!context) {
      return;
    }
 
    Iif (typeof definition === 'function') {
      context[commandName] = { commandFn: definition, options: {} };
    } else {
      context[commandName] = definition;
    }
  }
 
  /**
   * Finds a command with the provided name if it exists in the specified context,
   * or a currently active context.
   *
   * @method
   * @param {String} commandName - Command to find
   * @param {String} [contextName] - Specific command to look in. Defaults to current activeContexts.
   *                 Also allows an array of contexts to look in.
   */
  getCommand = (commandName: string, contextName: string | string[] = this.contextOrder) => {
    const contexts = [];
 
    if (Array.isArray(contextName)) {
      contexts.push(...contextName.map(name => this.getContext(name)).filter(it => !!it));
    } else if (contextName) {
      const context = this.getContext(contextName);
      if (context) {
        contexts.push(context);
      }
    }
 
    return contexts.find(context => !!context[commandName])?.[commandName];
  };
 
  /**
   *
   * @method
   * @param {String} commandName
   * @param {Object} [options={}] - Extra options to pass the command. Like a mousedown event
   * @param {String} [contextName]
   */
  public runCommand(commandName: string, options = {}, contextName?: string | string[]) {
    if (typeof commandName === 'function') {
      // If commandName is a function, run it directly
      return commandName(options);
    }
 
    const definition = this.getCommand(commandName, contextName);
    Iif (!definition) {
      log.warn(`Command "${commandName}" not found in current context`);
      return;
    }
 
    const { commandFn } = definition;
    const commandParams = Object.assign(
      {},
      definition.options || {}, // "Command configuration"
      options // "Time of call" info
    );
 
    Iif (typeof commandFn !== 'function') {
      log.warn(`No commandFn was defined for command "${commandName}"`);
      return;
    } else {
      return commandFn(commandParams);
    }
  }
 
  public static convertCommands(toRun: Command | Commands | Command[] | string | Function) {
    if (typeof toRun === 'string') {
      return [{ commandName: toRun }];
    }
    if ('commandName' in toRun) {
      return [toRun as ComplexCommand];
    }
    if (typeof toRun === 'function') {
      return [{ commandName: toRun }];
    }
    if ('commands' in toRun) {
      const commandsInput = (toRun as Commands).commands;
      return this.convertCommands(commandsInput);
    }
    if (Array.isArray(toRun)) {
      return toRun.map(command => CommandsManager.convertCommands(command)[0]);
    }
 
    return [];
  }
 
  private validate(input: RunInput, options: Record<string, unknown> = {}): ComplexCommand[] {
    if (!input) {
      console.debug('No command to run');
      return [];
    }
 
    // convert commands
    const converted: ComplexCommand[] = CommandsManager.convertCommands(input);
    Iif (!converted.length) {
      console.debug('Command is not runnable', input);
      return [];
    }
 
    return converted.map(command => ({
      commandName: command.commandName,
      commandOptions: { ...options, ...command.commandOptions },
      context: command.context,
    }));
  }
 
  /**
   * Run one or more commands with specified extra options.
   * Returns the result of the last command run.
   *
   * Example commands to run are:
   * * 'updateMeasurement'
   * * `{ commandName: 'displayWhatever'}`
   * * `['updateMeasurement', {commandName: 'displayWhatever'}]`
   * * `{ commands: 'updateMeasurement' }`
   * * `{ commands: ['updateMeasurement', {commandName: 'displayWhatever'}]}`
   *
   * Note how the various styles can be mixed, simplifying the declaration of
   * sets of commands.
   *
   * @param toRun - A specification of one or more commands,
   *  typically an object of { commandName, commandOptions, context }
   * or an array of such objects. It can also be a single commandName as string
   * if no options are needed.
   * @param options - to include in the commands run beyond
   *   the commandOptions specified in the base.
   */
  public run(input: RunInput, options: Record<string, unknown> = {}): unknown {
    const commands = this.validate(input, options);
 
    const results: unknown[] = [];
    for (let i = 0; i < commands.length; i++) {
      const command = commands[i];
      const { commandName, commandOptions, context } = command;
      results.push(this.runCommand(commandName, commandOptions, context));
    }
 
    return results.length === 1 ? results[0] : results;
  }
 
  /** Like run, but await each command before continuing */
  public async runAsync(input: RunInput, options: Record<string, unknown> = {}): Promise<unknown> {
    const commands = this.validate(input, options);
 
    const results: unknown[] = [];
    for (let i = 0; i < commands.length; i++) {
      const command = commands[i];
      const { commandName, commandOptions, context } = command;
      results.push(await this.runCommand(commandName, commandOptions, context));
    }
 
    return results.length === 1 ? results[0] : results;
  }
}
 
export default CommandsManager;