Skip to content

feat(onElementRemoval): new function, refactor useActiveElement useElementHover #4410

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jan 2, 2025
Merged
1 change: 1 addition & 0 deletions packages/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from './createReusableTemplate'
export * from './createTemplatePromise'
export * from './createUnrefFn'
export * from './onClickOutside'
export * from './onElementRemoval'
export * from './onKeyStroke'
export * from './onLongPress'
export * from './onStartTyping'
Expand Down
86 changes: 86 additions & 0 deletions packages/core/onElementRemoval/demo.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<script setup lang="ts">
import { onElementRemoval } from '@vueuse/core'
import { ref } from 'vue'

// demo1: recreate new element
const demo1Ref = ref<HTMLElement | null>(null)
const demo1State = ref(true)
const demo1Count = ref(0)

function demo1BtnOnClick() {
demo1State.value = !demo1State.value
}

onElementRemoval(demo1Ref, () => demo1Count.value++)

// demo2: reuse same element
const demo2ParentRef = ref<HTMLElement | null>(null)
const demo2Ref = ref<HTMLElement | null>(null)
const demo2State = ref(true)
const demo2Count = ref(0)

function demo2BtnOnClick() {
demo2State.value = !demo2State.value
if (demo2State.value) {
demo2ParentRef.value?.appendChild(demo2Ref.value!)
}
else {
demo2Ref.value?.remove()
}
}

onElementRemoval(demo2Ref, () => demo2Count.value++)
</script>

<template>
<div class="on-element-removal__demo">
<h3>demo1: recreate new element</h3>
<div>
<button
v-if="!demo1State"
@click="demo1BtnOnClick"
>
recreate me
</button>
<button
v-else
ref="demo1Ref"
class="btn"
@click="demo1BtnOnClick"
>
remove me
</button>
<div>
<b>removed times: {{ demo1Count }}</b>
</div>
</div>

<hr>

<h3>demo2: reuse same element</h3>
<button
:class="{ btn: demo2State }"
@click="demo2BtnOnClick"
>
{{ demo2State ? 'remove' : 'append' }} me
</button>
<span ref="demo2ParentRef">
<span ref="demo2Ref">
target element
</span>
</span>
<div>
<b>removed times: {{ demo2Count }}</b>
</div>
</div>
</template>

<style lang="postcss">
.on-element-removal__demo .btn {
@apply bg-red-400;
}

.on-element-removal__demo .btn:hover {
@apply bg-red-500;
}
</style>
43 changes: 43 additions & 0 deletions packages/core/onElementRemoval/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
category: Sensors
---

# onElementRemoval

Fires when the element or any element containing it is removed.

## Usage

```vue {13}
<script setup lang="ts">
import { onElementRemoval } from '@vueuse/core'
import { ref } from 'vue'

const btnRef = ref<HTMLElement | null>(null)
const btnState = ref(true)
const removedCount = ref(0)

function btnOnClick() {
btnState.value = !btnState.value
}

onElementRemoval(btnRef, () => ++removedCount.value)
</script>

<template>
<button
v-if="btnState"
@click="btnOnClick"
>
recreate me
</button>
<button
v-else
ref="btnRef"
@click="btnOnClick"
>
remove me
</button>
<b>removed times: {{ removedCount }}</b>
</template>
```
122 changes: 122 additions & 0 deletions packages/core/onElementRemoval/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import type { AnyFn } from '@vueuse/shared'
import type { Ref } from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { effectScope, nextTick, ref } from 'vue'
import { onElementRemoval } from '.'

