selection.ts 837 B

12345678910111213141516171819202122232425262728293031323334
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. export interface SelectionData {
  3. text: string
  4. html: string
  5. selection: Selection | null
  6. }
  7. export const getCurrentSelectionData = (): SelectionData => {
  8. let text = ''
  9. let html = ''
  10. let sel: Selection | null = null
  11. if (window.getSelection) {
  12. sel = window.getSelection()
  13. text = sel?.toString() || ''
  14. } else if (document.getSelection) {
  15. sel = document.getSelection()
  16. text = sel?.toString() || ''
  17. }
  18. if (sel && sel.rangeCount) {
  19. const container = document.createElement('div')
  20. for (let i = 1; i <= sel.rangeCount; i += 1) {
  21. container.appendChild(sel.getRangeAt(i - 1).cloneContents())
  22. }
  23. html = container.innerHTML
  24. }
  25. return {
  26. text: text.toString().trim() || '',
  27. html,
  28. selection: sel,
  29. }
  30. }