mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 19:04:46 +00:00
feat(packages/vue): add useSupported composable
This commit is contained in:
37
packages/vue/src/composables/useSupported/index.test.ts
Normal file
37
packages/vue/src/composables/useSupported/index.test.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { defineComponent } from 'vue';
|
||||||
|
import { describe, it, expect } from 'vitest';
|
||||||
|
import { useSupported } from '.';
|
||||||
|
import { mount } from '@vue/test-utils';
|
||||||
|
|
||||||
|
const ComponentStub = defineComponent({
|
||||||
|
props: {
|
||||||
|
location: {
|
||||||
|
type: String,
|
||||||
|
default: 'location',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
setup(props) {
|
||||||
|
const isSupported = useSupported(() => props.location in window);
|
||||||
|
|
||||||
|
return { isSupported };
|
||||||
|
},
|
||||||
|
template: `<div>{{ isSupported }}</div>`,
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useSupported', () => {
|
||||||
|
it('return whether the feature is supported', async () => {
|
||||||
|
const component = mount(ComponentStub);
|
||||||
|
|
||||||
|
expect(component.text()).toBe('true');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('return whether the feature is not supported', async () => {
|
||||||
|
const component = mount(ComponentStub, {
|
||||||
|
props: {
|
||||||
|
location: 'unsupported',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(component.text()).toBe('false');
|
||||||
|
});
|
||||||
|
});
|
||||||
27
packages/vue/src/composables/useSupported/index.ts
Normal file
27
packages/vue/src/composables/useSupported/index.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { computed } from 'vue';
|
||||||
|
import { useMounted } from '../useMounted';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @name useSupported
|
||||||
|
* @category Utilities
|
||||||
|
* @description SSR-friendly way to check if a feature is supported
|
||||||
|
*
|
||||||
|
* @param {Function} feature The feature to check for support
|
||||||
|
* @returns {ComputedRef<boolean>} Whether the feature is supported
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const isSupported = useSupported(() => 'IntersectionObserver' in window);
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const isSupported = useSupported(() => 'ResizeObserver' in window);
|
||||||
|
*/
|
||||||
|
export function useSupported(feature: () => unknown) {
|
||||||
|
const isMounted = useMounted();
|
||||||
|
|
||||||
|
return computed(() => {
|
||||||
|
// add reactive dependency on isMounted
|
||||||
|
isMounted.value;
|
||||||
|
|
||||||
|
return Boolean(feature());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
{
|
{
|
||||||
"extends": "@robonen/tsconfig/tsconfig.json"
|
"extends": "@robonen/tsconfig/tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"lib": ["DOM"]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user