Расширение выделения до текущего слова с помощью SlateJS - PullRequest
0 голосов
/ 03 июля 2019

С помощью Slatejs (v0.47), как мне расширить текущий выбор (начиная со свернутого), чтобы охватить текущее слово?

Итак (при условии [] обозначает текущий раздел)

Если я начну с

this is some te[]xt

Как программно расширить выбор до

this is some [text]

?

1 Ответ

0 голосов
/ 03 июля 2019

В конце концов это заработало.

export const word_selection = (editor) => {
  const {value} = editor
  const {selection, startText} = value
  const {start, isExpanded} = selection

  if (isExpanded) {
    return value.fragment.text
  }
  const {text} = startText
  const {offset} = start
  let left = text.slice(0, offset).search(/\S+$/)
  if (left === -1) {
    // character before the cursor is a space, selection starts at the cursor
    left = offset
  }
  let right = text.slice(offset).search(/\s/)
  if (right < 0) {
    // character after teh cursor is a space, selection ends at the cursor
    right = text.length
  } else {
    right = right + offset
  }
  if (left === right) {
    // nothing to select
    return ''
  }
  editor.moveAnchorBackward(offset - left).moveFocusForward(right - offset)
  return value.fragment.text
}
...