1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 02:44:45 +00:00

feat(packages/vue): add tryOnScopeDispose composable

This commit is contained in:
2024-10-19 06:40:32 +07:00
parent 9cc8f08d43
commit 7b4f2d0c0a
2 changed files with 79 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
import { defineComponent, effectScope, type PropType } from 'vue';
import { tryOnScopeDispose } from '.';
import { mount } from '@vue/test-utils';
import type { VoidFunction } from '@robonen/stdlib';
const ComponentStub = defineComponent({
props: {
callback: {
type: Function as PropType<VoidFunction>,
required: true
}
},
setup(props) {
tryOnScopeDispose(props.callback);
},
});
describe('tryOnScopeDispose', () => {
it('returns false when the scope is not active', () => {
const callback = vi.fn();
const detectedScope = tryOnScopeDispose(callback);
expect(detectedScope).toBe(false);
expect(callback).not.toHaveBeenCalled();
});
it('run the callback when the scope is disposed', () => {
const callback = vi.fn();
const scope = effectScope();
let detectedScope: boolean | undefined;
scope.run(() => {
detectedScope = tryOnScopeDispose(callback);
});
expect(detectedScope).toBe(true);
expect(callback).not.toHaveBeenCalled();
scope.stop();
expect(callback).toHaveBeenCalled();
});
it('run callback when the component is unmounted', () => {
const callback = vi.fn();
const component = mount(ComponentStub, {
props: { callback },
});
expect(callback).not.toHaveBeenCalled();
component.unmount();
expect(callback).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,22 @@
import type { VoidFunction } from '@robonen/stdlib';
import { getCurrentScope, onScopeDispose } from 'vue';
/**
* @name tryOnScopeDispose
* @category Components
* @description A composable that will run a callback when the scope is disposed or do nothing if the scope isn't available.
*
* @param {VoidFunction} callback - The callback to run when the scope is disposed.
* @returns {boolean} - Returns true if the callback was run, otherwise false.
*
* @example
* tryOnScopeDispose(() => console.log('Scope disposed'));
*/
export function tryOnScopeDispose(callback: VoidFunction) {
if (getCurrentScope()) {
onScopeDispose(callback);
return true;
}
return false;
}