|
| 1 | +import { createPluginFactory, getNode, getSelectionText, isText } from '@udecode/plate-common'; |
| 2 | +import { Range } from 'slate'; |
| 3 | + |
| 4 | +export const createSelectionPlugin = createPluginFactory({ |
| 5 | + key: 'selection', |
| 6 | + withOverrides: (editor) => { |
| 7 | + const { select } = editor; |
| 8 | + |
| 9 | + editor.select = (target) => { |
| 10 | + if (!Range.isRange(target) || Range.isCollapsed(target)) { |
| 11 | + return select(target); |
| 12 | + } |
| 13 | + |
| 14 | + if (!containsMultipleWords(getSelectionText(editor))) { |
| 15 | + return select(target); |
| 16 | + } |
| 17 | + |
| 18 | + const node = getNode(editor, target.anchor.path); |
| 19 | + |
| 20 | + if (!isText(node)) { |
| 21 | + return select(target); |
| 22 | + } |
| 23 | + |
| 24 | + const isForward = Range.isForward(target); |
| 25 | + |
| 26 | + const anchorOffset = isForward |
| 27 | + ? getWordStart(node.text, target.anchor.offset) |
| 28 | + : getWordEnd(node.text, target.anchor.offset); |
| 29 | + |
| 30 | + const focusOffset = isForward |
| 31 | + ? getWordEnd(node.text, target.focus.offset) |
| 32 | + : getWordStart(node.text, target.focus.offset); |
| 33 | + |
| 34 | + return select({ |
| 35 | + anchor: { ...target.anchor, offset: anchorOffset }, |
| 36 | + focus: { ...target.focus, offset: focusOffset }, |
| 37 | + }); |
| 38 | + }; |
| 39 | + |
| 40 | + return editor; |
| 41 | + }, |
| 42 | +}); |
| 43 | + |
| 44 | +const START_REGEX = /\S+$/; |
| 45 | +const END_REGEX = /^\S*/; |
| 46 | +const CONTAINS_REGEX = /\s/; |
| 47 | + |
| 48 | +const getWordStart = (text: string, offset: number): number => { |
| 49 | + const match = text.slice(0, offset).match(START_REGEX); |
| 50 | + |
| 51 | + return match ? offset - match[0].length : offset; |
| 52 | +}; |
| 53 | + |
| 54 | +const getWordEnd = (text: string, offset: number): number => { |
| 55 | + const match = text.slice(offset).match(END_REGEX); |
| 56 | + |
| 57 | + return match ? offset + match[0].length : offset; |
| 58 | +}; |
| 59 | + |
| 60 | +const containsMultipleWords = (text: string): boolean => CONTAINS_REGEX.test(text); |
0 commit comments