(
editor: CustomEditor,
location: Range,
options: {
terminator?: string[]
include?: boolean
directions?: 'both' | 'left' | 'right'
} = {},
)
| 42 | |
| 43 | // @see: https://github.com/ianstormtaylor/slate/issues/4162#issuecomment-1127062098 |
| 44 | export function word( |
| 45 | editor: CustomEditor, |
| 46 | location: Range, |
| 47 | options: { |
| 48 | terminator?: string[] |
| 49 | include?: boolean |
| 50 | directions?: 'both' | 'left' | 'right' |
| 51 | } = {}, |
| 52 | ): Range | undefined { |
| 53 | const { terminator = [' '], include = false, directions = 'both' } = options |
| 54 | |
| 55 | const { selection } = editor |
| 56 | if (!selection) return |
| 57 | |
| 58 | // Get start and end, modify it as we move along. |
| 59 | let [start, end] = Range.edges(location) |
| 60 | |
| 61 | let point: Point = start |
| 62 | |
| 63 | function move(direction: 'right' | 'left'): boolean { |
| 64 | const next = |
| 65 | direction === 'right' |
| 66 | ? Editor.after(editor, point, { |
| 67 | unit: 'character', |
| 68 | }) |
| 69 | : Editor.before(editor, point, { unit: 'character' }) |
| 70 | |
| 71 | const wordNext = |
| 72 | next && |
| 73 | Editor.string( |
| 74 | editor, |
| 75 | direction === 'right' ? { anchor: point, focus: next } : { anchor: next, focus: point }, |
| 76 | ) |
| 77 | |
| 78 | const last = wordNext && wordNext[direction === 'right' ? 0 : wordNext.length - 1] |
| 79 | if (next && last && !terminator.includes(last)) { |
| 80 | point = next |
| 81 | |
| 82 | if (point.offset === 0) { |
| 83 | // Means we've wrapped to beginning of another block |
| 84 | return false |
| 85 | } |
| 86 | } else { |
| 87 | return false |
| 88 | } |
| 89 | |
| 90 | return true |
| 91 | } |
| 92 | |
| 93 | // Move point and update start & end ranges |
| 94 | |
| 95 | // Move forwards |
| 96 | if (directions !== 'left') { |
| 97 | point = end |
| 98 | while (move('right')); |
| 99 | end = point |
| 100 | } |
| 101 |
no test coverage detected