import { B as BlockAnnotation, d as RTEBlock, M as ModifyContentAction, C as CommonAnnotationTypeEnum, o as CustomAttributeAnnotation, i as RTENode, g as ActionHandleStrategy } from './code-block-10be3916.js';
import { c as cleanObject } from './object-0c277f57.js';
import { V as VegaInternalThemeManager } from './dark-mode-style-controller-e9a6b097.js';
import './global-slimmer-registry-17c4efd4.js';
import { I as InjectVegaTelemetrySlimmer, c as createPublicAPIRuntimeMetricsSlimmer } from './create-public-api-runtime-metrics-slimmer-aaadaa08.js';
import { r as rgbToHex } from './ui-b7600a48.js';
import { i as isNonNullable } from './type-guard-adc244fd.js';
import { g as generateUUID } from './misc-9fdbcfbb.js';
import { U as UpdateCursorPositionAction, V as VegaRTEContent } from './content-state-afeb700d.js';

const ThemeManagerRuntimeMetricsPayloadDefinition = [
  {
    payloadKey: 'IS_OVERRIDECOLORS_METHOD_CALLED',
    payloadDescription: 'Indicate if the method overrideColors of public API ThemeManager is called',
    /**
     * Indicate whether the method is collected when the method been called .
     *
     * @param {string} scope - The class name of public api
     * @param {string} methodName - The method name called by the public api
     * @returns {boolean} A boolean value
     */
    canAccept: (scope, methodName) => scope === 'ThemeManager' && methodName === 'overrideColors',
    /**
     * The function checks if the method is be called.
     *
     * @returns {boolean} A boolean value
     */
    payloadValue: () => {
      return true;
    },
  },
  {
    payloadKey: 'IS_RESET_METHOD_CALLED',
    payloadDescription: 'Indicate if the method reset of public API ThemeManager is called',
    /**
     * Indicate whether the method is collected when the method been called .
     *
     * @param {string} scope - The class name of public api
     * @param {string} methodName - The method name called by the public api
     * @returns {boolean} A boolean value
     */
    canAccept: (scope, methodName) => scope === 'ThemeManager' && methodName === 'reset',
    /**
     * The function checks if the method is be called.
     *
     * @returns {boolean} A boolean value
     */
    payloadValue: () => {
      return true;
    },
  },
  {
    payloadKey: 'IS_TOGGLEDARKMODE_METHOD_CALLED',
    payloadDescription: 'Indicate if the method toggleDarkMode of public API ThemeManager is called',
    /**
     * Indicate whether the method is collected when the method been called .
     *
     * @param {string} scope - The class name of public api
     * @param {string} methodName - The method name called by the public api
     * @returns {boolean} A boolean value
     */
    canAccept: (scope, methodName) => scope === 'ThemeManager' && methodName === 'toggleDarkMode',
    /**
     * The function checks if the method is be called.
     *
     * @returns {boolean} A boolean value
     */
    payloadValue: () => {
      return true;
    },
  },
  {
    payloadKey: 'IS_ISDARKMODE_METHOD_CALLED',
    payloadDescription: 'Indicate if the method isDarkMode of public API ThemeManager is called',
    /**
     * Indicate whether the method is collected when the method been called .
     *
     * @param {string} scope - The class name of public api
     * @param {string} methodName - The method name called by the public api
     * @returns {boolean} A boolean value
     */
    canAccept: (scope, methodName) => scope === 'ThemeManager' && methodName === 'isDarkMode',
    /**
     * The function checks if the method is be called.
     *
     * @returns {boolean} A boolean value
     */
    payloadValue: () => {
      return true;
    },
  },
  {
    payloadKey: 'IS_APPLY_BRANDING_METHOD_CALLED',
    payloadDescription: 'Indicate if the method applyBranding of public API ThemeManager is called',
    /**
     * Indicate whether the method is collected when the method been called .
     *
     * @param {string} scope - The class name of public api
     * @param {string} methodName - The method name called by the public api
     * @returns {boolean} A boolean value
     */
    canAccept: (scope, methodName) => scope === 'ThemeManager' && methodName === 'applyBranding',
    /**
     * The function checks if the method is be called.
     *
     * @returns {boolean} A boolean value
     */
    payloadValue: () => {
      return true;
    },
  },
];

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Vega components theme manager
 */
class ThemeManager {
  constructor() {
    this.vegaPublicAPIRuntimeMetricsSlimmer = createPublicAPIRuntimeMetricsSlimmer(ThemeManager, ['overrideColors', 'reset', 'toggleDarkMode', 'isDarkMode', 'applyBranding'], ThemeManagerRuntimeMetricsPayloadDefinition);
  }
  /**
   * It takes the colors you passed in, parses them into the correct format, and then applies them to the theme
   *
   * @param {VegaThemeOverrideColors} overrideColors - OverrideColors - This is the object that you pass to the function.
   * @vegaVersion 1.20.0
   */
  async overrideColors(overrideColors) {
    void VegaInternalThemeManager.overrideColors(overrideColors);
  }
  /**
   * It removes all the custom override theme styles from the DOM
   *
   * @vegaVersion 1.20.0
   */
  async reset() {
    void VegaInternalThemeManager.reset();
  }
  /**
   * This function toggles the dark mode of a webpage by adding or removing a 'dark' class to the HTML element.
   *
   * @param {boolean | undefined} darkMode - A boolean or undefined value that determines whether to enable or disable dark mode.
   * If it is true, dark mode is enabled.
   * If it is false, dark mode is disabled.
   * @vegaVersion 1.32.0
   */
  toggleDarkMode(darkMode) {
    VegaInternalThemeManager.toggleDarkMode(darkMode);
  }
  /**
   * The function checks if the HTML element has a class of "dark" and returns a boolean value accordingly.
   *
   * @returns {boolean} A boolean value indicating whether the HTML element has a class of "dark", which is
   * typically used to indicate that the website is in dark mode.
   * @vegaVersion 1.32.0
   */
  isDarkMode() {
    return VegaInternalThemeManager.isDarkMode();
  }
  /**
   * This function switches the Vega theme to a brand theme based on the provided options.
   *
   * @param {BrandOptions} options - The options includes 'gp', 'genius' and 'heartland' options
   * @vegaVersion 2.47.0
   */
  applyBranding(options) {
    VegaInternalThemeManager.applyBranding(options);
  }
}
__decorate([
  InjectVegaTelemetrySlimmer()
], ThemeManager.prototype, "vegaPublicAPIRuntimeMetricsSlimmer", void 0);
const VegaThemeManager = new ThemeManager();

const RTE_TABLE_BORDER_STYLES = [
  'none',
  'solid',
  'dashed',
  'dotted',
  'double',
  'groove',
  'ridge',
  'inset',
  'outset',
];
const RTE_TABLE_DEFAULT_COLORS = [
  { key: 'white', dark: '#04041C', light: '#FCFCFC' },
  { key: 'red', dark: '#AA091C', light: '#FF4C61' },
  { key: 'orange', dark: '#974502', light: '#FDAB68' },
  { key: 'yellow', dark: '#735C00', light: '#FFDC4C' },
  { key: 'green', dark: '#2E6D18', light: '#7BDA58' },
  { key: 'teal', dark: '#287171', light: '#7BD1D1' },
  { key: 'gray', dark: '#595959', light: '#999999' },
  { key: 'black', dark: '#FCFCFC', light: '#04041C' },
];
// Default background color for table head cells in both light and dark modes: token = bg-table-header
const RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR = {
  key: 'default-head-bg',
  dark: '#181830',
  light: '#F0F3F7',
};

/**
 * Manages table colors for the rich text editor.
 */
class RTETableColorManager {
  /**
   * Get the list of table colors.
   *
   * @returns {VegaRTEColorSchema[]} - Array of table colors.
   */
  static getTableColors() {
    return RTETableColorManager.TABLE_COLORS;
  }
  /**
   * Set the list of table colors.
   *
   * @param {VegaRTEColorSchema[]} colors - Array of table colors.
   */
  static setTableColors(colors) {
    RTETableColorManager.TABLE_COLORS = colors;
  }
  /**
   * Get color key from color value
   *
   * @param {string} colorValue - color value
   * @param {boolean} isHeadCellColor - whether the color is for a head cell
   * @returns {string} - color key
   */
  static getColorKey(colorValue, isHeadCellColor = false) {
    var _a;
    let result = null;
    const defaultColorList = RTETableColorManager.TABLE_COLORS;
    const tableColors = isHeadCellColor
      ? [...defaultColorList, RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR]
      : defaultColorList;
    if (tableColors) {
      const hexColor = (_a = rgbToHex(colorValue)) === null || _a === void 0 ? void 0 : _a.toUpperCase();
      if (hexColor) {
        result = tableColors.find((schema) => VegaThemeManager.isDarkMode() ? schema.dark === hexColor : schema.light === hexColor);
      }
      else {
        for (const color of tableColors) {
          if (color.key === colorValue) {
            result = color;
            break;
          }
        }
      }
    }
    return result ? result.key : '';
  }
}
RTETableColorManager.TABLE_COLORS = RTE_TABLE_DEFAULT_COLORS;

/**
 * Class representing a table color annotation in the rich text editor.
 */
class RTETableColorAnnotation extends BlockAnnotation {
  constructor(colorKey) {
    super();
    this.type = RTETableExtensionAnnotationTypeEnum.COLOR;
    this.colorKey = colorKey;
    if (colorKey) {
      this.color = this.formatColor(colorKey);
    }
  }
  /**
   * Render the style for the annotation
   *
   * @returns {AnnotationStyle} The style object containing the color
   */
  renderStyle() {
    const color = this.color
      ? VegaInternalThemeManager.isDarkMode()
        ? this.color.dark
        : this.color.light
      : this.colorKey || '';
    return { color };
  }
  /**
   * Render the CSS class for the annotation
   *
   * @returns {Nullable<string>} Always returns null as no CSS class is used
   */
  renderClass() {
    return null;
  }
  /**
   * Convert the annotation to a JSON representation
   *
   * @returns {Record<string, string>} A JSON object containing the color key
   */
  toJSON() {
    var _a;
    return {
      color: ((_a = this.color) === null || _a === void 0 ? void 0 : _a.key) || this.colorKey || '',
    };
  }
  /**
   * Clone the current annotation
   *
   * @returns {BlockAnnotation<RTETableExtensionAnnotationTypeEnum.COLOR>} A new instance of RTETableColorAnnotation with the same color key
   */
  clone() {
    return new RTETableColorAnnotation(this.colorKey);
  }
  /**
   * format table color
   *
   * @param {string} colorKey - table color
   * @returns {Nullable<VegaRTEColorSchema>} - VegaRTEColorSchema
   */
  formatColor(colorKey) {
    return RTETableColorManager.getTableColors().find((item) => item.key === colorKey);
  }
}

