Path: blob/master/src/packages/frontend/editors/slate/slate-react/utils/lines.ts
1698 views
/**1* Utilities for single-line deletion2*/34import { Range, Editor } from "slate";5import { ReactEditor } from "..";67const doRectsIntersect = (rect: DOMRect, compareRect: DOMRect) => {8const middle = (compareRect.top + compareRect.bottom) / 2;910return rect.top <= middle && rect.bottom >= middle;11};1213const areRangesSameLine = (14editor: ReactEditor,15range1: Range,16range2: Range17) => {18const rect1 = ReactEditor.toDOMRange(editor, range1).getBoundingClientRect();19const rect2 = ReactEditor.toDOMRange(editor, range2).getBoundingClientRect();2021return doRectsIntersect(rect1, rect2) && doRectsIntersect(rect2, rect1);22};2324/**25* A helper utility that returns the end portion of a `Range`26* which is located on a single line.27*28* @param {Editor} editor The editor object to compare against29* @param {Range} parentRange The parent range to compare against30* @returns {Range} A valid portion of the parentRange which is on a single line31*/32export const findCurrentLineRange = (33editor: ReactEditor,34parentRange: Range35): Range => {36const parentRangeBoundary = Editor.range(editor, Range.end(parentRange));37const positions = Array.from(Editor.positions(editor, { at: parentRange }));3839let left = 0;40let right = positions.length;41let middle = Math.floor(right / 2);4243if (44areRangesSameLine(45editor,46Editor.range(editor, positions[left]),47parentRangeBoundary48)49) {50return Editor.range(editor, positions[left], parentRangeBoundary);51}5253if (positions.length < 2) {54return Editor.range(55editor,56positions[positions.length - 1],57parentRangeBoundary58);59}6061while (middle !== positions.length && middle !== left) {62if (63areRangesSameLine(64editor,65Editor.range(editor, positions[middle]),66parentRangeBoundary67)68) {69right = middle;70} else {71left = middle;72}7374middle = Math.floor((left + right) / 2);75}7677return Editor.range(editor, positions[right], parentRangeBoundary);78};798081