Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

editor selection not change when selecting in a popup text box #5704

Open
codingschoolkid opened this issue Aug 22, 2024 · 0 comments
Open

Comments

@codingschoolkid
Copy link

codingschoolkid commented Aug 22, 2024

Description
Selecting text in the editor and then popping up a text box to choose the text in the text box, the selection of the editor will not change, Is this the expected behavior? see code below.

code

import React, { useState, useCallback, useMemo } from "react";
import { createEditor, Transforms, Editor } from "slate";
import { Slate, Editable, withReact } from "slate-react";

export default function Page() {
  const [editor] = useState(() => withReact(createEditor()));
  const [showPopup, setShowPopup] = useState(false);
  const [popupPosition, setPopupPosition] = useState({ top: 0, left: 0 });
  const [savedSelection, setSavedSelection] = useState(null);

  const renderElement = useCallback((props) => {
    return <p {...props.attributes}>{props.children}</p>;
  }, []);

  const handleSelect = () => {
    const { selection } = editor;
    if (selection) {
      const domSelection = window.getSelection();
      const domRange = domSelection.getRangeAt(0);
      const rect = domRange.getBoundingClientRect();
      setPopupPosition({ top: rect.top + window.scrollY + 50, left: rect.left + window.scrollX });
      setShowPopup(true);
    } else {
      setShowPopup(false);
    }
  };

  const initialValue = [
    {
      type: "paragraph",
      children: [{ text: "这是一个段落,你可以选中一些文本来触发弹出框。" }],
    },
  ];

  return (
    <Slate editor={editor} initialValue={initialValue} onChange={handleSelect}>
      <Editable
        renderElement={renderElement}
        onBlur={(e) => {
          console.log(e);
          e.preventDefault();
        }}
      />
      {showPopup && (
        <div
          onMouseMove={() => {
            console.log(editor.selection);
          }}
          style={{
            position: "absolute",
            top: `${popupPosition.top}px`,
            left: `${popupPosition.left}px`,
            backgroundColor: "white",
            border: "1px solid black",
            padding: "5px",
          }}
        >
          这是一个弹出框
        </div>
      )}
    </Slate>
  );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant