All files / platform/core/src/services/ToolBarService ToolbarService.ts

74.09% Statements 163/220
57.14% Branches 52/91
68.51% Functions 37/54
74.4% Lines 157/211

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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646            34x         34x         34x                                                                 34x   34x 34x 34x 34x 34x             34x 34x 34x 34x         34x       34x       34x                   408x                 136x 136x 803x 803x     136x 170x 136x 34x 34x       170x                                           102x 1292x 1258x       1258x       102x                                         24x       24x 24x   24x       24x   24x                   24x   24x 24x                   24x       24x   24x         24x   24x                                       1387x 1387x   1387x 54884x 23679x 23679x   31205x 31205x             31205x 31205x       1387x 32959x   32959x 31205x 31205x   31205x 31205x         1754x 1754x   1754x       1754x           1754x   1754x       1754x 23679x 23679x 23679x               1387x 1387x                     1387x 1387x                                                                     24x 24x         79105x   79105x       79105x 237315x 1740310x     237315x                     136x             136x   136x                     9129x   9129x   79105x 79105x                                 13875x   13875x 13875x 13875x   13875x 12210x       1665x                     79105x       79105x 79105x   79105x   79105x   79105x 1224x     79105x 13x     79092x   79092x   79092x                                                                                               79092x                 79092x         79092x       79092x               2676x   2676x       2676x   2676x 102x     2574x 34596x   34x     142217x   142217x             142217x 135089x     7128x 476x 952x   952x   952x   952x           952x 12278x     476x     476x 24556x     12278x   12278x 10022x           12278x 2216x     12278x     476x     6652x 578x   578x 578x 578x               6074x 68x 68x 68x 1754x 68x                                 34x  
import { CommandsManager } from '../../classes';
import { ExtensionManager } from '../../extensions';
import { PubSubService } from '../_shared/pubSubServiceInterface';
import type { RunCommand } from '../../types/Command';
import { Button, ButtonProps, EvaluateFunction, EvaluatePublic, NestedButtonProps } from './types';
 
const EVENTS = {
  TOOL_BAR_MODIFIED: 'event::toolBarService:toolBarModified',
  TOOL_BAR_STATE_MODIFIED: 'event::toolBarService:toolBarStateModified',
};
 
export default class ToolbarService extends PubSubService {
  public static REGISTRATION = {
    name: 'toolbarService',
    altName: 'ToolBarService',
    create: ({ commandsManager, extensionManager, servicesManager }) => {
      return new ToolbarService(commandsManager, extensionManager, servicesManager);
    },
  };
 
  public static createButton(options: {
    id: string;
    label: string;
    commands: RunCommand;
    icon?: string;
    tooltip?: string;
    evaluate?: EvaluatePublic;
    listeners?: Record<string, RunCommand>;
  }): ButtonProps {
    const { id, icon, label, commands, tooltip, evaluate, listeners } = options;
    return {
      id,
      icon,
      label,
      commands,
      tooltip: tooltip || label,
      evaluate,
      listeners,
    };
  }
 
  state: {
    // all buttons in the toolbar with their props
    buttons: Record<string, Button>;
    // the buttons in the toolbar, grouped by section, with their ids
    buttonSections: Record<string, string[]>;
  } = {
    buttons: {},
    buttonSections: {},
  };
 
  _commandsManager: CommandsManager;
  _extensionManager: ExtensionManager;
  _servicesManager: AppTypes.ServicesManager;
  _evaluateFunction: Record<string, EvaluateFunction> = {};
  _serviceSubscriptions = [];
 
  constructor(
    commandsManager: CommandsManager,
    extensionManager: ExtensionManager,
    servicesManager: AppTypes.ServicesManager
  ) {
    super(EVENTS);
    this._commandsManager = commandsManager;
    this._extensionManager = extensionManager;
    this._servicesManager = servicesManager;
  }
 
  public reset(): void {
    // this.unsubscriptions.forEach(unsub => unsub());
    this.state = {
      buttons: {},
      buttonSections: {},
    };
    this.unsubscriptions = [];
  }
 
  public onModeEnter(): void {
    this.reset();
  }
 