var RTETableExtensionAnnotationTypeEnum;
(function (RTETableExtensionAnnotationTypeEnum) {
  RTETableExtensionAnnotationTypeEnum["TABLE"] = "EXTENSION_TABLE";
  RTETableExtensionAnnotationTypeEnum["CELL"] = "EXTENSION_TABLE_CELL";
  RTETableExtensionAnnotationTypeEnum["CAPTION"] = "EXTENSION_TABLE_CAPTION";
  RTETableExtensionAnnotationTypeEnum["COLOR"] = "EXTENSION_TABLE_COLOR";
})(RTETableExtensionAnnotationTypeEnum || (RTETableExtensionAnnotationTypeEnum = {}));
/**
 * Class representing a table annotation in the rich text editor.
 */
class RTETableAnnotation extends BlockAnnotation {
  constructor({ backgroundColor, border, width, height, alignment, borderCollapse } = {}, useInternalStyle = true) {
    super();
    this.type = RTETableExtensionAnnotationTypeEnum.TABLE;
    this.useInternalStyle = useInternalStyle;
    this.backgroundColor = backgroundColor;
    this.border = border;
    this.width = width;
    this.height = height;
    this.alignment =
      useInternalStyle && alignment === undefined ? RTETableAnnotation.DEFAULT_ALIGNMENT : alignment;
    this.backgroundColorAnnotation = new RTETableColorAnnotation(backgroundColor);
    this.borderColorAnnotation = new RTETableColorAnnotation(border === null || border === void 0 ? void 0 : border.color);
    this.borderCollapse =
      useInternalStyle && borderCollapse === undefined
        ? RTETableAnnotation.DEFAULT_BORDER_COLLAPSE
        : borderCollapse;
  }
  /**
   * @inheritDoc
   */
  static from(value, useInternalStyle = true) {
    return [RTETableExtensionAnnotationTypeEnum.TABLE, new RTETableAnnotation(value, useInternalStyle)];
  }
  /**
   * Get the default styles for the table annotation.
   *
   * @returns {AnnotationStyle} The default styles for the table annotation.
   */
  static getDefaultStyles() {
    return {
      borderCollapse: RTETableAnnotation.DEFAULT_BORDER_COLLAPSE,
      margin: RTETableAnnotation.DEFAULT_ALIGNMENT_STYLE_VALUE,
    };
  }
  /**
   * Generates the CSS border string from the border properties.
   *
   * @returns {Nullable<string>} The CSS border string.
   */
  get borderStr() {
    if (!this.border) {
      return null;
    }
    return `${this.border.style} ${this.border.width} ${this.borderColorAnnotation.renderStyle().color}`.trim();
  }
  /**
   * @inheritDoc
   */
  clone() {
    return new RTETableAnnotation({
      backgroundColor: this.backgroundColor,
      border: this.border,
      width: this.width,
      height: this.height,
      alignment: this.alignment,
      borderCollapse: this.borderCollapse,
    }, this.useInternalStyle);
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return {
      table: cleanObject({
        backgroundColor: this.backgroundColor,
        border: this.border,
        width: this.width,
        height: this.height,
        alignment: this.alignment,
        borderCollapse: this.borderCollapse,
      }),
    };
  }
  /**
   * @inheritDoc
   */
  renderStyle() {
    const backgroundColor = this.backgroundColorAnnotation.renderStyle().color;
    const tableStyles = Object.assign({ border: this.borderStr, width: this.width, height: this.height, borderCollapse: this.borderCollapse }, this.renderAlignmentStyle());
    backgroundColor && (tableStyles.backgroundColor = backgroundColor);
    return cleanObject(tableStyles);
  }
  /**
   * @inheritDoc
   */
  renderClass() {
    return 'v-rte--extension-table';
  }
  /**
   * Generates the alignment styles for the table.
   *
   * @returns {Record<string, string>} The alignment styles.
   */
  renderAlignmentStyle() {
    if (!this.alignment)
      return {};
    return {
      margin: this.alignment === 'center'
        ? RTETableAnnotation.DEFAULT_ALIGNMENT_STYLE_VALUE
        : this.alignment === 'left'
          ? '0'
          : '0 0 0 auto',
    };
  }
}
RTETableAnnotation.DEFAULT_BORDER_COLLAPSE = 'collapse';
RTETableAnnotation.DEFAULT_ALIGNMENT = 'center';
RTETableAnnotation.DEFAULT_ALIGNMENT_STYLE_VALUE = '0 auto';

/**
 * Class representing a table block in the rich text editor.
 */
class RTETableBlock extends RTEBlock {
  constructor(id, options) {
    super(id);
    this.type = 'table-block';
    this.children = [];
    const { autoMatchFormat } = options || { autoMatchFormat: true };
    if (autoMatchFormat) {
      this.annotationMap.set(RTETableExtensionAnnotationTypeEnum.TABLE, new RTETableAnnotation());
    }
  }
  /**
   * @inheritDoc
   */
  static from(block, options) {
    var _a;
    const tableBlock = new RTETableBlock(block.id, options);
    super.convertAnnotationsToMap(tableBlock.annotationMap, Object.assign({}, block.annotations));
    tableBlock.children = super.generateBlockChildren(block.children, options, tableBlock);
    if ((_a = block.annotations) === null || _a === void 0 ? void 0 : _a.table) {
      tableBlock.annotationMap.set(...RTETableAnnotation.from(block.annotations.table, options === null || options === void 0 ? void 0 : options.autoMatchFormat));
    }
    return tableBlock;
  }
  /**
   * @inheritDoc
   */
  clone(parent) {
    const clonedBlock = new RTETableBlock(this.id);
    clonedBlock.children = this.children.map((child) => child.clone(clonedBlock));
    clonedBlock.parent = parent;
    clonedBlock.annotationMap = super.cloneAnnotations();
    return clonedBlock;
  }
  /**
   * @inheritDoc
   */
  getLastNode() {
    return this.children[this.children.length - 1].getLastNode();
  }
  /**
   * Get the first node of the table block.
   *
   * @returns {RTENode} The first node of the table block.
   */
  getFirstNode() {
    if (this.hasCaption()) {
      return this.children[0].children[0].getLastNode();
    }
    else {
      const childNode = this.children[0].children[0]
        .children[0];
      return childNode.getLastNode();
    }
  }
  /**
   * @inheritDoc
   */
  isNotEmpty() {
    return this.children.length > 0;
  }
  /**
   * @inheritDoc
   */
  toHtml(options) {
    const childrenHtml = this.children.map((child) => child.toHtml(options)).join('');
    const attrStr = super.generateAttributeString(options);
    return `<table${attrStr}>${childrenHtml}</table>`;
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return Object.assign(Object.assign({}, super.toJSON()), { type: this.type, children: this.children.map((child) => child.toJSON()) });
  }
  /**
   * Retrieves the caption block from the children collection, if present.
   *
   * @returns {Nullable<RTETableCaptionBlock>} The caption block or `null`.
   */
  getCaption() {
    const caption = this.children.find((child) => child.type === 'table-caption');
    return caption !== null && caption !== void 0 ? caption : null;
  }
  /**
   * Inserts, replaces, or removes the caption block within the children.
   *
   * @param {Nullable<RTETableCaptionBlock>} caption - The caption block to set, or `null` to remove.
   */
  setCaption(caption) {
    const index = this.children.findIndex((child) => child.type === 'table-caption');
    if (!caption) {
      if (index >= 0) {
        this.children.splice(index, 1);
      }
      return;
    }
    caption.parent = this;
    if (index >= 0) {
      this.children[index] = caption;
    }
    else {
      this.children.unshift(caption);
    }
  }
  /**
   * Checks whether the table currently stores a caption block reference.
   *
   * @returns {boolean} `true` when a caption DTO is attached; otherwise `false`.
   */
  hasCaption() {
    return isNonNullable(this.getCaption());
  }
}

var TableSettingType;
(function (TableSettingType) {
  TableSettingType["ROW"] = "ROW";
  TableSettingType["CAPTION"] = "CAPTION";
  TableSettingType["COLUMN"] = "COLUMN";
  TableSettingType["MERGE_CELLS"] = "MERGE_CELLS";
  TableSettingType["TABLE"] = "TABLE";
  TableSettingType["CELL"] = "CELL";
  TableSettingType["SPLIT_CELL"] = "SPLIT_CELL";
})(TableSettingType || (TableSettingType = {}));
/**
 * Abstract class for setting event handlers.
 */
class SettingEventHandler {
  /**
   * Applies a cursor update action so the editor focuses on the resolved node.
   *
   * @param {RTETableBlock} block - Table block currently being toggled.
   * @param {Nullable<RTENode>} focusNode - Target node that should receive the caret.
   */
  syncCursorPosition(block, focusNode) {
    const rootContent = this.findRootContent(block);
    if (focusNode && rootContent) {
      const offset = focusNode.getRangeEndOffset();
      rootContent.apply(new UpdateCursorPositionAction(focusNode, offset));
    }
  }
  /**
   * Walks up the parent chain to locate the nearest VegaRTEContent root.
   *
   * @param {RTETableBlock} block - Table block used as the starting point.
   * @returns {Nullable<VegaRTEContent>} Content root containing the table, if found.
   */
  findRootContent(block) {
    let currentParent = block.parent;
    while (currentParent) {
      if (currentParent instanceof VegaRTEContent) {
        return currentParent;
      }
      currentParent = currentParent.parent;
    }
  }
}

const DELETE_TABLE_ROW = 'DELETE_TABLE_ROW';
/**
 * Action class for deleting a specific table row.
 */
class DeleteTableRowAction extends ModifyContentAction {
  /**
   * Constructs an InsertTableRowAction.
   *
   * @param {RTETableRowBlock[]} rowsToBeRemoved - The rows to be removed from the table.
   */
  constructor(rowsToBeRemoved) {
    super();
    this.isFlushable = true;
    this.type = DELETE_TABLE_ROW;
    this.rowsToBeRemoved = rowsToBeRemoved;
  }
}

const INSERT_TABLE_ROW_INTO_DIFFERENT_SECTION = 'INSERT_TABLE_ROW_INTO_DIFFERENT_SECTION';
/**
 * Action class for inserting a new row into a table within the rich text editor.
 */
class InsertTableRowIntoDifferentSectionAction extends ModifyContentAction {
  /**
   * Constructs an InsertTableRowIntoDifferentSectionAction.
   *
   * @param {InsertTableRowDirection} insertDirection - The direction to insert the new row (above or below the current row).
   * @param {RTETableRowBlock[]} selectedRows - The currently selected rows in the table.
   */
  constructor(insertDirection, selectedRows = []) {
    super();
    this.isFlushable = true;
    this.type = INSERT_TABLE_ROW_INTO_DIFFERENT_SECTION;
    this.selectedRows = [];
    this.insertDirection = insertDirection;
    this.selectedRows = selectedRows;
  }
}

const INSERT_TABLE_ROW_INTO_SAME_SECTION = 'INSERT_TABLE_ROW_INTO_SAME_SECTION';
var InsertTableRowDirection;
(function (InsertTableRowDirection) {
  InsertTableRowDirection["ABOVE"] = "ABOVE";
  InsertTableRowDirection["BELOW"] = "BELOW";
})(InsertTableRowDirection || (InsertTableRowDirection = {}));
/**
 * Action class for inserting a new row into a table within the rich text editor.
 */
