toolbar.ts 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. export function calcToolbarPosition(toolbarDom: HTMLDivElement, node: Element, container: HTMLDivElement) {
  2. const domSelection = window.getSelection();
  3. let domRange;
  4. if (domSelection?.rangeCount === 0) {
  5. return;
  6. } else {
  7. domRange = domSelection?.getRangeAt(0);
  8. }
  9. const nodeRect = node.getBoundingClientRect();
  10. const rect = domRange?.getBoundingClientRect() || { top: 0, left: 0, width: 0, height: 0 };
  11. const top = rect.top - nodeRect.top - toolbarDom.offsetHeight;
  12. let left = rect.left - nodeRect.left - toolbarDom.offsetWidth / 2 + rect.width / 2;
  13. // fix toolbar position when it is out of the container
  14. const containerRect = container.getBoundingClientRect();
  15. const leftBound = containerRect.left - nodeRect.left;
  16. const rightBound = containerRect.right;
  17. const rightThreshold = 20;
  18. if (left < leftBound) {
  19. left = leftBound;
  20. } else if (left + nodeRect.left + toolbarDom.offsetWidth > rightBound) {
  21. left = rightBound - toolbarDom.offsetWidth - nodeRect.left - rightThreshold;
  22. }
  23. return {
  24. top,
  25. left,
  26. };
  27. }