  /**
   * Registers an evaluate function with the specified name.
   *
   * @param name - The name of the evaluate function.
   * @param handler - The evaluate function handler.
   */
  public registerEvaluateFunction(name: string, handler: EvaluateFunction) {
    this._evaluateFunction[name] = handler;
  }
 
  /**
   * Registers a service and its event to listen for updates and refreshes the toolbar state when the event is triggered.
   * @param service - The service to register.
   * @param event - The event to listen for.
   */
  public registerEventForToolbarUpdate(service, events) {
    const { viewportGridService } = this._servicesManager.services;
    const callback = () => {
      const viewportId = viewportGridService.getActiveViewportId();
      this.refreshToolbarState({ viewportId });
    };
 
    const unsubscriptions = events.map(event => {
      if (service.subscribe) {
        return service.subscribe(event, callback);
      } else if (service.addEventListener) {
        return service.addEventListener(event, callback);
      }
    });
 
    unsubscriptions.forEach(unsub => this._serviceSubscriptions.push(unsub));
  }
 
  /**
   * Removes buttons from the toolbar.
   * @param buttonId - The button to be removed.
   */
  public removeButton(buttonId: string) {
    Iif (this.state.buttons[buttonId]) {
      delete this.state.buttons[buttonId];
    }
    this._broadcastEvent(this.EVENTS.TOOL_BAR_MODIFIED, {
      ...this.state,
    });
  }
 
  /**
   * Adds buttons to the toolbar.
   * @param buttons - The buttons to be added.
   * @param replace - Flag indicating if any existing button with the same id as one being added should be replaced
   */
  public addButtons(buttons: Button[], replace: boolean = false): void {
    buttons.forEach(button => {
      if (replace || !this.state.buttons[button.id]) {
        Iif (!button.props) {
          button.props = {} as ButtonProps;
        }
 
        this.state.buttons[button.id] = button;
      }
    });
 
    this._broadcastEvent(this.EVENTS.TOOL_BAR_MODIFIED, {
      ...this.state,
    });
  }
 
  /**
   *
   * @param {*} interaction - can be undefined to run nothing
   * @param {*} options is an optional set of extra commandOptions
   *    used for calling the specified interaction.  That is, the command is
   *    called with {...commandOptions,...options}
   */
  public recordInteraction(
    interaction,
    options?: {
      refreshProps: Record<string, unknown>;
      [key: string]: unknown;
    }
  ) {
    // if interaction is a string, we can assume it is the itemId
    // and get the props to get the other properties
    Iif (typeof interaction === 'string') {
      interaction = this.getButtonProps(interaction);
    }
 
    const itemId = interaction.itemId ?? interaction.id;
    interaction.itemId = itemId;
 
    let commands = Array.isArray(interaction.commands)
      ? interaction.commands
      : [interaction.commands];
 
    commands = commands.filter(Boolean);
 
    Iif (!commands?.length) {
      this.refreshToolbarState({
        ...options?.refreshProps,
        itemId,
        interaction,
      });
 
      return;
    }
 
    const commandOptions = { ...options, ...interaction };
 
    commands = commands.map(command => {
      Iif (typeof command === 'function') {
        return () => {
          command({
            ...commandOptions,
            commandsManager: this._commandsManager,
            servicesManager: this._servicesManager,
          });
        };
      }
 
      return command;
    });
 
    // if still no commands, return
    commands = commands.filter(Boolean);
 
    Iif (!commands.length) {
      return;
    }
 
    // Loop through commands and run them with the combined options
    this._commandsManager.run(commands, commandOptions);
 
    this.refreshToolbarState({
      ...options?.refreshProps,
      itemId,
      interaction,
    });
  }
 
  /**
   * Consolidates the state of the toolbar after an interaction, it accepts
   * props that get passed to the buttons
   *
   * @param refreshProps - The props that buttons need to get evaluated, they can be
   * { viewportId, toolGroup} for cornerstoneTools.
   *
   * Todo: right now refreshToolbarState should be used in the context where
   * we have access to the toolGroup and viewportId, but we should be able to
   * pass the props to the toolbar service and it should be able to decide
   * which buttons to evaluate based on the props
   */
  public refreshToolbarState(refreshProps) {
    const buttons = this.state.buttons;
    const evaluationResults = new Map();
 
    const evaluateButtonProps = (button, props, refreshProps) => {
      if (evaluationResults.has(button.id)) {
        const { disabled, disabledText, className, isActive } = evaluationResults.get(button.id);
        return { ...props, disabled, disabledText, className, isActive };
      } else {
        const evaluated = props.evaluate?.({ ...refreshProps, button });
        const updatedProps = {
          ...props,
          ...evaluated,
          disabled: evaluated?.disabled || false,
          className: evaluated?.className || '',
          isActive: evaluated?.isActive, // isActive will be undefined for buttons without this prop
        };
        evaluationResults.set(button.id, updatedProps);
        return updatedProps;
      }
    };
 
    Object.values(buttons).forEach(button => {
      const hasSection = (button.props as NestedButtonProps)?.buttonSection;
 
      if (!hasSection) {
        this.handleEvaluate(button.props);
        const buttonProps = button.props as ButtonProps;
 
        const updatedProps = evaluateButtonProps(button, buttonProps, refreshProps);
        buttons[button.id] = {
          ...button,
          props: updatedProps,
        };
      } else {
        let buttonProps = button.props as NestedButtonProps;
        const { evaluate: groupEvaluate } = buttonProps;
        const groupEvaluated =
          typeof groupEvaluate === 'function'
            ? groupEvaluate({ ...refreshProps, button })
            : undefined;
 
        buttonProps = {
          ...buttonProps,
          disabled: groupEvaluated?.disabled ?? buttonProps.disabled,
          disabledText: groupEvaluated?.disabledText ?? buttonProps.disabledText,
        };
 
        const toolButtonIds = this.state.buttonSections[buttonProps.buttonSection];
 
        Iif (!toolButtonIds) {
          return;
        }
 
        toolButtonIds.forEach(buttonId => {
          const button = buttons[buttonId];
          const updatedProps = evaluateButtonProps(button, button.props, refreshProps);
          buttons[buttonId] = {
            ...button,
            props: updatedProps,
          };
        });
      }
    });
 
    this.setButtons(buttons);
    return this.state;
  }
 
  /**
   * Sets the buttons for the toolbar, don't use this method to record an
   * interaction, since it doesn't update the state of the buttons, use
   * this if you know the buttons you want to set and you want to set them
   * all at once.
   * @param buttons - The buttons to set.
   */
  public setButtons(buttons) {
    this.state.buttons = buttons;
    this._broadcastEvent(this.EVENTS.TOOL_BAR_MODIFIED, {
      buttons: this.state.buttons,
      buttonSections: this.state.buttonSections,
    });
  }
 
  /**
   * Retrieves a button by its ID.
   * @param id - The ID of the button to retrieve.
   * @returns The button with the specified ID.
   */
  public getButton(id: string): Button {
    return this.state.buttons[id];
  }
 
  /**
   * Retrieves the buttons from the toolbar service.
   * @returns An array of buttons.
   */
  public getButtons() {
    return this.state.buttons;
  }
 
  /**
   * Retrieves the button properties for the specified button ID.
   * It prioritizes nested buttons over regular buttons if the ID is found
   * in both.
   *
   * @param id - The ID of the button.
   * @returns The button properties.
   */
  public getButtonProps(id: string): ButtonProps {
    // This should be checked after we checked the nested buttons, since
    // we are checking based on the ids, the nested objects are higher priority
    // and more specific
    if (this.state.buttons[id]) {
      return this.state.buttons[id].props as ButtonProps;
    }
  }
 
  _getButtonUITypes() {
    const registeredToolbarModules = this._extensionManager.modules['toolbarModule'];
 
    Iif (!Array.isArray(registeredToolbarModules)) {
      return {};
    }
 
    return registeredToolbarModules.reduce((buttonTypes, toolbarModule) => {
      toolbarModule.module.forEach(def => {
        buttonTypes[def.name] = def;
      });
 
      return buttonTypes;
    }, {});
  }
 
