/**
 * Mark Input Rule Helper
 * 标记输入规则辅助函数
 */

import { InputRule } from 'prosemirror-inputrules';
import type { MarkType } from 'prosemirror-model';

/**
 * 创建一个将匹配文本转换为标记的输入规则
 *
 * @param regexp - 匹配模式，第一个捕获组为要标记的文本
 * @param markType - 要应用的标记类型
 * @param getAttrs - 可选的属性获取函数
 */
export function markInputRule(
  regexp: RegExp,
  markType: MarkType,
  getAttrs?: ((match: RegExpMatchArray) => Record<string, unknown> | null) | Record<string, unknown>
): InputRule {
  return new InputRule(regexp, (state, match, start, end) => {
    const attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;
    const tr = state.tr;

    if (match[1]) {
      const textStart = start + match[0].indexOf(match[1]);
      const textEnd = textStart + match[1].length;

      // 删除整个匹配的文本
      tr.delete(start, end);

      // 在原位置插入带标记的文本
      tr.insertText(match[1], start);

      // 应用标记
      tr.addMark(start, start + match[1].length, markType.create(attrs));
    }

    return tr;
  });
}