class InsertTableRowIntoSameSectionAction extends ModifyContentAction {
  /**
   * Constructs an InsertTableRowIntoSameSectionAction.
   *
   * @param {InsertTableRowDirection} insertDirection - The direction to insert the new row (above or below the current row).
   * @param {RTETableRowBlock[]} selectedRows - The currently selected rows in the table.
   */
  constructor(insertDirection, selectedRows = []) {
    super();
    this.isFlushable = true;
    this.type = INSERT_TABLE_ROW_INTO_SAME_SECTION;
    this.selectedRows = [];
    this.insertDirection = insertDirection;
    this.selectedRows = selectedRows;
  }
}

const TOGGLE_HEADER_ROW = 'TOGGLE_HEADER_ROW';
/**
 * Action to convert selected rows to header rows or revert them back to normal rows.
 */
class ToggleHeaderRowAction extends ModifyContentAction {
  constructor(selectedRows) {
    super();
    this.isFlushable = true;
    this.type = TOGGLE_HEADER_ROW;
    this.selectedRows = selectedRows;
  }
}

/**
 * Class representing a table body block in the rich text editor.
 */
class RTETableBodyBlock extends RTEBlock {
  constructor(id) {
    super(id);
    this.type = 'table-body';
    this.children = [];
  }
  /**
   * @inheritDoc
   */
  static from(block, options) {
    const tableBodyBlock = new RTETableBodyBlock(block.id);
    super.convertAnnotationsToMap(tableBodyBlock.annotationMap, Object.assign({}, block.annotations));
    tableBodyBlock.children = super.generateBlockChildren(block.children, options, tableBodyBlock);
    return tableBodyBlock;
  }
  /**
   * @inheritDoc
   */
  clone(parent) {
    const clonedBlock = new RTETableBodyBlock(this.id);
    clonedBlock.children = this.children.map((child) => child.clone(clonedBlock));
    clonedBlock.parent = parent;
    clonedBlock.annotationMap = super.cloneAnnotations();
    return clonedBlock;
  }
  /**
   * @inheritDoc
   */
  getLastNode() {
    return this.children[this.children.length - 1].getLastNode();
  }
  /**
   * @inheritDoc
   */
  isNotEmpty() {
    return this.children.length > 0;
  }
  /**
   * @inheritDoc
   */
  toHtml(options) {
    const childrenHtml = this.children.map((child) => child.toHtml(options)).join('');
    const attrStr = super.generateAttributeString(options);
    return `<tbody${attrStr}>${childrenHtml}</tbody>`;
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return Object.assign(Object.assign({}, super.toJSON()), { type: this.type, children: this.children.map((child) => child.toJSON()) });
  }
}

/**
 * Class representing a table head block in the rich text editor.
 */
class RTETableHeadBlock extends RTEBlock {
  constructor(id) {
    super(id);
    this.type = 'table-head';
    this.children = [];
  }
  /**
   * @inheritDoc
   */
  static from(block, options) {
    const headBlock = new RTETableHeadBlock(block.id);
    super.convertAnnotationsToMap(headBlock.annotationMap, Object.assign({}, block.annotations));
    headBlock.children = super.generateBlockChildren(block.children, options, headBlock);
    return headBlock;
  }
  /**
   * @inheritDoc
   */
  clone(parent) {
    const clonedBlock = new RTETableHeadBlock(this.id);
    clonedBlock.children = this.children.map((child) => child.clone(clonedBlock));
    clonedBlock.parent = parent;
    clonedBlock.annotationMap = super.cloneAnnotations();
    return clonedBlock;
  }
  /**
   * @inheritDoc
   */
  getLastNode() {
    return this.children[this.children.length - 1].getLastNode();
  }
  /**
   * @inheritDoc
   */
  isNotEmpty() {
    return this.children.length > 0;
  }
  /**
   * @inheritDoc
   */
  toHtml(options) {
    const childrenHtml = this.children
      .map((child) => {
      return child.toHtml(options);
    })
      .join('');
    const attrStr = super.generateAttributeString(options);
    return `<thead${attrStr}>${childrenHtml}</thead>`;
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return Object.assign(Object.assign({}, super.toJSON()), { type: this.type, children: this.children.map((child) => child.toJSON()) });
  }
}

/**
 * Class representing a table row block in the rich text editor.
 */
class RTETableRowBlock extends RTEBlock {
  constructor(id) {
    super(id);
    this.type = 'table-row';
    this.children = [];
  }
  /**
   * @inheritDoc
   */
  static from(block, options) {
    const rowBlock = new RTETableRowBlock(block.id);
    super.convertAnnotationsToMap(rowBlock.annotationMap, Object.assign({}, block.annotations));
    rowBlock.children = super.generateBlockChildren(block.children, options, rowBlock);
    return rowBlock;
  }
  /**
   * @inheritDoc
   */
  clone(parent) {
    const clonedBlock = new RTETableRowBlock(this.id);
    clonedBlock.children = this.children.map((child) => child.clone(clonedBlock));
    clonedBlock.parent = parent;
    clonedBlock.annotationMap = super.cloneAnnotations();
    return clonedBlock;
  }
  /**
   * @inheritDoc
   */
  getLastNode() {
    return this.children[this.children.length - 1].getLastNode();
  }
  /**
   * @inheritDoc
   */
  isNotEmpty() {
    return this.children.length > 0;
  }
  /**
   * @inheritDoc
   */
  toHtml(options) {
    const childrenHtml = this.children
      .map((child) => {
      return child.toHtml(options);
    })
      .join('');
    const attrStr = super.generateAttributeString(options);
    return `<tr${attrStr}>${childrenHtml}</tr>`;
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return Object.assign(Object.assign({}, super.toJSON()), { type: this.type, children: this.children.map((child) => child.toJSON()) });
  }
}

/**
 * Class representing a table cell annotation in the rich text editor.
 */
class RTETableCellAnnotation extends BlockAnnotation {
  constructor({ backgroundColor, padding, border, width, height, textAlign, verticalAlign, minWidth, boxSizing, } = {}, useInternalStyle = true) {
    super();
    this.type = RTETableExtensionAnnotationTypeEnum.CELL;
    this.useInternalStyle = useInternalStyle;
    this.backgroundColor = backgroundColor;
    this.width = width;
    this.height = height;
    this.border =
      useInternalStyle && border === undefined ? RTETableCellAnnotation.DEFAULT_BORDER : border;
    this.padding =
      useInternalStyle && padding === undefined ? RTETableCellAnnotation.DEFAULT_PADDING : padding;
    this.textAlign =
      useInternalStyle && textAlign === undefined
        ? RTETableCellAnnotation.DEFAULT_HORIZONTAL_TEXT_ALIGN
        : textAlign;
    this.verticalAlign =
      useInternalStyle && verticalAlign === undefined
        ? RTETableCellAnnotation.DEFAULT_VERTICAL_TEXT_ALIGN
        : verticalAlign;
    this.minWidth =
      useInternalStyle && minWidth === undefined
        ? RTETableCellAnnotation.DEFAULT_CELL_MIN_WIDTH
        : minWidth;
    this.boxSizing =
      useInternalStyle && boxSizing === undefined
        ? RTETableCellAnnotation.DEFAULT_BOX_SIZING
        : boxSizing;
  }
  /**
   * @inheritDoc
   */
  static from(cellAnnotation, useInternalStyle) {
    return [
      RTETableExtensionAnnotationTypeEnum.CELL,
      new RTETableCellAnnotation(cellAnnotation, useInternalStyle),
    ];
  }
  /**
   * Get the default styles for the table annotation.
   *
   * @param {boolean} isHexColor - Whether to return color values as hex codes.
   * @returns {AnnotationStyle} The default styles for the table annotation.
   */
  static getDefaultStyles(isHexColor = true) {
    return {
      padding: RTETableCellAnnotation.DEFAULT_PADDING,
      textAlign: RTETableCellAnnotation.DEFAULT_HORIZONTAL_TEXT_ALIGN,
      verticalAlign: RTETableCellAnnotation.DEFAULT_VERTICAL_TEXT_ALIGN,
      minWidth: RTETableCellAnnotation.DEFAULT_CELL_MIN_WIDTH,
      boxSizing: RTETableCellAnnotation.DEFAULT_BOX_SIZING,
      border: `${RTETableCellAnnotation.DEFAULT_BORDER.style} ${RTETableCellAnnotation.DEFAULT_BORDER.width} ${isHexColor
        ? RTETableCellAnnotation.DEFAULT_BORDER.color
        : RTETableCellAnnotation.DEFAULT_BORDER_RGB_COLOR}`,
    };
  }
  /**
   * Generates the CSS border string from the border properties.
   *
   * @returns {Nullable<string>} The CSS border string.
   */
  get borderStr() {
    if (!this.border)
      return null;
    return `${this.border.style || ''} ${this.border.width || ''} ${this.borderColorAnnotation.renderStyle().color}`.trim();
  }
  /**
   * Sets the background color using a color key.
   *
   * @param {Nullable<string>} colorKey - The key representing the background color.
   */
  set backgroundColor(colorKey) {
    this._backgroundColor = colorKey;
    this.backgroundColorAnnotation = new RTETableColorAnnotation(colorKey);
  }
  /**
   * Gets the background color value.
   *
   * @returns {Nullable<string>} The background color value.
   */
  get backgroundColor() {
    return this._backgroundColor;
  }
  /**
   * Sets the border properties and updates the border color annotation accordingly.
   *
   * @param {Nullable<VegaRTETableBorderType>} border - The border properties to set.
   */
  set border(border) {
    this._border = border;
    this.borderColorAnnotation = new RTETableColorAnnotation(border === null || border === void 0 ? void 0 : border.color);
  }
  /**
   * Gets the border properties.
   *
   * @returns {Nullable<VegaRTETableBorderType>} The border properties.
   */
  get border() {
    return this._border;
  }
  /**
   * @inheritDoc
   */
  clone() {
    return new RTETableCellAnnotation({
      backgroundColor: this.backgroundColor,
      padding: this.padding,
      border: this.border,
      width: this.width,
      height: this.height,
      textAlign: this.textAlign,
      verticalAlign: this.verticalAlign,
      minWidth: this.minWidth,
      boxSizing: this.boxSizing,
    }, this.useInternalStyle);
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return {
      tableCell: cleanObject({
        backgroundColor: this.backgroundColor,
        padding: this.padding,
        border: this.border,
        width: this.width,
        height: this.height,
        textAlign: this.textAlign,
        verticalAlign: this.verticalAlign,
        minWidth: this.minWidth,
        boxSizing: this.boxSizing,
      }),
    };
  }
  /**
   * @inheritDoc
   */
  renderStyle(options) {
    const backgroundColor = this.backgroundColorAnnotation.renderStyle().color;
    const style = {
      padding: this.padding,
      border: this.borderStr,
      width: this.width,
      height: this.height,
      textAlign: this.textAlign,
      verticalAlign: this.verticalAlign,
      minWidth: this.minWidth,
      boxSizing: this.boxSizing,
    };
    if (backgroundColor) {
      style.backgroundColor = backgroundColor;
    }
    if (!(options === null || options === void 0 ? void 0 : options.standalone)) {
      return cleanObject(this.removeDefaultValues(style), { cleanEmptyString: true });
    }
    return cleanObject(style, { cleanEmptyString: true });
  }
  /**
   * @inheritDoc
   */
  renderClass() {
    return null;
  }
  /**
   * Removes default values from the style object to avoid redundancy.
   *
   * @param {Record<string, Nullable<string>>} style - The style object to clean.
   * @returns {Record<string, Nullable<string>>} The cleaned style object.
   */
  removeDefaultValues(style) {
    const cleanedStyle = Object.assign({}, style);
    if (cleanedStyle.padding === RTETableCellAnnotation.DEFAULT_PADDING) {
      delete cleanedStyle.padding;
    }
    if (cleanedStyle.border ===
      `${RTETableCellAnnotation.DEFAULT_BORDER.style} ${RTETableCellAnnotation.DEFAULT_BORDER.width} ${RTETableCellAnnotation.DEFAULT_BORDER.color}`) {
      delete cleanedStyle.border;
    }
    if (cleanedStyle.textAlign === RTETableCellAnnotation.DEFAULT_HORIZONTAL_TEXT_ALIGN) {
      delete cleanedStyle.textAlign;
    }
    if (cleanedStyle.verticalAlign === RTETableCellAnnotation.DEFAULT_VERTICAL_TEXT_ALIGN) {
      delete cleanedStyle.verticalAlign;
    }
    if (cleanedStyle.minWidth === RTETableCellAnnotation.DEFAULT_CELL_MIN_WIDTH) {
      delete cleanedStyle.minWidth;
    }
    if (cleanedStyle.boxSizing === RTETableCellAnnotation.DEFAULT_BOX_SIZING) {
      delete cleanedStyle.boxSizing;
    }
    return cleanedStyle;
  }
}
RTETableCellAnnotation.DEFAULT_PADDING = '12px';
RTETableCellAnnotation.DEFAULT_BORDER = {
  style: 'solid',
  width: '1px',
  color: '#ddd',
};
RTETableCellAnnotation.DEFAULT_BORDER_RGB_COLOR = 'rgb(221, 221, 221)'; // Equivalent RGB for #ddd
RTETableCellAnnotation.DEFAULT_HORIZONTAL_TEXT_ALIGN = 'left';
RTETableCellAnnotation.DEFAULT_VERTICAL_TEXT_ALIGN = 'middle';
RTETableCellAnnotation.DEFAULT_CELL_MIN_WIDTH = '55px';
RTETableCellAnnotation.DEFAULT_BOX_SIZING = 'border-box';

