ui-ingredients
Version:
Headless component library for Svelte powered by zag
40 lines (39 loc) • 1.09 kB
JavaScript
import * as presence from '@zag-js/presence';
import { normalizeProps, useMachine } from '@zag-js/svelte';
export function createPresence(props) {
const service = useMachine(presence.machine, props);
const api = $derived(presence.connect(service, normalizeProps));
function getPresenceProps() {
return {
hidden: !api.present,
'data-state': props.present ? 'open' : 'closed',
};
}
let wasPresent = $state(false);
$effect(() => {
if (!api.present)
return;
if (wasPresent)
return;
wasPresent = true;
});
const unmounted = $derived.by(() => {
if (api.present)
return false;
if (!wasPresent && props.lazyMount)
return true;
if (wasPresent && !props.keepMounted)
return true;
return false;
});
const setReference = (node) => {
api.setNode(node);
};
return {
setReference,
getPresenceProps,
get mounted() {
return !unmounted;
},
};
}