如何替换 ProseMirror 中当前选定的内容

Sam*_*l G 5 prose-mirror

目前在 ProseMirror 中有点迷失,并试图了解替换当前选择的文本的正确方法。我希望能够在小写/大写之间切换。

state.selection.content();将返回选择下的相关节点的切片以及所选的内容,但不返回每个节点内需要替换的范围。

我假设我需要创建一个新的文本节点来替换每个选定节点内的范围,例如:

const updatedText = node.textContent.toUpperCase();
const textNode = state.schema.text(updatedText);
transaction = transaction.replaceWith(startPos, startPos + node.nodeSize, textNode);
Run Code Online (Sandbox Code Playgroud)

如何获取每个节点内要替换的范围?

不幸的是,我找不到合适的例子。

Sam*_*l G 7

最终得到以下使用replaceWith的内容。

可能是一个更好的解决方案,但希望这对其他人有帮助。

请参阅内嵌评论:

const execute = (casing, state, dispatch) => {
  // grab the current transaction and selection
  let tr = state.tr;
  const selection = tr.selection;

  // check we will actually need a to dispatch transaction
  let shouldUpdate = false;

  state.doc.nodesBetween(selection.from, selection.to, (node, position) => {
    // we only processing text, must be a selection
    if (!node.isTextblock || selection.from === selection.to) return;

    // calculate the section to replace
    const startPosition = Math.max(position + 1, selection.from);
    const endPosition = Math.min(position + node.nodeSize, selection.to);

    // grab the content
    const substringFrom = Math.max(0, selection.from - position - 1);
    const substringTo = Math.max(0, selection.to - position - 1);
    const updatedText = node.textContent.substring(substringFrom, substringTo);

    // set the casing
    const textNode = (casing === 'uppercase')
      ? state.schema.text(updatedText.toUpperCase(), node.marks)
      : state.schema.text(updatedText.toLocaleLowerCase(), node.marks);

    // replace
    tr = tr.replaceWith(startPosition, endPosition, textNode);
    shouldUpdate = true;
  });

  if (dispatch && shouldUpdate) {
    dispatch(tr.scrollIntoView());
  }
}
Run Code Online (Sandbox Code Playgroud)