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

71.96% Statements 190/264
56.89% Branches 66/116
68.25% Functions 43/63
72.04% Lines 183/254

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 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821            43x               43x                                                             344x                     43x         43x               215x                                                               43x   43x 43x 43x 43x 43x             43x 43x 43x 43x         43x       43x       43x                   989x                 301x 301x 1079x 1079x     301x 516x 473x 43x 43x       516x                                                           43x 2064x 2064x         2064x 129x     2064x       43x                                         33x       33x 33x   33x       33x   33x 4x           4x     29x   29x 29x                   29x       29x   29x         29x   29x                                       2479x 2479x 2479x   2479x 82530x       82530x   82530x       82530x 82530x               82530x 82530x       2479x 2479x     88032x 58688x     29344x   29344x 23842x 23842x   23842x 23842x         23842x   5502x 5502x   5502x       5502x           5502x   5502x       5502x 58688x 58688x       58688x       58688x 58688x         58688x         2479x 2479x                     2479x 2479x                       6042x                                                                       33x 33x         181203x   181203x       181203x 543609x 7610526x     543609x                     344x             344x   344x                                               33841x   33841x   181203x 181203x                                 35425x   35425x 35425x 35425x   35425x 31174x       4251x                     181203x       181203x 181203x   181203x   181203x   181203x 2064x     181203x       181203x   181203x   181203x                                                                                               181203x                 181203x         181203x       181203x               6982x   6982x       6982x   6982x 559x     6423x 72509x   43x     270572x   270572x             270572x 256096x     14476x 602x 1204x   1204x   1204x   1204x           1204x 25676x     602x     602x 602x 51352x     25676x   25676x 23562x           25676x 4751x     25676x     602x   602x     13874x 817x   817x 817x 817x               13057x 430x 430x 430x 430x 17281x 430x 430x                                                 1417x         1417x 5668x                             1466x 1466x   976x                   490x                   43x  
import { CommandsManager } from '../../classes';
import { ExtensionManager } from '../../extensions';
import { PubSubService } from '../_shared/pubSubServiceInterface';
import type { RunCommand } from '../../types/Command';
import { Button, ButtonProps, EvaluateFunction, EvaluatePublic } from './types';
 
const EVENTS = {
  TOOL_BAR_MODIFIED: 'event::toolBarService:toolBarModified',
  TOOL_BAR_STATE_MODIFIED: 'event::toolBarService:toolBarStateModified',
};
 
/**
 * Predefined toolbar sections used throughout the application
 */
export const TOOLBAR_SECTIONS = {
  /**
   * Main toolbar
   */
  primary: 'primary',
 
  /**
   * Secondary toolbar
   */
  secondary: 'secondary',
 
  /**
   * Viewport action menu sections
   */
  viewportActionMenu: {
    topLeft: 'viewportActionMenu.topLeft',
    topRight: 'viewportActionMenu.topRight',
    bottomLeft: 'viewportActionMenu.bottomLeft',
    bottomRight: 'viewportActionMenu.bottomRight',
    topMiddle: 'viewportActionMenu.topMiddle',
    bottomMiddle: 'viewportActionMenu.bottomMiddle',
    leftMiddle: 'viewportActionMenu.leftMiddle',
    rightMiddle: 'viewportActionMenu.rightMiddle',
  },
 
  // mode specific
  segmentationToolbox: 'segmentationToolbox',
  dynamicToolbox: 'dynamic-toolbox',
  roiThresholdToolbox: 'ROIThresholdToolbox',
};
 
export enum ButtonLocation {
  TopLeft = 0,
  TopMiddle = 1,
  TopRight = 2,
  LeftMiddle = 3,
  RightMiddle = 4,
  BottomLeft = 5,
  BottomMiddle = 6,
  BottomRight = 7,
}
 
export default class ToolbarService extends PubSubService {
  public static REGISTRATION = {
    name: 'toolbarService',
    altName: 'ToolBarService',
    create: ({ commandsManager, extensionManager, servicesManager }) => {
      return new ToolbarService(commandsManager, extensionManager, servicesManager);
    },
  };
 