/**
 * Class representing a table cell block in the rich text editor.
 */
class RTETableCellBlock extends RTEBlock {
  constructor(id, options) {
    super(id);
    this.type = 'table-cell';
    this.children = [];
    const { autoMatchFormat } = options || { autoMatchFormat: true };
    if (autoMatchFormat) {
      this.annotationMap.set(RTETableExtensionAnnotationTypeEnum.CELL, new RTETableCellAnnotation());
    }
  }
  /**
   * @inheritDoc
   */
  static from(block, options) {
    var _a;
    const tableCellBlock = new RTETableCellBlock(block.id, options);
    super.convertAnnotationsToMap(tableCellBlock.annotationMap, Object.assign({}, block.annotations));
    if ((_a = block.annotations) === null || _a === void 0 ? void 0 : _a.tableCell) {
      tableCellBlock.annotationMap.set(...RTETableCellAnnotation.from(block.annotations.tableCell, options === null || options === void 0 ? void 0 : options.autoMatchFormat));
    }
    tableCellBlock.children = super.generateBlockChildren(block.children, options, tableCellBlock);
    return tableCellBlock;
  }
  /**
   * @inheritDoc
   */
  clone(parent) {
    const clonedBlock = new RTETableCellBlock(this.id);
    clonedBlock.children = this.children.map((child) => child.clone(clonedBlock));
    clonedBlock.parent = parent;
    clonedBlock.annotationMap = super.cloneAnnotations();
    return clonedBlock;
  }
  /**
   * @inheritDoc
   */
  getLastNode() {
    return this.children[this.children.length - 1].getLastNode();
  }
  /**
   * @inheritDoc
   */
  isNotEmpty() {
    return this.children.length > 0;
  }
  /**
   * Get the rowSpan of the table cell
   *
   * @returns {number} - rowSpan value
   */
  get rowSpan() {
    const rowSpan = this.getCustomAttributeByName('rowspan');
    return !isNaN(Number(rowSpan)) ? Math.max(Number(rowSpan), 1) : 1;
  }
  /**
   * Get the colSpan of the table cell
   *
   * @returns {number} - colSpan value
   */
  get colSpan() {
    const colSpan = this.getCustomAttributeByName('colspan');
    return !isNaN(Number(colSpan)) ? Math.max(Number(colSpan), 1) : 1;
  }
  /**
   * @inheritDoc
   */
  toHtml(options) {
    const childrenHtml = this.children.map((child) => child.toHtml(options)).join('');
    const attrStr = super.generateAttributeString(options);
    return `<td${attrStr}>${childrenHtml}</td>`;
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return Object.assign(Object.assign({}, super.toJSON()), { type: this.type, children: this.children.map((child) => child.toJSON()) });
  }
  /**
   * Get custom attribute by name
   *
   * @param {string} attrName - attribute name
   * @returns {Nullable<string>} - attribute value
   */
  getCustomAttributeByName(attrName) {
    const customAttrAnnotation = this.getCustomAttributesAnnotation();
    if (customAttrAnnotation) {
      const customAttributes = customAttrAnnotation.toJSON()['customAttribute'] || {};
      return customAttributes[attrName];
    }
  }
}

/**
 * Class representing a table head cell annotation in the rich text editor.
 */
class RTETableHeadCellAnnotation extends RTETableCellAnnotation {
  constructor(annotation = {}, useInternalStyle = true) {
    super(annotation, useInternalStyle);
  }
  /**
   * @inheritDoc
   */
  static from(cellAnnotation, useInternalStyle) {
    return [
      RTETableExtensionAnnotationTypeEnum.CELL,
      new RTETableHeadCellAnnotation(cellAnnotation, useInternalStyle),
    ];
  }
  /**
   * Gets the default background color for table head cells based on the current theme mode.
   *
   * @returns {string} The default background color for table head cells.
   */
  static getDefaultBackgroundColor() {
    return VegaInternalThemeManager.isDarkMode()
      ? RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR.dark
      : RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR.light;
  }
  /**
   * @inheritDoc
   */
  clone() {
    return new RTETableHeadCellAnnotation({
      backgroundColor: this.backgroundColor,
      padding: this.padding,
      border: this.border,
      width: this.width,
      height: this.height,
      textAlign: this.textAlign,
      verticalAlign: this.verticalAlign,
      minWidth: this.minWidth,
      boxSizing: this.boxSizing,
    }, this.useInternalStyle);
  }
  /**
   * @inheritDoc
   */
  renderStyle(options) {
    var _a;
    const styles = super.renderStyle(options);
    return cleanObject(Object.assign(Object.assign({}, styles), { backgroundColor: (_a = styles.backgroundColor) !== null && _a !== void 0 ? _a : RTETableHeadCellAnnotation.getDefaultBackgroundColor() }));
  }
}

/**
 * Class representing a table head block in the rich text editor.
 */
class RTETableHeadCellBlock extends RTETableCellBlock {
  constructor(id, options) {
    super(id, options);
    this.type = 'table-head-cell';
    const { autoMatchFormat } = options || { autoMatchFormat: true };
    if (autoMatchFormat) {
      this.annotationMap.set(RTETableExtensionAnnotationTypeEnum.CELL, new RTETableHeadCellAnnotation());
    }
  }
  /**
   * @inheritDoc
   */
  static from(block, options) {
    var _a;
    const headCellBlock = new RTETableHeadCellBlock(block.id, options);
    super.convertAnnotationsToMap(headCellBlock.annotationMap, Object.assign({}, block.annotations));
    if ((_a = block.annotations) === null || _a === void 0 ? void 0 : _a.tableCell) {
      headCellBlock.annotationMap.set(...RTETableHeadCellAnnotation.from(block.annotations.tableCell, options === null || options === void 0 ? void 0 : options.autoMatchFormat));
    }
    headCellBlock.children = super.generateBlockChildren(block.children, options, headCellBlock);
    return headCellBlock;
  }
  /**
   * @inheritDoc
   */
  clone(parent) {
    const clonedBlock = new RTETableHeadCellBlock(this.id);
    clonedBlock.children = this.children.map((child) => child.clone(clonedBlock));
    clonedBlock.parent = parent;
    clonedBlock.annotationMap = super.cloneAnnotations();
    return clonedBlock;
  }
  /**
   * @inheritDoc
   */
  toHtml(options) {
    const childrenHtml = this.children.map((child) => child.toHtml(options)).join('');
    const attrStr = super.generateAttributeString(options);
    return `<th${attrStr}>${childrenHtml}</th>`;
  }
  /**
   * @inheritDoc
   */
  toJSON() {
    return Object.assign(Object.assign({}, super.toJSON()), { type: this.type, children: this.children.map((child) => child.toJSON()) });
  }
}

const MERGE_CELLS = 'MERGE_CELLS';
/**
 * Action to merge cells into the RTETable.
 */
class MergeCellsAction extends ModifyContentAction {
  constructor(targetCell, mergeCells, colSpan, rowSpan, direction) {
    super();
    this.type = MERGE_CELLS;
    this.isFlushable = true;
    this.targetCell = targetCell;
    this.mergeCells = mergeCells;
    this.colSpan = colSpan;
    this.rowSpan = rowSpan;
    this.direction = direction;
  }
}

var MergeCellsOperationType;
(function (MergeCellsOperationType) {
  MergeCellsOperationType["MERGE_CELLS"] = "MERGE_CELLS";
  MergeCellsOperationType["MERGE_CELL_UP"] = "MERGE_CELL_UP";
  MergeCellsOperationType["MERGE_CELL_RIGHT"] = "MERGE_CELL_RIGHT";
  MergeCellsOperationType["MERGE_CELL_DOWN"] = "MERGE_CELL_DOWN";
  MergeCellsOperationType["MERGE_CELL_LEFT"] = "MERGE_CELL_LEFT";
})(MergeCellsOperationType || (MergeCellsOperationType = {}));
/**
 * Event handler for merge cells operations in a table.
 */
