toolbar.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { getBlockEditor } from '@/appflowy_app/block_editor';
  2. import { Editor, Range } from 'slate';
  3. export function calcToolbarPosition(editor: Editor, toolbarDom: HTMLDivElement, blockId: string) {
  4. const { selection } = editor;
  5. const scrollContainer = document.querySelector('.doc-scroller-container');
  6. if (!scrollContainer) return;
  7. if (!selection || Range.isCollapsed(selection) || Editor.string(editor, selection) === '') {
  8. return;
  9. }
  10. const blockEditor = getBlockEditor();
  11. const blockRect = blockEditor?.renderTree.getNodeRect(blockId);
  12. const blockDom = document.querySelector(`[data-block-id=${blockId}]`);
  13. if (!blockDom || !blockRect) return;
  14. const domSelection = window.getSelection();
  15. let domRange;
  16. if (domSelection?.rangeCount === 0) {
  17. return;
  18. } else {
  19. domRange = domSelection?.getRangeAt(0);
  20. }
  21. const rect = domRange?.getBoundingClientRect() || { top: 0, left: 0, width: 0, height: 0 };
  22. const top = `${-toolbarDom.offsetHeight - 5 + (rect.top + scrollContainer.scrollTop - blockRect.top)}px`;
  23. const left = `${rect.left - blockRect.left - toolbarDom.offsetWidth / 2 + rect.width / 2}px`;
  24. return {
  25. top,
  26. left,
  27. }
  28. }