SlateJS:仅在活动块上方显示浮动工具栏

问题描述

我正在使用 SlateJS 创建一个 @udecode/slate-plugins 编辑器。我让大部分编辑器都在工作,但是,我正在尝试为表格块创建一个工具栏,当表格被选中/激活时,该工具栏应该在表格上方可见。

工具栏当前正确显示在表格上方,但是,当我在编辑器中插入多个表格时,当其中一个表格被选中/处于活动状态时,工具栏在每个表格上方可见。

如何让工具栏只在活动表上可见而在其余表上隐藏?

演示: Codesandbox.io

表格块代码

const Table = ({
  attributes,children,className,nodeProps
}: StyledElementProps) => {
  const editor = useTSlate();

  const isActive = someNode(editor,{ match: { type: ELEMENT_TABLE } });

  return (
    <table {...attributes} className={className} {...nodeProps}>
      <Tippy
        interactive={true}
        arrow={false}
        visible={isActive}
        onClickOutside={(instance) => instance.hide()}
        content={
          <div style={{ display: "flex",flexDirection: "row" }}>
            <ToolbarTable
              icon={<CgExtensionRemove />}
              transform={deleteTable}
              tooltip={{ content: "Delete Table" }}
            />
            <ToolbarTable
              icon={<AIoUtlineInsertRowBelow />}
              transform={addRow}
              tooltip={{ content: "Insert Row" }}
            />
            <ToolbarTable
              icon={<AIoUtlineDeleteRow />}
              transform={deleteRow}
              tooltip={{ content: "Delete Row" }}
            />
            <ToolbarTable
              icon={<AIoUtlineInsertRowRight />}
              transform={addColumn}
              tooltip={{ content: "Insert Column" }}
            />
            <ToolbarTable
              icon={<AIoUtlineDeleteColumn />}
              transform={deleteColumn}
              tooltip={{ content: "Delete Column" }}
            />
          </div>
        }
      >
        <tbody>{children}</tbody>
      </Tippy>
    </table>
  );
};

解决方法

通过获取当前选择并检查表格块是否包含选择来解决它。

const [isActive,setIsActive] = useState(false);
const domSelection = window.getSelection();

useEffect(() => {
    setIsActive(
        !!(
            someNode(editor,{ match: { type: ELEMENT_TABLE } }) &&
            domSelection &&
            attributes.ref.current &&
            attributes.ref.current.contains(domSelection.anchorNode)
        )
    );
},[attributes,domSelection,editor]);