class MergeCellsOperationEventHandler extends SettingEventHandler {
  /**
   * @inheritDoc
   */
  canHandle(action) {
    return action[0] === TableSettingType.MERGE_CELLS;
  }
  /**
   * @inheritDoc
   */
  execute(action, extensionContext) {
    const selectedCells = extensionContext.tableSelection.getSelectedCells();
    const operation = action[1];
    switch (operation) {
      case MergeCellsOperationType.MERGE_CELL_UP:
      case MergeCellsOperationType.MERGE_CELL_RIGHT:
      case MergeCellsOperationType.MERGE_CELL_DOWN:
      case MergeCellsOperationType.MERGE_CELL_LEFT:
        {
          const mergeCells = this.getDirectionMergeCells(operation, selectedCells[0]);
          this.handleMergeCells(mergeCells, operation);
        }
        break;
      default:
        {
          if (selectedCells.length > 1) {
            this.handleMergeCells(selectedCells, MergeCellsOperationType.MERGE_CELLS);
          }
        }
        break;
    }
  }
  /**
   * Get the adjacent cell in the specified direction.
   *
   * @param {MergeCellsOperationType} direction - The direction to look for the adjacent cell.
   * @param {RTETableCellBlock | RTETableHeadCellBlock} cell - The current cell.
   * @returns {Array<RTETableCellBlock | RTETableHeadCellBlock>} Array containing the cells to merge.
   */
  getDirectionMergeCells(direction, cell) {
    const adjacent = getAdjacentCell(cell, direction);
    if (!adjacent) {
      return [cell];
    }
    switch (direction) {
      case MergeCellsOperationType.MERGE_CELL_UP:
        return [adjacent, cell];
      case MergeCellsOperationType.MERGE_CELL_DOWN:
        return [cell, adjacent];
      case MergeCellsOperationType.MERGE_CELL_LEFT:
        return [adjacent, cell];
      default:
        return [cell, adjacent];
    }
  }
  /**
   * Handle the merge cells operation by creating and applying a MergeCellsAction.
   *
   * @param {Array<RTETableCellBlock | RTETableHeadCellBlock>} mergeCells - The cells to merge.
   * @param {MergeCellsOperationType} direction - The merge cell direction.
   */
  handleMergeCells(mergeCells, direction) {
    if (mergeCells.length < 2) {
      return;
    }
    const rectInfo = getRectangularBounds(mergeCells);
    const { minRow, maxRow, minCol, maxCol, targetCell } = rectInfo;
    const colSpan = maxCol - minCol + 1;
    const rowSpan = maxRow - minRow + 1;
    const action = new MergeCellsAction(targetCell, mergeCells, colSpan, rowSpan, direction);
    this.applyActionOnTable(action, targetCell);
  }
  /**
   * Apply the specified action on the table containing the selected cell.
   *
   * @param {MergeCellsAction} action - The action to apply.
   * @param {RTETableCellBlock | RTETableHeadCellBlock} selectedCell - The selected table cell.
   */
  applyActionOnTable(action, selectedCell) {
    const table = getParentBlockByType(selectedCell, RTETableBlock);
    if (table) {
      table.apply(action);
    }
  }
}

/**
 * Recursively searches for a parent block of a specific type.
 *
 * @typedef T - Generic type extending RTEBlock.
 * @param {RTEBlock} block - The starting block to search from.
 * @param {ClassType<unknown>} dtoClass - The class type to match the parent block against.
 * @returns {T | null} - The found parent block of the specified type, or null if not found.
 */
function getParentBlockByType(block, dtoClass) {
  if (block) {
    if (block instanceof dtoClass) {
      return block;
    }
    else {
      return getParentBlockByType(block.parent, dtoClass);
    }
  }
  return null;
}
/**
 * Generate the table body with the specified number of rows and columns.
 *
 * @param {number} rowCount - The number of rows in the table body.
 * @param {number} columnCount - The number of columns in the table body.
 * @returns {VegaRTETableBodyBlock} The generated table body block.
 */
function generateTableBody(rowCount, columnCount) {
  return {
    id: generateUUID(),
    type: 'table-body',
    children: Array.from({ length: rowCount }, () => generateTableRow(columnCount)),
  };
}
/**
 * Create a table row block with the specified number of columns and cell type.
 *
 * @param {number} columnCount - The number of columns in the row.
 * @returns {VegaRTETableRowBlock} The created table row block.
 */
function generateTableRow(columnCount) {
  return {
    id: generateUUID(),
    type: 'table-row',
    children: Array.from({ length: columnCount }, () => getDefaultCellBlockTemplate('table-cell')),
  };
}
/**
 * Get all table rows from a table block (including rows from all table bodies and headers).
 *
 * @param {RTETableBlock} tableBlock - The table block.
 * @returns {RTETableRowBlock[]} Array of all table row blocks.
 */
function getAllTableRows(tableBlock) {
  return tableBlock.children
    .filter((child) => child instanceof RTETableBodyBlock || child instanceof RTETableHeadBlock)
    .flatMap((body) => body.children);
}
/**
 * Find the first node within a block recursively.
 *
 * @param {Nullable<RTEBlock>} block - The block to find the first node in.
 * @returns {Nullable<RTENode>} The focusable node within the block.
 */
function getFirstNode(block) {
  if (!block || !block.children || !block.children[0])
    return null;
  const firstNode = block.children[0];
  if (firstNode instanceof RTENode) {
    return firstNode;
  }
  return getFirstNode(firstNode);
}
/**
 * Find a cell block by its ID across all table rows.
 *
 * @param {RTETableRowBlock[]} allTableRows - All table rows to search within.
 * @param {string} cellId - The unique identifier of the cell to find.
 * @returns {Nullable<RTETableCellBlock | RTETableHeadCellBlock>} The found cell block, or null if not found.
 */
function findCellBlockById(allTableRows, cellId) {
  for (const row of allTableRows) {
    const found = row.children.find((cell) => cell.id === cellId);
    if (found) {
      return found;
    }
  }
  return null;
}
/**
 * Get the default cell block template.
 *
 * @param {string} cellType - The type of the cell block.
 * @returns {VegaRTETableCellBlock} The default cell block template.
 */
function getDefaultCellBlockTemplate(cellType) {
  const id = generateUUID();
  return {
    id,
    type: cellType,
    children: [
      {
        id: `${id}-p`,
        type: 'paragraph',
        nodes: [
          {
            id: `${id}-p-t`,
            type: 'text',
            text: '',
          },
        ],
      },
    ],
  };
}
/**
 * Get the actual col span and row span of a cell.
 *
 * @param {RTETableCellBlock | RTETableHeadCellBlock} cell - The cell to check.
 * @returns {CellSpan} The actual span values.
 */
function getCellSpan(cell) {
  return { colSpan: cell.colSpan, rowSpan: cell.rowSpan };
}
/**
 * Get the actual column position of a cell considering previous cells' colspan
 * and cells from previous rows with rowspan that extend into the current row.
 *
 * @param {RTETableCellBlock | RTETableHeadCellBlock} cell - The cell to check.
 * @param {RTETableRowBlock[]} allRows - The table all rows.
 * @param {string[][]} grid - The 2D grid representation of the table
 * @returns {number} The actual column position.
 */
function getActualColumnPosition(cell, allRows, grid) {
  const tableGrid = grid !== null && grid !== void 0 ? grid : buildTableGrid(allRows);
  for (let row = 0; row < tableGrid.length; row++) {
    const cols = tableGrid[row];
    for (let col = 0; col < cols.length; col++) {
      if (cols[col] === cell.id) {
        return col;
      }
    }
  }
  return -1;
}
/**
 * Build a 2D grid representation of a table section where each occupied position
 * contains the cell id covering that (row, col) coordinate, accounting for colSpan/rowSpan.
 *
 * @param {RTETableRowBlock[]} allRows - All rows in the current table section.
 * @returns {string[][]} The table grid.
 */
function buildTableGrid(allRows) {
  const grid = [];
  allRows.forEach((row, rowIndex) => {
    if (!grid[rowIndex]) {
      grid[rowIndex] = [];
    }
    let colIndex = 0;
    row.children.forEach((cell) => {
      const { colSpan, rowSpan } = getCellSpan(cell);
      while (grid[rowIndex][colIndex] !== undefined) {
        colIndex++;
      }
      for (let r = 0; r < rowSpan; r++) {
        for (let c = 0; c < colSpan; c++) {
          if (!grid[rowIndex + r]) {
            grid[rowIndex + r] = [];
          }
          grid[rowIndex + r][colIndex + c] = cell.id;
        }
      }
      colIndex += colSpan;
    });
  });
  return grid;
}
/**
 * Get the adjacent cell in the specified direction based on the table matrix.
 *
 * @param {RTETableCellBlock | RTETableHeadCellBlock} cell - The current cell.
 * @param {AdjacentCellDirection} direction - The direction to locate the adjacent cell.
 * @returns {RTETableCellBlock | RTETableHeadCellBlock | null} The adjacent cell or null.
 */
function getAdjacentCell(cell, direction) {
  if (!cell) {
    return null;
  }
  const row = cell.parent;
  const sectionRows = row.parent.children;
  const rowIndex = sectionRows.indexOf(row);
  const { colSpan, rowSpan } = getCellSpan(cell);
  const cellColPosition = getActualColumnPosition(cell, sectionRows);
  let targetRowIndex = rowIndex;
  let targetColPosition = cellColPosition;
  switch (direction) {
    case MergeCellsOperationType.MERGE_CELL_LEFT:
      targetColPosition = cellColPosition - 1;
      break;
    case MergeCellsOperationType.MERGE_CELL_RIGHT:
      targetColPosition = cellColPosition + colSpan;
      break;
    case MergeCellsOperationType.MERGE_CELL_UP:
      targetRowIndex = rowIndex - 1;
      break;
    default:
      targetRowIndex = rowIndex + rowSpan;
      break;
  }
  return findCellAtPosition(sectionRows, targetRowIndex, targetColPosition);
}
/**
 * Find the cell that covers the specified matrix position.
 *
 * @param {RTETableRowBlock[]} rows - Rows in the current table section.
 * @param {number} targetRowIndex - Target matrix row index.
 * @param {number} targetColPosition - Target matrix column position.
 * @returns {RTETableCellBlock | RTETableHeadCellBlock | null} The covering cell or null.
 */
function findCellAtPosition(rows, targetRowIndex, targetColPosition) {
  const tableGrid = buildTableGrid(rows);
  for (let r = 0; r < rows.length; r++) {
    const currentRow = rows[r];
    for (const candidate of currentRow.children) {
      const { colSpan, rowSpan } = getCellSpan(candidate);
      const candidateColPosition = getActualColumnPosition(candidate, rows, tableGrid);
      const candidateRowStart = r;
      const candidateRowEnd = r + rowSpan - 1;
      const candidateColEnd = candidateColPosition + colSpan - 1;
      const isSameMatrixRow = targetRowIndex >= candidateRowStart && targetRowIndex <= candidateRowEnd;
      const isTargetColumnCovered = targetColPosition >= candidateColPosition && targetColPosition <= candidateColEnd;
      if (isSameMatrixRow && isTargetColumnCovered) {
        return candidate;
      }
    }
  }
  return null;
}
/**
 * Get the rectangular bounds of selected cells.
 * Calculates the bounding box (minRow, maxRow, minCol, maxCol) and returns related information.
 *
 * @param {RTETableCellBlock[] | RTETableHeadCellBlock[]} selectedCells - The selected table cells.
 * @returns {RectangularBounds} The rectangular bounds' information.
 */
function getRectangularBounds(selectedCells) {
  const firstCell = selectedCells[0];
  const firstRow = firstCell.parent;
  const table = firstRow.parent;
  const allRows = table.children;
  const tableGrid = buildTableGrid(allRows);
  let minRow = Number.POSITIVE_INFINITY;
  let maxRow = -1;
  let minCol = Number.POSITIVE_INFINITY;
  let maxCol = -1;
  const coveredPositions = new Set();
  selectedCells.forEach((cell) => {
    const row = cell.parent;
    const rowIndex = allRows.indexOf(row);
    const actualColPosition = getActualColumnPosition(cell, allRows, tableGrid);
    const { colSpan, rowSpan } = getCellSpan(cell);
    const cellMinRow = rowIndex;
    const cellMaxRow = rowIndex + rowSpan - 1;
    const cellMinCol = actualColPosition;
    const cellMaxCol = actualColPosition + colSpan - 1;
    for (let r = cellMinRow; r <= cellMaxRow; r++) {
      for (let c = cellMinCol; c <= cellMaxCol; c++) {
        coveredPositions.add(`${r},${c}`);
      }
    }
    minRow = Math.min(minRow, cellMinRow);
    maxRow = Math.max(maxRow, cellMaxRow);
    minCol = Math.min(minCol, cellMinCol);
    maxCol = Math.max(maxCol, cellMaxCol);
  });
  const targetCell = selectedCells[0];
  return {
    minRow,
    maxRow,
    minCol,
    maxCol,
    targetCell,
    coveredPositions,
  };
}
/**
 * Calculate the total number of columns in the table.
 * Accounts for cells with col span.
 *
 * @param {RTETableBlock} table - The table block.
 * @returns {number} The total number of columns in the table.
 */
function getTableColumnCount(table) {
  const rows = getAllTableRows(table);
  // Calculate the total columns from the first row, accounting for col span
  let totalColumns = 0;
  const firstRow = rows[0];
  for (const cell of firstRow.children) {
    const { colSpan } = getCellSpan(cell);
    totalColumns += colSpan;
  }
  return totalColumns;
}
/**
 * Check if the selected cells form a rectangular area.
 * Considers cells with col span and row span.
 *
 * @param {RTETableCellBlock[] | RTETableHeadCellBlock[]} selectedCells - The selected table cells.
 * @returns {boolean} True if the selected cells form a rectangle, false otherwise.
 */
function isRectangularSelection(selectedCells) {
  if (selectedCells.length === 1) {
    return true;
  }
  const bounds = getRectangularBounds(selectedCells);
  const { minRow, maxRow, minCol, maxCol, coveredPositions } = bounds;
  const expectedPositions = (maxRow - minRow + 1) * (maxCol - minCol + 1);
  if (coveredPositions.size !== expectedPositions) {
    return false;
  }
  return true;
}
/**
 * Set the col span and row span attributes for a target cell.
 * When colSpan equals the table's total columns, rowSpan is removed.
 *
 * @param {RTETableCellBlock | RTETableHeadCellBlock} targetCell - The target cell to set attributes on.
 * @param {number} colSpan - The column span value.
 * @param {number} rowSpan - The row span value.
 * @param {RTETableBlock} table - The table block.
 * @param {boolean} insertColumn - Whether the operation is an insert-column action.
 */
function setSpanAttributes(targetCell, colSpan, rowSpan, table, insertColumn) {
  const existingAnnotation = targetCell.annotationMap.get(CommonAnnotationTypeEnum.CUSTOM_ATTRIBUTE);
  const existingAttrs = existingAnnotation
    ? Object.assign({}, existingAnnotation['customAttribute']) : {};
  delete existingAttrs.colspan;
  delete existingAttrs.rowspan;
  if (colSpan > 1) {
    existingAttrs.colspan = String(colSpan);
  }
  // When colspan equals table column count, don't set rowspan
  const tableColumnCount = getTableColumnCount(table) + (insertColumn ? 1 : 0);
  if (rowSpan > 1 && colSpan !== tableColumnCount) {
    existingAttrs.rowspan = String(rowSpan);
  }
  if (Object.keys(existingAttrs).length > 0) {
    const customAttributeAnnotation = new CustomAttributeAnnotation(existingAttrs);
    targetCell.annotationMap.set(CommonAnnotationTypeEnum.CUSTOM_ATTRIBUTE, customAttributeAnnotation);
  }
  else {
    targetCell.annotationMap.delete(CommonAnnotationTypeEnum.CUSTOM_ATTRIBUTE);
  }
}
/**
 * Create a new cell of the specified type.
 *
 * @param {string} cellType - The type of cell ('table-cell' or 'table-head-cell').
 * @returns {RTETableCellBlock | RTETableHeadCellBlock} The newly created cell.
 */
function createNewCell(cellType) {
  const cellTemplate = getDefaultCellBlockTemplate(cellType);
  if (cellType === 'table-head-cell') {
    return RTETableHeadCellBlock.from(cellTemplate);
  }
  return RTETableCellBlock.from(cellTemplate);
}
/**
 * Find the first logical column index in a row that is not a header cell.
 *
 * @param {string[]} gridRow - The grid row array.
 * @param {RTETableRowBlock} row - The table row block.
 * @param {number} maxColLength - The maximum number of columns.
 * @returns {number} The first non-header logical column index, or -1 if not found.
 */
function findFirstBodyColIndex(gridRow, row, maxColLength) {
  for (let colIndex = 0; colIndex < maxColLength; colIndex++) {
    const cellId = gridRow[colIndex];
    const cellBlock = row.children.find((c) => c.id === cellId);
    if (cellBlock && !(cellBlock instanceof RTETableHeadCellBlock)) {
      return colIndex;
    }
  }
  return -1;
}
/**
 * Build a map of cell id to its first logical column index in the table grid.
 *
 * @param {string[][]} tableGrid - The table grid.
 * @returns {Map<string, number>} Cell id to start column index.
 */
function buildCellStartColumnMap(tableGrid) {
  const cellStartColMap = new Map();
  tableGrid.forEach((gridRow) => {
    for (let col = 0; col < gridRow.length; col++) {
      const cellId = gridRow[col];
      if (cellId && !cellStartColMap.has(cellId)) {
        cellStartColMap.set(cellId, col);
      }
    }
  });
  return cellStartColMap;
}
/**
 * Find the index range of the table selection.
 * Returns the starting and ending indices of the selected cells.
 *
 * @param {(RTETableCellBlock | RTETableHeadCellBlock)[]} selectedCells - The selected table cells.
 * @param {RTETableBlock} table - The table block
 * @param {RTETableRowBlock[]} allTableRows - All table rows.
 * @param {string[][]} grid - The 2D grid representation of the table
 * @returns {[number, number]} A tuple containing the start and end indices.
 */
function getSelectedCellsBoundary(selectedCells, table, allTableRows, grid) {
  if (selectedCells.length === 0) {
    return [0, -1];
  }
  const tableRows = allTableRows ? allTableRows : getAllTableRows(table);
  const tableGrid = grid !== null && grid !== void 0 ? grid : buildTableGrid(tableRows);
  let minCol = Number.POSITIVE_INFINITY;
  let maxCol = Number.NEGATIVE_INFINITY;
  selectedCells.forEach((cell) => {
    const logicalCol = getActualColumnPosition(cell, tableRows, tableGrid);
    minCol = Math.min(minCol, logicalCol);
    maxCol = Math.max(maxCol, logicalCol);
  });
  return [minCol, maxCol];
}

var RowOperationType;
(function (RowOperationType) {
  RowOperationType["HEADER_ROW"] = "HEADER_ROW";
  RowOperationType["ADD_ROW_ABOVE"] = "ADD_ROW_ABOVE";
  RowOperationType["ADD_ROW_BELOW"] = "ADD_ROW_BELOW";
  RowOperationType["DELETE_ROW"] = "DELETE_ROW";
  RowOperationType["SELECT_ROW"] = "SELECT_ROW";
})(RowOperationType || (RowOperationType = {}));
/**
 * Event handler for row operations in a table.
 */
class RowOperationEventHandler extends SettingEventHandler {
  /**
   * @inheritDoc
   */
  canHandle(action) {
    return action[0] === TableSettingType.ROW;
  }
  /**
   * @inheritDoc
   */
  execute(action, extensionContext) {
    const operation = action[1];
    switch (operation) {
      case RowOperationType.ADD_ROW_ABOVE:
      case RowOperationType.ADD_ROW_BELOW:
        this.handleInsertRow(operation, extensionContext);
        break;
      case RowOperationType.DELETE_ROW:
        this.handleDeleteRow(extensionContext);
        break;
      case RowOperationType.HEADER_ROW:
        this.handleToggleHeader(extensionContext);
        break;
      case RowOperationType.SELECT_ROW:
        this.handleSelectRow(extensionContext);
        break;
    }
  }
  /**
   * Adds a new row to the table at the specified position.
   *
   * @param {RowOperationType} direction - The position to insert the new row (above or below).
   * @param {RTETableExtensionContext} extensionContext - The extension context.
   */
  handleInsertRow(direction, extensionContext) {
    const selectedRows = this.getAllSelectedRows(extensionContext);
    if (selectedRows.length > 0) {
      const insertDirection = direction === RowOperationType.ADD_ROW_ABOVE
        ? InsertTableRowDirection.ABOVE
        : InsertTableRowDirection.BELOW;
      // The reference block will control where to insert the new row
      const refBlock = insertDirection === InsertTableRowDirection.ABOVE
        ? selectedRows[0]
        : selectedRows[selectedRows.length - 1];
      const refBlockIsBodyRow = refBlock.parent instanceof RTETableBodyBlock;
      const action = this.shouldInsertHeaderRow(refBlock, insertDirection) || refBlockIsBodyRow
        ? new InsertTableRowIntoSameSectionAction(insertDirection, selectedRows)
        : new InsertTableRowIntoDifferentSectionAction(insertDirection, selectedRows);
      this.applyActionToTable(selectedRows[0], action);
    }
  }
  /**
   * Checks if a header row should be inserted based on the selected rows and position.
   *
   * @param {RTETableRowBlock} refBlock - The reference table row block.
   * @param {InsertTableRowDirection} direction - The direction to insert the new row (above or below).
   * @returns {boolean} True if a header row should be inserted, false otherwise.
   */
  shouldInsertHeaderRow(refBlock, direction) {
    if (direction === InsertTableRowDirection.ABOVE) {
      return refBlock.parent instanceof RTETableHeadBlock;
    }
    else {
      const parentBlock = refBlock.parent;
      return (parentBlock instanceof RTETableHeadBlock &&
        parentBlock.children[parentBlock.children.length - 1] !== refBlock);
    }
  }
  /**
   * Deletes the selected row(s) from the table.
   *
   * @param {RTETableExtensionContext} extensionContext - The extension context.
   */
  handleDeleteRow(extensionContext) {
    const selectedRows = this.getAllSelectedRows(extensionContext);
    if (selectedRows.length) {
      const action = new DeleteTableRowAction(selectedRows);
      this.applyActionToTable(selectedRows[0], action);
    }
  }
  /**
   * Converts selected rows to header rows or reverts them back to normal rows.
   *
   * @param {RTETableExtensionContext} extensionContext - The extension context.
   */
  handleToggleHeader(extensionContext) {
    const selectedRows = this.getAllSelectedRows(extensionContext);
    if (selectedRows.length > 0) {
      const action = new ToggleHeaderRowAction(selectedRows);
      this.applyActionToTable(selectedRows[0], action);
    }
  }
  /**
   * Selects the focus row(s) in the table.
   *
   * @param {RTETableExtensionContext} extensionContext - The extension context.
   */
  handleSelectRow(extensionContext) {
    const selectedRows = this.getAllSelectedRows(extensionContext);
    if (selectedRows.length > 0 && extensionContext && extensionContext.tableSelection) {
      const allCells = selectedRows.flatMap((row) => row.children);
      extensionContext.tableSelection.setSelectedCells(allCells);
    }
  }
  /**
   * Get all selected table rows.
   *
   * @param {RTETableExtensionContext} extensionContext - The extension context.
   * @returns {RTETableRowBlock[]} The selected table row blocks.
   */
  getAllSelectedRows(extensionContext) {
    const selectedRows = new Set();
    if (extensionContext && extensionContext.tableSelection) {
      const { tableSelection } = extensionContext;
      const selectedCells = tableSelection.getSelectedCells();
      selectedCells.forEach((cell) => {
        const rowBlock = getParentBlockByType(cell, RTETableRowBlock);
        if (rowBlock) {
          selectedRows.add(rowBlock);
        }
      });
    }
    return Array.from(selectedRows);
  }
  /**
   * Applies the given action to the table containing the reference block.
   *
   * @param {RTEBlock} refBlock - The reference block within the table.
   * @param {ModifyContentAction} action - The action to apply to the table.
   */
  applyActionToTable(refBlock, action) {
    const table = getParentBlockByType(refBlock, RTETableBlock);
    if (table) {
      table.apply(action);
    }
  }
}