describe('onElementRemoval', () => {
let callBackFn: AnyFn
let grandElement: Ref<HTMLElement>
let parentElement: Ref<HTMLElement>
let targetElement: Ref<HTMLElement>

beforeEach(() => {
callBackFn = vi.fn(m => expect(m[0]).toBeInstanceOf(MutationRecord))
grandElement = ref(document.createElement('div'))
parentElement = ref(document.createElement('div'))
targetElement = ref(document.createElement('div'))

parentElement.value.appendChild(targetElement.value)
grandElement.value.appendChild(parentElement.value)
document.body.appendChild(grandElement.value)
})

afterEach(() => {
document.body.innerHTML = ''
})

it('should be defined', () => {
expect(onElementRemoval).toBeDefined()
})

it('should be called when the element is removed', async () => {
onElementRemoval(targetElement, callBackFn)

parentElement.value.removeChild(targetElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(1)

parentElement.value.appendChild(targetElement.value)
parentElement.value.removeChild(targetElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(2)

parentElement.value.appendChild(targetElement.value)
parentElement.value.innerHTML = ''
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(3)
})

it('should be called when any element containing the target element is removed', async () => {
onElementRemoval(targetElement, callBackFn)

grandElement.value.removeChild(parentElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(1)

grandElement.value.appendChild(parentElement.value)
grandElement.value.remove()
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(2)

document.body.appendChild(grandElement.value)
document.body.removeChild(grandElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(3)
})

it('should correctly triggered when use the custom document', async () => {
const shadowRoot = grandElement.value.attachShadow({ mode: 'open' })
shadowRoot.appendChild(parentElement.value)

onElementRemoval(targetElement, callBackFn, { document: shadowRoot })

parentElement.value.removeChild(targetElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(1)

parentElement.value.appendChild(targetElement.value)
parentElement.value.removeChild(targetElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(2)

parentElement.value.appendChild(targetElement.value)
parentElement.value.innerHTML = ''
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(3)
})

it('should correctly triggered even if the element is assigned a value after initialization', async () => {
const targetElement2 = ref()
onElementRemoval(targetElement2, callBackFn)

const el = document.createElement('div')
targetElement2.value = el
parentElement.value.appendChild(el)
await nextTick()
parentElement.value.removeChild(el)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(1)
})

it('should stop observing after called dispose scope', async () => {
const scope = effectScope()
scope.run(() => {
onElementRemoval(targetElement, callBackFn)
})
scope.stop()

parentElement.value.removeChild(targetElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(0)
})

it('should stop observing after called the stop handle', async () => {
const stop = onElementRemoval(targetElement, callBackFn)
stop()

parentElement.value.removeChild(targetElement.value)
await nextTick()
expect(callBackFn).toHaveBeenCalledTimes(0)
})
})
76 changes: 76 additions & 0 deletions packages/core/onElementRemoval/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import type { Fn } from '@vueuse/shared'
import type { WatchOptionsBase } from 'vue'
import type { ConfigurableDocumentOrShadowRoot, ConfigurableWindow } from '../_configurable'
import type { MaybeElementRef } from '../unrefElement'
import { noop, tryOnScopeDispose } from '@vueuse/shared'
import { watchEffect } from 'vue'
import { defaultWindow } from '../_configurable'
import { unrefElement } from '../unrefElement'
import { useMutationObserver } from '../useMutationObserver'

export interface OnElementRemovalOptions
extends ConfigurableWindow, ConfigurableDocumentOrShadowRoot, WatchOptionsBase { }

/**
* Fires when the element or any element containing it is removed.
*
* @param target
* @param callback
* @param options
*/
export function onElementRemoval(
target: MaybeElementRef,
callback: (mutationRecords: MutationRecord[]) => void,
options: OnElementRemovalOptions = {},
): Fn {
const {
window = defaultWindow,
document = window?.document,
flush = 'sync',
} = options

// SSR
if (!window || !document)
return noop

let stopFn: Fn | undefined
const cleanupAndUpdate = (fn?: Fn) => {
stopFn?.()
stopFn = fn
}

const stopWatch = watchEffect(() => {
const el = unrefElement(target)
if (el) {
const { stop } = useMutationObserver(
document as any,
(mutationsList) => {
const targetRemoved = mutationsList
.map(mutation => [...mutation.removedNodes])
.flat()
.some(node => node === el || node.contains(el))

if (targetRemoved) {
callback(mutationsList)
}
},
{
window,
childList: true,
subtree: true,
},
)

cleanupAndUpdate(stop)
}
}, { flush })

const stopHandle = () => {
stopWatch()
cleanupAndUpdate()
}

tryOnScopeDispose(stopHandle)

return stopHandle
}
15 changes: 2 additions & 13 deletions packages/core/useActiveElement/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { ConfigurableDocumentOrShadowRoot, ConfigurableWindow } from '../_configurable'
import { ref } from 'vue'
import { defaultWindow } from '../_configurable'
import { onElementRemoval } from '../onElementRemoval'
import { useEventListener } from '../useEventListener'
import { useMutationObserver } from '../useMutationObserver'

export interface UseActiveElementOptions extends ConfigurableWindow, ConfigurableDocumentOrShadowRoot {
/**
Expand Down Expand Up @@ -59,18 +59,7 @@ export function useActiveElement<T extends HTMLElement>(
}

if (triggerOnRemoval) {
useMutationObserver(document as any, (mutations) => {
mutations.filter(m => m.removedNodes.length)
.map(n => Array.from(n.removedNodes))
.flat()
.forEach((node) => {
if (node === activeElement.value)
trigger()
})
}, {
childList: true,
subtree: true,
})
onElementRemoval(activeElement, trigger, { document })
}

trigger()
Expand Down
Loading
Loading