Skip to content

Commit

Permalink
fix(useTextSelection): ssr compactible
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Mar 5, 2022
1 parent 7887f84 commit 2a87733
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions packages/core/useTextSelection/index.ts
@@ -1,4 +1,6 @@
import { computed, ref } from 'vue-demi'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
import { useEventListener } from '../useEventListener'

function getRangesFromSelection(selection: Selection) {
Expand All @@ -16,18 +18,25 @@ function getRangesFromSelection(selection: Selection) {
*
* @see https://vueuse.org/useTextSelection
*/
export function useTextSelection() {
export function useTextSelection(options: ConfigurableWindow = {}) {
const {
window = defaultWindow,
} = options

const selection = ref<Selection | null>(null)
const text = computed(() => selection.value?.toString() ?? '')
const ranges = computed<Range[]>(() => selection.value ? getRangesFromSelection(selection.value) : [])
const rects = computed(() => ranges.value.map(range => range.getBoundingClientRect()))

function onSelectionChange() {
selection.value = null // trigger computed update
selection.value = window.getSelection()
if (window)
selection.value = window.getSelection()
}

useEventListener(document, 'selectionchange', onSelectionChange)
if (window)
useEventListener(window.document, 'selectionchange', onSelectionChange)

return {
text,
rects,
Expand Down

0 comments on commit 2a87733

Please sign in to comment.