const REPLACE_TABLE_CELL = 'REPLACE_TABLE_CELL';
/**
 * Action to replace a fully overlapped table cell.
 */
class ReplaceTableCellAction extends ModifyContentAction {
  constructor(payload) {
    super();
    this.isFlushable = true;
    this.type = REPLACE_TABLE_CELL;
    this.payload = payload;
  }
}

const SPLIT_TABLE_CELL = 'SPLIT_TABLE_CELL';
/**
 * Action to split a partially overlapped table cell.
 */
class SplitTableCellAction extends ModifyContentAction {
  constructor(payload) {
    super();
    this.isFlushable = true;
    this.type = SPLIT_TABLE_CELL;
    this.payload = payload;
  }
}

/**
 * Abstract base strategy for handling table column operations.
 * Provides common functionality for all column-related strategies.
 */
class TableColumnStrategy extends ActionHandleStrategy {
  /**
   * Finds the index range of cells within a table row.
   * Returns the start and end indices of the given cell range.
   *
   * @param {(RTETableCellBlock | RTETableHeadCellBlock)[]} cellRange - The range of table cells to find indices for.
   * @param {RTETableRowBlock[]} allTableRows - All table rows.
   * @param {string[][]} grid - The 2D grid representation of the table
   * @returns {[number, number]} A tuple containing the start and end indices.
   */
  getBoundaryCellColumnRange(cellRange, allTableRows, grid) {
    let minCol = Number.POSITIVE_INFINITY;
    let maxCol = Number.NEGATIVE_INFINITY;
    cellRange.forEach((cell) => {
      const logicalCol = getActualColumnPosition(cell, allTableRows, grid);
      minCol = Math.min(minCol, logicalCol);
      maxCol = Math.max(maxCol, logicalCol);
    });
    return [minCol, maxCol];
  }
}

/**
 * Strategy to handle the toggle of header state of a table column.
 */
class ToggleHeaderTableColumnStrategy extends TableColumnStrategy {
  /**
   * Check if all cells in the column containing the selected cell are head cells.
   *
   * @param {(RTETableCellBlock | RTETableHeadCellBlock)[]} selectedCellRange - The range of selected table cell blocks.
   * @returns {boolean} True if all cells in the column containing the selected cell are head cells, false otherwise.
   */
  static isFullHeaderSelection(selectedCellRange) {
    if (selectedCellRange.length === 0) {
      return false;
    }
    const firstSelectedCell = selectedCellRange[0];
    const table = getParentBlockByType(firstSelectedCell, RTETableBlock);
    if (table) {
      const allTableRows = getAllTableRows(table);
      const tableGrid = buildTableGrid(allTableRows);
      const tableCellsById = new Map();
      allTableRows.forEach((row) => {
        row.children.forEach((cell) => tableCellsById.set(cell.id, cell));
      });
      const [minCol, maxCol] = getSelectedCellsBoundary(selectedCellRange, table, allTableRows, tableGrid);
      for (const gridRow of tableGrid) {
        for (let col = minCol; col <= maxCol; col++) {
          const cell = tableCellsById.get(gridRow[col]);
          if (cell && !(cell instanceof RTETableHeadCellBlock)) {
            return false;
          }
        }
      }
      return true;
    }
    return false;
  }
  /**
   * @inheritDoc
   */
  handleAction(action, target) {
    const headerOn = action.headerOn;
    const allTableRows = getAllTableRows(target);
    const tableGrid = buildTableGrid(allTableRows);
    const [minSelectCellCol, maxSelectCellCol] = this.getBoundaryCellColumnRange(action.tableCellHeaderRange, allTableRows, tableGrid);
    const shouldSplitHeadCells = headerOn || (!headerOn && minSelectCellCol > 0);
    if (shouldSplitHeadCells) {
      this.toggleHeadRows(target, allTableRows, tableGrid, headerOn, maxSelectCellCol, minSelectCellCol);
    }
    this.toggleBodyRows(target, allTableRows, tableGrid, headerOn, minSelectCellCol, maxSelectCellCol);
    const root = this.getRootContent(target);
    if (root && action.tableCellHeaderRange[0].parent) {
      const focusNode = action.tableCellHeaderRange[0].parent.getFirstNode();
      focusNode && root.apply(new UpdateCursorPositionAction(focusNode, 0));
    }
  }
  /**
   * Toggle header cells within existing table-head rows.
   *
   * @param {RTETableBlock} table - The target table block.
   * @param {RTETableRowBlock[]} allTableRows - All table rows in order.
   * @param {string[][]} tableGrid - Table grid representation.
   * @param {boolean} headerOn - Whether header mode is being enabled.
   * @param {number} maxSelectCellCol - Maximum selected logical column.
   * @param {number} minSelectCellCol - Minimum selected logical column.
   */
  toggleHeadRows(table, allTableRows, tableGrid, headerOn, maxSelectCellCol, minSelectCellCol) {
    var _a;
    const allTableHeadRows = ((_a = table.children.find((head) => head instanceof RTETableHeadBlock)) === null || _a === void 0 ? void 0 : _a.children) || [];
    const headRowLength = allTableHeadRows.length;
    for (let rowIndex = 0; rowIndex < headRowLength; rowIndex++) {
      const row = allTableRows[rowIndex];
      const endColIndex = headerOn ? maxSelectCellCol : minSelectCellCol - 1;
      this.toggleCellType(table, row, tableGrid[rowIndex], 0, endColIndex, () => true, (cell) => RTETableHeadCellBlock.from(cell.toJSON()));
    }
  }
  /**
   * Toggle header cells within body rows.
   *
   * @param {RTETableBlock} table - The target table block.
   * @param {RTETableRowBlock[]} allTableRows - All table rows in order.
   * @param {string[][]} tableGrid - Table grid representation.
   * @param {boolean} headerOn - Whether header mode is being enabled.
   * @param {number} minSelectCellCol - Minimum selected logical column.
   * @param {number} maxSelectCellCol - Maximum selected logical column.
   */
  toggleBodyRows(table, allTableRows, tableGrid, headerOn, minSelectCellCol, maxSelectCellCol) {
    var _a;
    const tableColLength = tableGrid[0].length;
    const allTableBodyRows = ((_a = table.children.find((body) => body instanceof RTETableBodyBlock)) === null || _a === void 0 ? void 0 : _a.children) || [];
    const headRowLength = allTableRows.length - allTableBodyRows.length;
    for (let i = 0; i < allTableBodyRows.length; i++) {
      const rowIndex = i + headRowLength;
      const row = allTableRows[rowIndex];
      const gridRow = tableGrid[rowIndex];
      const startColIndex = findFirstBodyColIndex(gridRow, row, tableColLength);
      if (headerOn) {
        if (startColIndex > -1) {
          this.toggleCellType(table, row, gridRow, startColIndex, maxSelectCellCol, (cell) => !(cell instanceof RTETableHeadCellBlock), (cell) => RTETableHeadCellBlock.from(cell.toJSON()));
        }
        continue;
      }
      const lastHeaderCol = startColIndex === -1 ? tableColLength - 1 : startColIndex - 1;
      this.toggleCellType(table, row, gridRow, minSelectCellCol, lastHeaderCol, (cell) => cell instanceof RTETableHeadCellBlock, (cell) => RTETableCellBlock.from(cell.toJSON()));
    }
  }
  /**
   * Toggle cell types in a row within a logical column range.
   *
   * @param {RTETableBlock} table - The table block containing the target row.
   * @param {RTETableRowBlock} row - The table row block.
   * @param {string[]} gridRow - The grid row array.
   * @param {number} startCol - Start logical column.
   * @param {number} endCol - End logical column.
   * @param {(cell: RTETableCellBlock | RTETableHeadCellBlock) => boolean} shouldConvert - Predicate to determine if a cell should be converted.
   * @param {(cell: RTETableCellBlock | RTETableHeadCellBlock) => RTETableCellBlock | RTETableHeadCellBlock} convert - Function to convert the cell.
   */
  toggleCellType(table, row, gridRow, startCol, endCol, shouldConvert, convert) {
    for (let col = startCol; col <= endCol; col++) {
      const cellId = gridRow[col];
      const cell = row.children.find((c) => c.id === cellId);
      if (cell && shouldConvert(cell)) {
        const cellStartCol = gridRow.indexOf(cellId);
        const targetCellType = convert(cell).type;
        const payload = {
          table,
          cell,
          col,
          cellStartCol,
          endCol,
          targetCellType,
        };
        const cellEndCol = cellStartCol + cell.colSpan - 1;
        const shouldSplit = cellEndCol > endCol || cellStartCol < col;
        if (shouldSplit) {
          row.apply(new SplitTableCellAction(payload));
          if (cellEndCol > endCol) {
            return;
          }
          col = cellEndCol;
          continue;
        }
        row.apply(new ReplaceTableCellAction(payload));
      }
      if (cell) {
        col += cell.colSpan - 1;
      }
    }
  }
}

