【问题标题】:How to create a hyperlink insertion modal without losing text selection?How to create a hyperlink insertion modal without losing text selection?
【发布时间】:2022-12-02 07:39:07
【问题描述】:

I've got a React site which uses Slate-React (https://docs.slatejs.org/libraries/slate-react) to create a rich text input field. Slate uses the browser's prompt() function to apply hyperlinks to selected text, but I need to be able to style the prompt modal so I have to find an alternative. However, if I create a simple Javascript popup with an input field, the selected text is deselected as soon as the focus is applied to the modal so no link is inserted.

Is there a way to move focus to another element whilst still keeping the original text selected?

Essentially I'm trying to emulate the Insert Hyperlink functionality/styling that Google Docs uses:

【问题讨论】:

    标签: javascript reactjs slatejs


    【解决方案1】:

    you can have this selection in state, and pass some prop using this selection to apply link on this selection. You can do this by using Transforms.select(editor, thisSelection) followed by applying link

    【讨论】:

      【解决方案2】:

      It's pretty hard, especially if you are making an accessible modal that captures input. We have something like the following:

      const handleSave = (inputText: string, url: string, caretPosition: number, remove = false) => {
              let removalOffset = 0;
              let prevPath = null;
              if (remove && Path.hasPrevious(linkPath)) {
                prevPath = Path.previous(linkPath);
                const prevNode = Node.first(editor, prevPath)[0];
                removalOffset = Node.string(prevNode).length;
              }
              Transforms.insertText(editor, inputText, { at: { path: linkPath, offset: 0 } });
              Transforms.delete(editor, {
                at: {
                  anchor: { path: linkPath, offset: inputText.length },
                  focus: { path: linkPath, offset: text.text.length + inputText.length }
                }
              });
              Transforms.setNodes(
                editor,
                remove ? { link: undefined, url: undefined, linkOpen: undefined } : { linkOpen: undefined, url },
                { at: linkPath }
              );
              handleClose();
              if (!remove) {
                setPointer(inputText, caretPosition, linkPath);
              } else if (prevPath !== null) {
                setPointer(inputText, removalOffset + caretPosition, prevPath);
              }
      };
      

      The setPointer function calls Transforms.select. However, you may need to run it asynchronously if you are capturing inputs in the modal for accessibility.

      【讨论】:

        猜你喜欢
        • 2022-12-02
        • 2022-12-02
        • 2022-12-16
        • 2022-12-27
        • 2023-02-01
        • 2022-12-02
        • 2022-12-26
        • 2022-12-02
        • 2022-12-26
        相关资源
        最近更新 更多