首页 > 解决方案 > SlateJS:仅在活动块上方显示浮动工具栏

问题描述

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

该工具栏当前在表格上方正确显示,但是当我在选择/活动中的一个表中,当我在编辑器中插入多个表时,在每个表上方都可以看到工具栏。

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

演示: 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>
  );
};

标签: reactjsslatejs

解决方案


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

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]);

推荐阅读