const DELETE_TABLE_COLUMN = 'DELETE_TABLE_COLUMN';
/**
 * Action to delete a table column
 */
class DeleteTableColumnAction extends ModifyContentAction {
  constructor(target) {
    super();
    this.isFlushable = true;
    this.type = DELETE_TABLE_COLUMN;
    this.tableCellDeleteRange = target;
  }
}

const INSERT_TABLE_COLUMN = 'INSERT_TABLE_COLUMN';
var InsertTableColumnDirection;
(function (InsertTableColumnDirection) {
  InsertTableColumnDirection["LEFT"] = "LEFT";
  InsertTableColumnDirection["RIGHT"] = "RIGHT";
})(InsertTableColumnDirection || (InsertTableColumnDirection = {}));
/**
 * Action to insert a table column into the RTETable.
 */
class InsertTableColumnAction extends ModifyContentAction {
  constructor(insertDirection, tableCellInsertRange) {
    super();
    this.isFlushable = true;
    this.type = INSERT_TABLE_COLUMN;
    this.tableCellInsertRange = tableCellInsertRange;
    this.insertDirection = insertDirection;
  }
}

const SELECT_TABLE_COLUMN = 'SELECT_TABLE_COLUMN';
/**
 * Action to select a table column into the RTETable.
 */
class SelectTableColumnAction extends ModifyContentAction {
  constructor(tableCellSelectRange, selectCellCallback) {
    super();
    this.type = SELECT_TABLE_COLUMN;
    this.tableCellSelectRange = tableCellSelectRange;
    this.selectCellCallback = selectCellCallback;
  }
}

const TOGGLE_HEADER_TABLE_COLUMN = 'TOGGLE_HEADER_TABLE_COLUMN';
/**
 * Action to toggle header state of a table column in the RTETable.
 */
class ToggleHeaderTableColumnAction extends ModifyContentAction {
  constructor(tableCellHeaderRange, headerOn) {
    super();
    this.isFlushable = true;
    this.type = TOGGLE_HEADER_TABLE_COLUMN;
    this.headerOn = false;
    this.tableCellHeaderRange = tableCellHeaderRange;
    this.headerOn = headerOn;
  }
}

var ColumnOperationType;
(function (ColumnOperationType) {
  ColumnOperationType["HEADER_COLUMN"] = "HEADER_COLUMN";
  ColumnOperationType["ADD_COLUMN_LEFT"] = "ADD_COLUMN_LEFT";
  ColumnOperationType["ADD_COLUMN_RIGHT"] = "ADD_COLUMN_RIGHT";
  ColumnOperationType["DELETE_COLUMN"] = "DELETE_COLUMN";
  ColumnOperationType["SELECT_COLUMN"] = "SELECT_COLUMN";
})(ColumnOperationType || (ColumnOperationType = {}));
/**
 * Event handler for column operations in a table.
 */
class ColumnOperationEventHandler extends SettingEventHandler {
  /**
   * @inheritDoc
   */
  canHandle(action) {
    return action[0] === TableSettingType.COLUMN;
  }
  /**
   * @inheritDoc
   */
  execute(action, extensionContext) {
    const selectedCells = extensionContext.tableSelection.getSelectedCells();
    if (!selectedCells || selectedCells.length === 0) {
      return;
    }
    const operation = action[1];
    switch (operation) {
      case ColumnOperationType.ADD_COLUMN_LEFT:
      case ColumnOperationType.ADD_COLUMN_RIGHT:
        this.handleInsertColumn(operation, selectedCells);
        break;
      case ColumnOperationType.DELETE_COLUMN:
        this.handleDeleteColumn(selectedCells);
        break;
      case ColumnOperationType.SELECT_COLUMN:
        this.handleSelectColumn(selectedCells, extensionContext);
        break;
      case ColumnOperationType.HEADER_COLUMN:
        this.handleToggleHeaderColumn(selectedCells);
        break;
    }
  }
  /**
   * Adds a new column to the table at the specified position.
   *
   * @param {ColumnOperationType} direction - The position to insert the new column (left or right).
   * @param {RTETableCellBlock[] | RTETableHeadCellBlock[]} selectedCells - The selected table cells.
   */
  handleInsertColumn(direction, selectedCells) {
    const action = new InsertTableColumnAction(direction === ColumnOperationType.ADD_COLUMN_LEFT
      ? InsertTableColumnDirection.LEFT
      : InsertTableColumnDirection.RIGHT, selectedCells);
    this.applyActionOnTable(action, selectedCells[0]);
  }
  /**
   * Deletes the selected column from the table.
   *
   * @param {RTETableCellBlock[] | RTETableHeadCellBlock[]} selectedCells - The selected table cells.
   */
  handleDeleteColumn(selectedCells) {
    const action = new DeleteTableColumnAction(selectedCells);
    this.applyActionOnTable(action, selectedCells[0]);
  }
  /**
   * Selects the entire column in the table.
   *
   * @param {RTETableCellBlock[] | RTETableHeadCellBlock[]} selectedCells - The selected table cells.
   * @param {RTETableExtensionContext} extensionContext - The table extension context.
   */
  handleSelectColumn(selectedCells, extensionContext) {
    const action = new SelectTableColumnAction(selectedCells, (allSelectedCells) => {
      extensionContext.tableSelection.setSelectedCells(allSelectedCells);
    });
    this.applyActionOnTable(action, selectedCells[0]);
  }
  /**
   * Toggles the header state of the selected column in the table.
   *
   * @param {RTETableCellBlock[] | RTETableHeadCellBlock[]} selectedCells - The selected table cells.
   */
  handleToggleHeaderColumn(selectedCells) {
    const headerOn = !ToggleHeaderTableColumnStrategy.isFullHeaderSelection(selectedCells);
    const action = new ToggleHeaderTableColumnAction(selectedCells, headerOn);
    this.applyActionOnTable(action, selectedCells[0]);
  }
  /**
   * Apply the specified action on the table containing the selected cell.
   *
   * @param {DeleteTableColumnAction | InsertTableColumnAction} action - The action to apply.
   * @param {RTETableCellBlock | RTETableHeadCellBlock} selectedCell - The selected table cell.
   */
  applyActionOnTable(action, selectedCell) {
    const table = getParentBlockByType(selectedCell, RTETableBlock);
    if (table) {
      table.apply(action);
    }
  }
}

const SPLIT_CELL_HORIZONTALLY = 'SPLIT_CELL_HORIZONTALLY';
/**
 * Action to split a table cell horizontally.
 */
class SplitCellHorizontallyAction extends ModifyContentAction {
  constructor() {
    super();
    this.isFlushable = true;
    this.type = SPLIT_CELL_HORIZONTALLY;
  }
}

const SPLIT_CELL_VERTICALLY = 'SPLIT_CELL_VERTICALLY';
/**
 * Action to split a table cell vertically.
 */
class SplitCellVerticallyAction extends ModifyContentAction {
  constructor() {
    super();
    this.isFlushable = true;
    this.type = SPLIT_CELL_VERTICALLY;
  }
}

var SplitCellOperationType;
(function (SplitCellOperationType) {
  SplitCellOperationType["SPLIT_CELL_HORIZONTALLY"] = "SPLIT_CELL_HORIZONTALLY";
  SplitCellOperationType["SPLIT_CELL_VERTICALLY"] = "SPLIT_CELL_VERTICALLY";
})(SplitCellOperationType || (SplitCellOperationType = {}));
/**
 * Event handler for split cell operations in a table.
 */
class SplitCellOperationEventHandler extends SettingEventHandler {
  /**
   * @inheritDoc
   */
  canHandle(action) {
    return action[0] === TableSettingType.SPLIT_CELL;
  }
  /**
   * @inheritDoc
   */
  execute(action, extensionContext) {
    const selectedCells = extensionContext.tableSelection.getSelectedCells();
    if (selectedCells && selectedCells.length === 1) {
      const targetCell = selectedCells[0];
      const operation = action[1];
      switch (operation) {
        case SplitCellOperationType.SPLIT_CELL_HORIZONTALLY:
          this.handleSplitCellHorizontally(targetCell);
          break;
        case SplitCellOperationType.SPLIT_CELL_VERTICALLY:
          this.handleSplitCellVertically(targetCell);
          break;
      }
    }
  }
  /**
   * Splits the selected table cell horizontally (split top/bottom).
   *
   * @param {RTETableCellBlock | RTETableHeadCellBlock} selectedCell - The table cell block to split.
   */
  handleSplitCellHorizontally(selectedCell) {
    const action = new SplitCellHorizontallyAction();
    selectedCell.apply(action);
  }
  /**
   * Splits the selected table cell vertically (split left/right).
   *
   * @param {RTETableCellBlock | RTETableHeadCellBlock} selectedCell - The table cell block to split.
   */
  handleSplitCellVertically(selectedCell) {
    const action = new SplitCellVerticallyAction();
    selectedCell.apply(action);
  }
}

export { getSelectedCellsBoundary as $, RTETableRowBlock as A, getActualColumnPosition as B, ColumnOperationEventHandler as C, InsertTableRowDirection as D, RTE_TABLE_DEFAULT_COLORS as E, INSERT_TABLE_ROW_INTO_DIFFERENT_SECTION as F, INSERT_TABLE_ROW_INTO_SAME_SECTION as G, DELETE_TABLE_ROW as H, InsertTableColumnDirection as I, TOGGLE_HEADER_ROW as J, INSERT_TABLE_COLUMN as K, DELETE_TABLE_COLUMN as L, MergeCellsOperationEventHandler as M, TOGGLE_HEADER_TABLE_COLUMN as N, ToggleHeaderTableColumnStrategy as O, SPLIT_TABLE_CELL as P, REPLACE_TABLE_CELL as Q, RTETableExtensionAnnotationTypeEnum as R, SettingEventHandler as S, TableSettingType as T, SPLIT_CELL_HORIZONTALLY as U, VegaThemeManager as V, SPLIT_CELL_VERTICALLY as W, SELECT_TABLE_COLUMN as X, MERGE_CELLS as Y, RTE_TABLE_BORDER_STYLES as Z, ColumnOperationType as _, RTE_TABLE_HEAD_DEFAULT_BACKGROUND_COLOR as a, RowOperationType as a0, SplitCellOperationType as a1, isRectangularSelection as a2, getAdjacentCell as a3, RTETableAnnotation as b, RTETableCellAnnotation as c, RTETableHeadCellBlock as d, RowOperationEventHandler as e, SplitCellOperationEventHandler as f, RTETableColorManager as g, RTETableBlock as h, generateTableBody as i, RTETableCellBlock as j, RTETableHeadBlock as k, RTETableBodyBlock as l, getParentBlockByType as m, RTETableHeadCellAnnotation as n, TableColumnStrategy as o, getAllTableRows as p, buildTableGrid as q, findCellBlockById as r, setSpanAttributes as s, getDefaultCellBlockTemplate as t, buildCellStartColumnMap as u, getTableColumnCount as v, getFirstNode as w, getCellSpan as x, createNewCell as y, MergeCellsOperationType as z };