  /**
   * Access to predefined toolbar sections for autocomplete support
   */
  public get sections() {
    return TOOLBAR_SECTIONS;
  }
 
  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];
    }
 
    // Remove button from all sections
    Object.keys(this.state.buttonSections).forEach(sectionKey => {
      this.state.buttonSections[sectionKey] = this.state.buttonSections[sectionKey].filter(
        id => id !== 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 register(buttons: Button[], replace: boolean = false): void {
    buttons.forEach(button => {
      if (replace || !this.state.buttons[button.id]) {
        Iif (!button.props) {
          button.props = {} as ButtonProps;
        }
 
        // if button section is true as boolean, we assign the id of the button to the buttonSection
        if (button.props.buttonSection === true) {
          button.props.buttonSection = button.id;
        }
 
        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);
 
    if (!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 originalButtons = this.state.buttons;
    const updatedButtons = { ...originalButtons };
    const evaluationResults = new Map();
 
    const evaluateButtonProps = (button, props, refreshProps) => {
      Iif (evaluationResults.has(button.id)) {
        const { disabled, disabledText, className, isActive } = evaluationResults.get(button.id);
        return { ...props, disabled, disabledText, className, isActive };
      } else {
        const evaluateProps = props.evaluateProps;
        const evaluated =
          typeof props.evaluate === 'function'
            ? props.evaluate({ ...refreshProps, button })
            : undefined;
        // Check hideWhenDisabled at both evaluateProps level and props level
        const hideWhenDisabled = evaluateProps?.hideWhenDisabled || props.hideWhenDisabled;
        const updatedProps = {
          ...props,
          ...evaluated,
          disabled: evaluated?.disabled || false,
          visible: hideWhenDisabled && evaluated?.disabled ? false : true,
          className: evaluated?.className || '',
          isActive: evaluated?.isActive, // isActive will be undefined for buttons without this prop
        };
        evaluationResults.set(button.id, updatedProps);
        return updatedProps;
      }
    };
 
    const updatedIds = new Set();
    Object.values(originalButtons).forEach(button => {
      // Note: do not re-evaluate buttons that have already been evaluated
      // this will result in inconsistencies in the toolbar state
      if (updatedIds.has(button.id)) {
        return;
      }
 
      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);
        updatedButtons[button.id] = {
          ...button,
          props: updatedProps,
        };
 
        updatedIds.add(button.id);
      } 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 = originalButtons[buttonId];
          Iif (!button) {
            return;
          }
 
          Iif (updatedIds.has(buttonId)) {
            return;
          }
 
          const updatedProps = evaluateButtonProps(button, button.props, refreshProps);
          updatedButtons[buttonId] = {
            ...button,
            props: updatedProps,
          };
 
          updatedIds.add(buttonId);
        });
      }
    });
 
    this.setButtons(updatedButtons);
    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];
  }
 
  /**
   * @deprecated Use register() instead. This method will be removed in a future version.
   * 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 {
    console.warn(
      'ToolbarService.addButtons() is deprecated. Use ToolbarService.register() instead.'
    );
    this.register(buttons, replace);
  }
 
  /**
   * 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.
   */
  updateSection(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 });
  }
 
  /**
   * @deprecated Use updateSection() instead. This method will be removed in a future version.
   * Creates a button section with the specified key and buttons.
   * @param {string} key - The key of the button section.
   * @param {Array} buttons - The buttons to be added to the section.
   */
  createButtonSection(key, buttons) {
    console.warn(
      'ToolbarService.createButtonSection() is deprecated. Use ToolbarService.updateSection() instead.'
    );
    this.updateSection(key, buttons);
  }
 
  /**
   * 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 { buttonSection } = btn.props;
 
    const buttonTypes = this._getButtonUITypes();
 
    const buttonType = buttonTypes[uiType];
 
    if (!btn.component) {
      btn.component = buttonType.defaultComponent;
    }
 
    Iif (!buttonType) {
      return;
    }
 
    !buttonSection ? 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;
      });
 
      const evaluateProps = props.evaluate;
      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;
      };
 
      props.evaluateProps = evaluateProps;
 
      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) {
        const evaluateProps = props.evaluate;
        props.evaluate = args => evaluateFunction({ ...args, ...options });
        props.evaluateProps = evaluateProps;
        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 });
  }
 
  /**
   * Checks if a button exists in any toolbar section.
   *
   * @param buttonId - The button ID to check for
   * @returns True if the button exists in any section, false otherwise
   */
  isInAnySection(buttonId: string): boolean {
    Iif (!buttonId) {
      return false;
    }
 
    // Check all sections to see if the button ID exists in any of them
    return Object.values(this.state.buttonSections).some(
      section => Array.isArray(section) && section.includes(buttonId)
    );
  }
 
  /**
   * Returns the alignment and side for a specific viewport corner location.
   * Used for menu positioning based on the corner location.
   *
   * @param location - The viewport corner location
   * @returns An object with align and side properties
   */
  public getAlignAndSide(location: ButtonLocation | string): {
    align: 'start' | 'end' | 'center';
    side: 'top' | 'bottom' | 'left' | 'right';
  } {
    const locationNumber = Number(location);
    switch (locationNumber) {
      case ButtonLocation.TopLeft: // Enum 0, Original 0 (topLeft)
        return { align: 'start', side: 'bottom' };
      case ButtonLocation.TopMiddle: // Enum 1, Original 4 (topMiddle)
        return { align: 'center', side: 'bottom' };
      case ButtonLocation.TopRight: // Enum 2, Original 1 (topRight)
        return { align: 'end', side: 'bottom' };
      case ButtonLocation.LeftMiddle: // Enum 3, Original 6 (leftMiddle)
        return { align: 'start', side: 'right' };
      case ButtonLocation.RightMiddle: // Enum 4, Original 7 (rightMiddle)
        return { align: 'end', side: 'left' };
      case ButtonLocation.BottomLeft: // Enum 5, Original 2 (bottomLeft)
        return { align: 'start', side: 'top' };
      case ButtonLocation.BottomMiddle: // Enum 6, Original 5 (bottomMiddle)
        return { align: 'center', side: 'top' };
      case ButtonLocation.BottomRight: // Enum 7, Original 3 (bottomRight)
        return { align: 'end', side: 'top' };
      default:
        // Default to TopLeft behavior if an unexpected value is passed.
        return { align: 'start', side: 'bottom' };
    }
  }
}