在shadowRoot里获取光标(selection)信息

3大浏览器,3种不一样的处理方式😅

  getSelectionAndRange() {
    let selection = document.getSelection();
    if (!selection) return null;

    // 规范 getComposedRanges, CH--FF--SF17
    if ('getComposedRanges' in selection) {
      const [firstRange] = selection.getComposedRanges(this.#shadowRoot);
      if (!firstRange || !this.#editor.contains(firstRange.startContainer)) return null;

      const range = document.createRange();
      range.setStart(firstRange.startContainer, firstRange.startOffset);
      range.setEnd(firstRange.endContainer, firstRange.endOffset);
      return [selection, range] as const;
    }

    if (selection.type === 'None') {
      return null;
    }

    // shadowRoot.getSelection() CH53FF--SF--
    if ('getSelection' in this.#shadowRoot) {
      selection = this.#shadowRoot.getSelection();
      if (selection.type === 'None') return null;
      return [selection, selection.getRangeAt(0)] as const;
    }

    // selection 可穿透shadowRoot CH--FF??SF--
    if (selection.anchorNode === this.#editor || this.#editor.contains(selection.anchorNode)) {
      return [selection, selection.getRangeAt(0)] as const;
    }

    return null;
  }

评论

暂无评论