  /**
   * Creates a button section with the specified key and buttons.
   * Buttons already in the section (i.e. with the same ids) will NOT be added twice.
   * @param {string} key - The key of the button section.
   * @param {Array} buttons - The buttons to be added to the section.
   */
  createButtonSection(key, buttons) {
    Iif (this.state.buttonSections[key]) {
      this.state.buttonSections[key].push(
        ...buttons.filter(
          button => !this.state.buttonSections[key].find(sectionButton => sectionButton === button)
        )
      );
    } else {
      this.state.buttonSections[key] = buttons;
    }
    this._broadcastEvent(this.EVENTS.TOOL_BAR_MODIFIED, { ...this.state });
  }
 
  /**
   * Retrieves the button section with the specified sectionId.
   *
   * @param sectionId - The ID of the button section to retrieve.
   * @param props - Optional additional properties for mapping the button to display.
   * @returns An array of buttons in the specified section, mapped to their display representation.
   */
  getButtonSection(sectionId: string, props?: Record<string, unknown>) {
    const buttonSectionIds = this.state.buttonSections[sectionId];
 
    return (
      buttonSectionIds?.map(btnId => {
        const btn = this.state.buttons[btnId];
        return this._mapButtonToDisplay(btn, props);
      }) || []
    );
  }
 
  getButtonPropsInButtonSection(sectionId: string) {
    const buttonSectionIds = this.state.buttonSections[sectionId];
 
    return buttonSectionIds?.map(btnId => this.getButtonProps(btnId)) || [];
  }
 
  /**
   * Retrieves the tool name for a given button.
   * @param button - The button object.
   * @returns The tool name associated with the button.
   */
  getToolNameForButton(button) {
    const { props } = button;
 
    const commands = props?.commands || button.commands;
    const commandsArray = Array.isArray(commands) ? commands : [commands];
    const firstCommand = commandsArray[0];
 
    if (firstCommand?.commandOptions) {
      return firstCommand.commandOptions.toolName ?? props?.id ?? button.id;
    }
 
    // use id as a fallback for toolName
    return props?.id ?? button.id;
  }
 
  /**
   *
   * @param {*} btn
   * @param {*} btnSection
   * @param {*} metadata
   * @param {*} props - Props set by the Viewer layer
   */
  _mapButtonToDisplay(btn: Button, props: Record<string, unknown>) {
    Iif (!btn) {
      return;
    }
 
    const { id, uiType } = btn;
    const { groupId } = btn.props as NestedButtonProps;
 
    const buttonTypes = this._getButtonUITypes();
 
    const buttonType = buttonTypes[uiType];
 
    if (!btn.component) {
      btn.component = buttonType.defaultComponent;
    }
 
    if (!buttonType) {
      return;
    }
 
    !groupId ? this.handleEvaluate(btn.props) : this.handleEvaluateNested(btn.props);
 
    const { id: buttonId, props: componentProps } = btn;
 
    const createEnhancedOptions = (options, itemId) => {
      const optionsToUse = Array.isArray(options) ? options : [options];
      const toolProps = this.getButtonProps(itemId);
 
      return optionsToUse.map(option => {
        Iif (typeof option.optionComponent === 'function') {
          return option;
        }
 
        return {
          ...option,
          onChange: value => {
            // Update the option's value for UI
            option.value = value;
 
            const cmds = Array.isArray(option.commands) ? option.commands : [option.commands];
 
            // Find the parent button and update its options
            Iif (toolProps && toolProps.options) {
              // Find the option in the button's options array and update its value
              const optionIndex = toolProps.options.findIndex(opt => opt.id === option.id);
              Iif (optionIndex !== -1) {
                toolProps.options[optionIndex].value = value;
              }
            }
 
            cmds.forEach(command => {
              const commandOptions = {
                ...option,
                value,
                options: toolProps.options,
                servicesManager: this._servicesManager,
                commandsManager: this._commandsManager,
              };
 
              this._commandsManager.run(command, commandOptions);
            });
 
            // Notify that toolbar state has been modified
            this._broadcastEvent(EVENTS.TOOL_BAR_STATE_MODIFIED, {
              buttons: this.state.buttons,
              buttonSections: this.state.buttonSections,
            });
          },
        };
      });
    };
 
    Iif ((componentProps as NestedButtonProps)?.items?.length) {
      const { items = [] } = componentProps as NestedButtonProps;
 
      items.forEach(item => {
        Iif (!item.options) {
          return;
        }
        item.options = createEnhancedOptions(item.options, item.id);
      });
    } else Iif ((componentProps as ButtonProps).options?.length) {
      (componentProps as ButtonProps).options = createEnhancedOptions(
        (componentProps as ButtonProps).options,
        buttonId
      );
    } else Iif ((componentProps as ButtonProps).optionComponent) {
      (componentProps as ButtonProps).optionComponent = options.optionComponent;
    }
 
    return {
      id,
      Component: btn.component,
      componentProps: Object.assign({ id }, btn.props, props),
    };
  }
 
