@threlte/core
Version:
A 3D framework for the web, built on top of Svelte and Three.js
37 lines (36 loc) • 1.36 kB
JavaScript
import { derived } from 'svelte/store';
import { useUserContext } from '../context/fragments/user.js';
export function useThrelteUserContext(namespace, value, options) {
const userCtxStore = useUserContext();
if (!userCtxStore) {
throw new Error('No user context store found, did you invoke this function outside of your main <Canvas> component?');
}
// return the plain user context store
if (!namespace) {
return {
subscribe: userCtxStore.subscribe
};
}
// return a specific user context entry
if (namespace && !value) {
return derived(userCtxStore, (ctx) => ctx[namespace]);
}
// we are possibly setting a new user context entry here
userCtxStore.update((ctx) => {
if (namespace in ctx) {
// skip is the default value
if (!options || options.existing === 'skip')
return ctx;
if (options.existing === 'merge') {
const v = typeof value === 'function' ? value() : value;
Object.assign(ctx[namespace], v);
return ctx;
}
}
// also handles options.existing === 'replace'
const v = typeof value === 'function' ? value() : value;
ctx[namespace] = v;
return ctx;
});
return userCtxStore.current[namespace];
}