@grail-ui/svelte
Version:
[](https://www.npmjs.com/package/@grail-ui/svelte) [](https://bundlephobia.com/package/@grail-ui/svelte) [ • 1.32 kB
JavaScript
import { get } from 'svelte/store';
import { isFunction } from '../util/is.js';
import documentClickStore from './documentClickStore.js';
export const useClickOutside = (node, config = {}) => {
let options = { enabled: true, ...config };
function isEnabled() {
return typeof options.enabled === 'boolean' ? options.enabled : get(options.enabled);
}
const unsubscribe = documentClickStore.subscribe((e) => {
if (!isEnabled() || !e || e.target === node) {
return;
}
const composedPath = e.composedPath();
if (composedPath.includes(node))
return;
if (options.ignore) {
if (isFunction(options.ignore)) {
if (options.ignore(e))
return;
}
else if (Array.isArray(options.ignore)) {
if (options.ignore.length > 0 &&
options.ignore.some((ignoreEl) => {
return ignoreEl && (e.target === ignoreEl || composedPath.includes(ignoreEl));
}))
return;
}
}
options.handler?.(e);
});
return {
update(params) {
options = { ...options, ...params };
},
destroy() {
unsubscribe();
},
};
};