  handleEvaluateNested = props => {
    const { buttonSection } = props;
 
    Iif (!buttonSection) {
      return;
    }
 
    const toolbarButtons = this.getButtonSection(buttonSection);
 
    if (!toolbarButtons?.length) {
      return;
    }
 
    toolbarButtons.forEach(button => {
      this.handleEvaluate(button.componentProps);
    });
  };
 
  handleEvaluate = props => {
    const { evaluate, options } = props;
 
    Iif (typeof options === 'string') {
      // get the custom option component from the extension manager and set it as the optionComponent
      const buttonTypes = this._getButtonUITypes();
      const optionComponent = buttonTypes[options]?.defaultComponent;
      props.options = optionComponent;
    }
 
    if (typeof evaluate === 'function') {
      return;
    }
 
    if (Array.isArray(evaluate)) {
      const evaluators = evaluate.map(evaluator => {
        const isObject = typeof evaluator === 'object';
 
        const evaluatorName = isObject ? evaluator.name : evaluator;
 
        const evaluateFunction = this._evaluateFunction[evaluatorName];
 
        Iif (!evaluateFunction) {
          throw new Error(
            `Evaluate function not found for name: ${evaluatorName}, you can register an evaluate function with the getToolbarModule in your extensions`
          );
        }
 
        if (isObject) {
          return args => evaluateFunction({ ...args, ...evaluator });
        }
 
        return evaluateFunction;
      });
 
      props.evaluate = args => {
        const results = evaluators.map(evaluator => evaluator(args)).filter(Boolean);
 
        // had at least one disabled button, so we need to disable the button
        const hasDisabledButton = results?.some(result => result.disabled);
 
        const mergedResult = results.reduce((acc, result) => {
          return {
            ...acc,
            ...result,
          };
        }, {});
 
        if (hasDisabledButton) {
          mergedResult.disabled = true;
        }
 
        return mergedResult;
      };
 
      return;
    }
 
    if (typeof evaluate === 'string') {
      const evaluateFunction = this._evaluateFunction[evaluate];
 
      if (evaluateFunction) {
        props.evaluate = evaluateFunction;
        return;
      }
 
      throw new Error(
        `Evaluate function not found for name: ${evaluate}, you can register an evaluate function with the getToolbarModule in your extensions`
      );
    }
 
    if (typeof evaluate === 'object') {
      const { name, ...options } = evaluate;
      const evaluateFunction = this._evaluateFunction[name];
      if (evaluateFunction) {
        props.evaluate = args => evaluateFunction({ ...args, ...options });
        return;
      }
 
      throw new Error(
        `Evaluate function not found for name: ${name}, you can register an evaluate function with the getToolbarModule in your extensions`
      );
    }
  };
 
  getButtonComponentForUIType(uiType: string) {
    return uiType ? (this._getButtonUITypes()[uiType]?.defaultComponent ?? null) : null;
  }
 
  clearButtonSection(buttonSection: string) {
    this.state.buttonSections[buttonSection] = [];
    this._broadcastEvent(this.EVENTS.TOOL_BAR_MODIFIED, { ...this.state });
  }
}