@threlte/core
Version:
A 3D framework for the web, built on top of Svelte and Three.js
79 lines (78 loc) • 2.48 kB
TypeScript
import { type Readable } from 'svelte/store';
type UserContextEntry = Record<string, any>;
type UserContext = Record<string, UserContextEntry>;
type SetThrelteUserContextOptions = {
existing: 'merge' | 'replace' | 'skip';
};
/**
* ### `useThrelteUserContext`
*
* The `UserContext` is a store scoped to the context of your root `<Canvas>` component and can be used to
* store and retrieve arbitrary data from anywhere in the Threlte app.
* Because it's scoped, it's especially interesting for authoring reusable components and inter-component communication.
*
* `useThrelteUserContext` can set and get the user context store.
*
* ### Get the user context store
*
* If no `namespace` is provided, the whole user context store is returned.
*
* ```svelte
* <script>
* import { useThrelteUserContext } from '@threlte/core'
*
* const userCtx = useThrelteUserContext()
* console.log($userCtx) // -> { 'some-context': { foo: 'bar' } }
* </script>
* ```
*
* If a `namespace` is provided, the hook returns a derived store.
*
* ```svelte
* <script>
* import { useThrelteUserContext } from '@threlte/core'
*
* const ctx = useThrelteUserContext('some-context')
* console.log($ctx) // -> { foo: 'bar' }
* </script>
* ```
*
* ### Set the user context store
*
* ```svelte
* <script>
* import { useThrelteUserContext } from '@threlte/core'
*
* const getCtx = () => {
* return {
* foo: 'bar'
* }
* }
*
* const ctx = useThrelteUserContext('some-context', getCtx)
* console.log(ctx) // -> { foo: 'bar' }
* </script>
* ```
*
* By default, when a context is set at a given namespace, setting it again will be ignored.
* You can override this behaviour:
*
* ```svelte
* <script>
* import { useThrelteUserContext } from '@threlte/core'
*
* const getCtx = () => {
* return {
* foo: 'bar'
* }
* }
*
* const ctx = useThrelteUserContext('some-context', getCtx, { exising: 'merge' })
* console.log(ctx) // -> { foo: 'bar' }
* </script>
* ```
*/
export declare function useThrelteUserContext<UC extends UserContext = UserContext>(): Readable<UC>;
export declare function useThrelteUserContext<UCT extends UserContextEntry = UserContextEntry>(namespace: string): Readable<UCT>;
export declare function useThrelteUserContext<UCT extends UserContextEntry = UserContextEntry>(namespace: string, value: UCT | (() => UCT), options?: SetThrelteUserContextOptions): UCT;
export {};