Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A high-performance framework with fine-grained observable/signal-based reactivity for building rich applications.

License

NotificationsYou must be signed in to change notification settings

vobyjs/voby

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Voby's Banner

Join The Discord ChatOpen The PlaygroundDonate With Open Collective

A high-performance framework with fine-grained observable/signal-based reactivity for building rich applications.

Features

This works similarly toSolid, but without a custom Babel transform and with a different API.

  • No VDOM: there's no VDOM overhead, the framework deals with raw DOM nodes directly.
  • No stale closures: functions are always executed afresh, no need to worry about previous potential executions of the current function, ever.
  • No rules of hooks: hooks are just regular functions, which you can nest indefinitely, call conditionally, use outside components, whatever you want.
  • No dependencies arrays: the framework is able to detect what depends on what else automatically, no need to specify dependencies manually.
  • No props diffing: updates are fine grained, there's no props diffing, whenever an attribute/property/class/handler/etc. should be updated it's updated directly and immediately.
  • No key prop: you can just map over arrays, or use theFor component with an array of unique values, no need to specify keys explicitly.
  • No Babel: there's no need to use Babel with this framework, it works with plain old JS (plus JSX if you are into that). As a consequence we have 0 transform function bugs, because we don't have a transform function.
  • No magic: what you see is what you get, your code is not transformed to actually do something different than what you write, there are no surprises.
  • No server support: for the time being this framework is focused on local-first rich applications, most server-related features are not implemented: no hydration, no server components, no streaming etc.
  • Observable-based: observables, also known as "signals", are at the core of our reactivity system. The way it works is very different from a React-like system, it may be more challenging to learn, but it's well worth the effort.
  • Work in progress: this is probably beta software, I'm working on it because I need something with great performance forNotable, I'm allergic to third-party dependencies, I'd like something with an API that resonates with me, and I wanted to deeply understand how the more solidSolid, which you should also check out, works.

Demos

You can find some demos and benchmarks below, more demos are contained inside the repository.

APIs

MethodsComponentsHookscoreHookswebTypesExtras
$DynamicuseBooleanuseAbortControllerContextContributing
$$ErrorBoundaryuseCleanupuseAbortSignalDirectiveGlobals
batchForuseContextuseAnimationFrameDirectiveOptionsJSX
createContextFragmentuseDisposeduseAnimationLoopEffectOptionsTree Shaking
createDirectiveIfuseEffectuseEventListenerFunctionMaybeTypeScript
createElementKeepAliveuseMemouseFetchMemoOptions
hPortalusePromiseuseIdleCallbackObservable
hmrSuspenseuseReadonlyuseIdleLoopObservableLike
htmlSwitchuseResolveduseIntervalObservableReadonly
isBatchingTernaryuseResourceuseMicrotaskObservableReadonlyLike
isObservableuseRootuseTimeoutObservableMaybe
isServeruseSelectorObservableOptions
isStoreuseSuspendedResource
lazyuseUntrackedStoreOptions
render
renderToString
resolve
store
template
tick
untrack

Usage

This framework is simply a view layer built on top of the Observable libraryoby, knowing how that works is necessary to understand how this works.

This framework basically re-exports everything thatoby exports, sometimes with a slightly different interface, adjusted for usage as components or hooks, plus some additional functions.

Methods

The following top-level functions are provided.

$

This function is just the default export ofoby, it can be used to wrap a value in an observable.

No additional methods are attached to this function. Everything thatoby attaches to it is instead exported as components and hooks.

Read upstream documentation.

Interface:

function$<T>():Observable<T|undefined>;function$<T>(value:undefined,options?:ObservableOptions<T|undefined>):Observable<T|undefined>;function$<T>(value:T,options?:ObservableOptions<T>):Observable<T>;

Usage:

import{$}from'voby';// Create an observable without an initial value$<number>();// Create an observable with an initial value$(1);// Create an observable with an initial value and a custom equality functionconstequals=(value,valuePrev)=>Object.is(value,valuePrev);consto=$(1,{ equals});// Create an observable with an initial value and a special "false" equality function, which is a shorthand for `() => false`, which causes the observable to always emit when its setter is calledconstoFalse=$(1,{equals:false});// Gettero();// => 1// Settero(2);// => 2// Setter via a function, which gets called with the current valueo(value=>value+1);// => 3// Setter that sets a function, it has to be wrapped in another function because the above form existsconstnoop=()=>{};o(()=>noop);

$$

This function unwraps a potentially observable value.

Read upstream documentation.

Interface:

function$$<T>(value:T):(TextendsObservableReadonly<inferU> ?U :T);

Usage:

import{$$}from'voby';// Getting the value out of an observableconsto=$(123);$$(o);// => 123// Getting the value out of a function$$(()=>123);// => 123// Getting the value out of an observable but not out of a function$$(o,false);// => 123$$(()=>123,false);// => () => 123// Getting the value out of a non-observable and non-function$$(123);// => 123

batch

This function prevents effects from firing until the function passed to it resolves. It's largely only useful when the passed function is asynchronous, as otherwise the reactivity system is lazy so effects won't be over-executed anyway.

Read upstream documentation.

Interface:

functionbatch<T>(fn:()=>Promise<T>|T):Promise<Awaited<T>>;functionbatch<T>(value:T):Promise<Awaited<T>>;

Usage:

import{batch}from'voby';batch// => Same as require ( 'oby' ).batch

createContext

This function creates a context object, optionally with a default value, which can later be used to provide a new value for the context or to read the current value.

A context'sProvider will register the value of context with its children.

Interface:

typeContextProvider<T>=(props:{value:T,children:JSX.Element})=>JSX.Element;typeContext<T>={Provider:ContextProvider<T>};functioncreateContext<T>(defaultValue?:T):Context<T>;

Usage:

import{createContext,useContext}from'voby';constApp=()=>{constContext=createContext(123);return(<>{()=>{constvalue=useContext(Context);return<p>{value}</p>;}}<Context.Providervalue={312}>{()=>{constvalue=useContext(Context);return<p>{value}</p>;}}</Context.Provider></>);};

createDirective

This function creates a directive provider, which can be used to register a directive with its children.

A directive is a function that always receives anElement as its first argument, which is basically a ref to the target element, and arbitrary user-provided arguments after that.

Each directive has a unique name and it can be called by simply writinguse:directivename={[arg1, arg2, ...argN]]} in the JSX.

Directives internally are registered using context providers, so you can also override directives for a particular scope just by registering another directive with the same name closer to where you are reading it.

A directive'sProvider will register the directive with its children, which is always what you want, but it can lead to messy code due to nesting.

A directive'sregister function will register the directive with the current parent observer, which is usually only safe to do at the root level, but it will lead to very readable code.

Interface:

typeDirectiveFunction=<Textendsunknown[]>(ref:Element, ...args:T)=>void;typeDirectiveProvider=(props:{children:JSX.Element})=>JSX.Element;typeDirectiveRef<Textendsunknown[]>=( ...args:T)=>((ref:Element)=>void);typeDirectiveRegister=()=>void;typeDirective={Provider:DirectiveProvider,ref:DirectiveRef,register:DirectiveRegister};functioncreateDirective<Textendsunknown[]=[]>(name:string,fn:DirectiveFunction<T>,options?:DirectiveOptions):Directive;

Usage:

import{createDirective,useEffect}from'voby';// First of all if you are using TypeScript you should extend the "JSX.Directives" interface, so that TypeScript will know about your new directivenamespaceJSX{interfaceDirectives{tooltip:[title:string]// Mapping the name of the directive to the array of arguments it accepts}}// Then you should create a directive providerconstTooltipDirective=createDirective('tooltip',(ref,title:string)=>{useEffect(()=>{if(!ref())return;// The element may not be available yet, or it might have been unmounted// Code that implements a tooltip for the given element here...});});// Then you can use the new "tooltip" directive anywhere inside the "TooltipDirective.Provider"constApp=()=>{return(<TooltipDirective.Provider><inputvalue="Placeholder..."use:tooltip={['This is a tooltip!']}/></TooltipDirective.Provider>);};// You can also use directives directly by padding them along as refsconstApp=()=>{return<inputref={TooltipDirective.ref('This is a tooltip!')}value="Placeholder..."/>;};

createElement

This is the internal function that will make DOM nodes and call/instantiate components, it will be called for you automatically via JSX.

Interface:

functioncreateElement<P={}>(component:JSX.Component<P>,props:P|null, ...children:JSX.Element[]):()=>JSX.Element);

Usage:

import{createElement}from'voby';constelement=createElement('div',{class:'foo'},'child');// => () => HTMLDivElement

h

This function is just an alias for thecreateElement function, it's more convenient to use if you want to use Voby in hyperscript mode just because it has a much shorter name.

Interface:

functionh<P={}>(component:JSX.Component<P>,props:P|null, ...children:JSX.Element[]):()=>JSX.Element);

Usage:

import{h}from'voby';constelement=h('div',{class:'foo'},'child');// => () => HTMLDivElement

hmr

This function wraps a component and makes it HMR-aware, for implementations of HMR like Vite's, this makes the component refresh itself and its children without requiring a reload of the whole page.

For an automated way to make all your components HMR-aware check outvoby-vite instead.

Interface:

functionhmr<TextendsFunction>(accept:Function,component:T):T;

Usage:

import{hmr}from'voby';// Define a componentconstCounter=({ value}):JSX.Element=>{// Return something...};// Optionally attach components and other values to itCounter.Button=({ onClick}):JSX.Element=>{// Return something...};Counter.INITIAL_VALUE=0;// Lastly export it as "default", wrapped in "hmr"// Only components exported as "default" are supportedexportdefaulthmr(import.meta.hot?.accept?.bind(import.meta.hot),Counter);

html

This function provides an alternative way to use the framework, without writing JSX or using theh function manually, it instead allows you to write your markup as tagged template literals.

htm is used under the hood, read its documentation.

Interface:

functionhtml(strings:TemplateStringsArray, ...values:any[]):JSX.Element;

Usage:

import{html,If}from'voby';constCounter=():JSX.Element=>{constvalue=$(0);constincrement=()=>value(prev=>prev+1);constdecrement=()=>value(prev=>prev-1);returnhtml`<h1>Counter</h1><p>${value}</p><buttononClick=${increment}>+</button><buttononClick=${decrement}>-</button>  `;};// Using a custom component without registering itconstNoRegistration=():JSX.Element=>{returnhtml`<${If}when=${true}><p>content</p></${If}>  `;};// Using a custom component after registering it, so you won't need to interpolate it anymorehtml.register({ If});constNoRegistration=():JSX.Element=>{returnhtml`<Ifwhen=${true}><p>content</p></If>  `;};

isBatching

This function tells you if batching is currently active or not.

Interface:

functionisBatching():boolean;

Usage:

import{batch,isBatching}from'voby';// Checking if currently batchingisBatching();// => falsebatch(()=>{isBatching();// => true});isBatching();// => false

isObservable

This function tells you if a variable is an observable or not.

Interface:

functionisObservable<T=unknown>(value:unknown):value isObservable<T>|ObservableReadonly<T>;

Usage:

import{$,isObservable}from'voby';isObservable(123);// => falseisObservable($(123));// => true

isServer

This function tells you if your code is executing in a browser environment or not.

Interface:

functionisServer():boolean;

Usage:

import{isServer}from'voby';isServer();// => true or false

isStore

This function tells you if a variable is a store or not.

Interface:

functionisStore(value:unknown):boolean;

Usage:

import{store,isStore}from'voby';isStore({});// => falseisStore(store({}));// => true

lazy

This function creates a lazy component, which is loaded via the provided function only when/if needed.

This function usesuseResource internally, so it's significant forSuspense too.

Interface:

typeLazyComponent<P={}>=(props:P)=>ObservableReadonly<Child>;typeLazyFetcher<P={}>=()=>Promise<{default:JSX.Component<P>}|JSX.Component<P>>;typeLazyResult<P={}>=LazyComponent<P>&({preload:()=>Promise<void>});functionlazy<P={}>(fetcher:LazyFetcher<P>):LazyResult<P>;

Usage:

import{lazy}from'voby';constLazyComponent=lazy(()=>import('./component'));

render

This function mounts a component inside a provided DOM element and returns a disposer function for unmounting it and stopping all reactivity inside it.

Interface:

functionrender(child:JSX.Element,parent?:HTMLElement|null):Disposer;

Usage:

import{render}from'voby';constApp=()=><p>Hello, World!</p>;constdispose=render(<App/>,document.body);dispose();// Unmounted and all reactivity inside it stopped

renderToString

This works just likerender, but it returns a Promise to the HTML representation of the rendered component.

This is currently implemented in a way that works only inside a browser-like environement, so you'll need to useJSDOM or similar for this to work server-side, but it can work server-side too potentially.

This function automatically waits for allSuspense boundaries to resolve before returning.

Interface:

functionrenderToString(child:JSX.Element):Promise<string>;

Usage:

import{renderToString}from'voby';constApp=()=><p>Hello, World!</p>;consthtml=awaitrenderToString(<App/>);

resolve

This function basically resolves any reactivity inside the passed argument, basically replacing every function it finds with a memo to the value of that function.

You may never need to use this function yourself, but it's necessary internally at times to make sure that a child value is properly tracked by its parent computation.

Read upstream documentation.

Interface:

typeResolvablePrimitive=null|undefined|boolean|number|bigint|string|symbol;typeResolvableArray=Resolvable[];typeResolvableObject={[Keyinstring|number|symbol]?:Resolvable};typeResolvableFunction=()=>Resolvable;typeResolvable=ResolvablePrimitive|ResolvableObject|ResolvableArray|ResolvableFunction;functionresolve<T>(value:T):TextendsResolvable ?T :never;

Usage:

import{resolve}from'voby';resolve// => Same as require ( 'oby' ).resolve

store

This function returns a deeply reactive version of the passed object, where property accesses and writes are automatically interpreted as Observables reads and writes for you.

Read upstream documentation.

Interface:

functionstore<T>(value:T,options?:StoreOptions):T;

Usage:

import{store}from'voby';store// => Same as require ( 'oby' ).store

template

This function enables constructing elements withSolid-level performance without using the Babel transform, but also without the convenience of that.

It basically works likesinuous's template function, but with a cleaner API, since you don't have to access your props any differently inside the template here.

Basically you can use this to wrap a component that doesn't directly create any observables or call any hooks to significanly improve performance when instantiating that component.

Interface:

functiontemplate<P={}>(fn:((props:P)=>JSX.Element)):((props:P)=>()=>Element);

Usage:

import{template}from'voby';constRow=template(({ id, cls, label, onSelect, onRemove})=>{// Now Row is super fast to instantiatereturn(<trclass={cls}><tdclass="col-md-1">{id}</td><tdclass="col-md-4"><aonClick={onSelect}>{label}</a></td><tdclass="col-md-1"><aonClick={onRemove}><spanclass="glyphicon glyphicon-remove"ariaHidden={true}></span></a></td><tdclass="col-md-6"></td></tr>);});constTable=()=>{constrows=[/* props for all your rows here */];returnrows.map(row=><Row{...row}> );};

tick

This function forces effects scheduled for execution to be executed immediately, bypassing automatic or manual batching.

Read upstream documentation.

Interface:

functiontick():void;

Usage:

import{tick}from'voby';tick// => Same as require ( 'oby' ).tick

untrack

This function executes the provided function without creating dependencies on observables retrieved inside it.

Read upstream documentation.

Interface:

functionuntrack<T>(fn:()=>T):T;functionuntrack<T>(value:T):T;

Usage:

import{untrack}from'voby';untrack// => Same as require ( 'oby' ).untrack

Components

The following components are provided.

Crucially some components are provided for control flow, since regular JavaScript control flow primitives are not reactive, and we need to have reactive alternatives to them to have great performance.

Dynamic

This component is just an alternative tocreateElement that can be used in JSX, it's useful to create a new element dynamically.

Interface:

functionDynamic<P={}>(props:{component:ObservableMaybe<JSX.Component<P>,props?:FunctionMaybe<P|null>,children?:JSX.Element}):JSX.Element;

Usage:

import{Dynamic}from'voby';constApp=()=>{constheading='h2';return(<Dynamiccomponent={heading}>      Some content</Dynamic>);};

ErrorBoundary

The error boundary catches errors thrown inside it, and renders a fallback component when that happens.

Interface:

functionErrorBoundary(props:{fallback:JSX.Element|((props:{error:Error,reset:Callback})=>JSX.Element),children:JSX.Element}):ObservableReadonly<JSX.Element>;

Usage:

import{ErrorBoundary}from'voby';constFallback=({ reset, error}:{reset:()=>void,error:Error})=>{return(<><p>Error:{error.message}</p><buttononClick={error}>Recover</button></>);};constSomeComponentThatThrows=()=>{throw'whatever';};constApp=()=>{return(<ErrorBoundaryfallback={Fallback}><SomeComponentThatThrows/></ErrorBoundary>);};

For

This component is the reactive alternative to natively mapping over an array.

It must be called with an array, or a function that returns an array, ofunique values, and each of them are passed to the child function to render something.

It can be used to map over values either with a keyed (default) or unkeyed (opt-in) strategy. Readthis for some details about the differences between those, and theupstream documentation.

Interface:

functionFor<T>(props:{values?:FunctionMaybe<readonlyT[]>,fallback?:JSX.ELement,children:((value:T,index:FunctionMaybe<number>)=>JSX.Element)}):ObservableReadonly<JSX.Element>;functionFor<T>(props:{values?:FunctionMaybe<readonlyT[]>,fallback?:JSX.ELement,pooled?:true,unkeyed?:true,children:((value:ObservableReadonly<T>,index:FunctionMaybe<number>)=>JSX.Element)}):ObservableReadonly<JSX.Element>;

Usage:

import{For}from'voby';constApp=()=>{constnumbers=[1,2,3,4,5];return(<Forvalues={numbers}>{(value)=>{return<p>Value:{value}</p>}}</For>);};

Fragment

This is just the internal component used for rendering fragments:<></>, you probably would never use this directly even if you are not using JSX, since you can return plain arrays from your components anyway.

Interface:

functionFragment(props:{children:JSX.Element}):JSX.Element;

Usage:

import{Fragment}from'voby';constApp=()=>{return(<Fragment><p>child 1</p><p>child 2</p></Fragment>);};

If

This component is the reactive alternative to the nativeif.

If a function is passed as the children then it will be called with a read-only observable that contains the current, always truthy, value of the "when" condition.

Interface:

typeTruthy<T=unknown>=Extract<T,number|bigint|string|true|object|symbol|Function>;functionIf<T>(props:{when:FunctionMaybe<T>,fallback?:JSX.Element,children:JSX.Element|((value:(()=>Truthy<T>))=>JSX.Element)}):ObservableReadonly<JSX.Element>;

Usage:

import{If}from'voby';constApp=()=>{constvisible=$(false);consttoggle=()=>visible(!visible());return(<><buttononClick={toggle}>Toggle</button><Ifwhen={visible}><p>Hello!</p></If></>);};

KeepAlive

This component allows you to create singleton instances of other components that survive their parent components being disposed, and can therefore be reused cheaply.

Components rendered inside aKeepAlive are detached from the rest of the reactivity graph, so they don't inherit any context provided outside of their parentKeepAlive wrapper.

Components rendered inside aKeepAlive are kept in memory until the wrapperKeepAlive is unmounted andttl milliseconds have passed without anotherKeepAlive with the sameid being mounted. Or never, if nottl prop is provided.

Interface:

functionKeepAlive(props:{id:FunctionMaybe<string>,ttl?:FunctionMaybe<number>,children:JSX.Element}):ObservableReadonly<JSX.Element>;

Usage:

import{KeepAlive}from'voby';// Render some expensive component inside a KeepAliveconstApp=()=>{return(<KeepAliveid="some-unique-id"ttl={60_000}><SomeExpensiveComponent/></KeepAlive>);};

Portal

This component mounts its children inside a provided DOM element, or insidedocument.body otherwise.

Themount prop can also be an observable, if its value changes the portal is reparented.

Thewhen prop can be used to apply the portal conditionally, if it explicitly resolves to false then children are mounted normally, as if they weren't wrapped in a portal.

Events will propagate natively, according to the resulting DOM hierarchy, not the components hierarchy.

Interface:

functionPortal(props:{when:boolean,mount?:JSX.Element,wrapper?:JSX.Element,children:JSX.Element}):(()=>JSX.Element|null)&({metadata:{portal:HTMLDivElement}});

Usage:

import{Portal}from'voby';constModal=()=>{// Some modal component maybe...};constApp=()=>{return(<Portalmount={document.body}><Modal/></Portal>);};

Suspense

This component is likeIf, the reactive alternative to the nativeif, but the fallback branch is shown automatically while there are some resources loading in the main branch, and the main branch is kept alive under the hood.

So this can be used to show some fallback content while the actual content is loading in the background.

This component relies onuseResource to understand if there's a resource loading or not.

This component also supports a manual "when" prop for manually deciding whether the fallback branch should be rendered or not.

Interface:

functionSuspense(props:{when?:FunctionMaybe<unknown>,fallback?:JSX.Element,children:JSX.Element}):ObservableReadonly<JSX.Element>;

Usage:

import{Suspense}from'voby';constApp=()=>{constContent=()=>{constresource=useResource(()=>makeSomePromise());return(<Ifwhen={()=>!resource().pending&&!resource().error}>{resource().value}</If>);};constSpinner=()=>{return<p>Loading...</p>;};return(<Suspensefallback={<Spinner/>}><Content/></Suspense>);};

Switch

This component is the reactive alternative to the nativeswitch.

Interface:

functionSwitch<T>(props:{when:FunctionMaybe<T>,fallback?:JSX.Element,children:JSX.Element}):ObservableReadonly<JSX.Element>;Switch.Case=function<T>(props:{when:T,children:JSX.Element}):(()=>JSX.Element)&({metadata:[T,JSX.Element]});Switch.Default=function(props:{ children:JSX.Element}):(()=>JSX.Element)&({metadata:[JSX.Element]});

Usage:

import{Switch}from'voby';constApp=()=>{constvalue=$(0);constincrement=()=>value(value()+1);constdecrement=()=>value(value()-1);return(<><Switchwhen={value}><Switch.Casewhen={0}><p>0, the boundary between positives and negatives! (?)</p></Switch.Case><Switch.Casewhen={1}><p>1, the multiplicative identity!</p></Switch.Case><Switch.Default><p>{value}, I don't have anything interesting to say about that :(</p></Switch.Default></Switch><buttononClick={increment}>+</button><buttononClick={decrement}>-</button></>);};

Ternary

This component is the reactive alternative to the native ternary operator.

The first child will be rendered when the condition is truthy, otherwise the second child will be rendered.

Interface:

functionTernary(props:{when:FunctionMaybe<unknown>,children:[JSX.Element,JSX.Element]}):ObservableReadonly<JSX.Element>;

Usage:

import{Ternary}from'voby';constApp=()=>{constvisible=$(false);consttoggle=()=>visible(!visible());return(<><buttononClick={toggle}>Toggle</button><Ternarywhen={visible}><p>Visible :)</p><p>Invisible :(</p></Ternary></>);};

Hookscore

The following core hooks are provided.

Most of these are just functions thatoby provides, re-exported asuse* functions.

useBoolean

This hook is like the reactive equivalent of the!! operator, it returns you a boolean, or a function to a boolean, depending on the input that you give it.

Read upstream documentation.

Interface:

functionuseBoolean(value:FunctionMaybe<unknown>):FunctionMaybe<boolean>;

Usage:

import{useBoolean}from'voby';useBoolean// => Same as require ( 'oby' ).boolean

useCleanup

This hook registers a function to be called when the parent computation is disposed.

Read upstream documentation.

Interface:

functionuseCleanup(fn:()=>void):void;

Usage:

import{useCleanup}from'voby';useCleanup// => Same as require ( 'oby' ).cleanup

useContext

This hook retrieves the value out of a context object.

Interface:

functionuseContext<T>(context:Context<T>):T|undefined;

Usage:

import{createContext,useContext}from'voby';constApp=()=>{constctx=createContext(123);constvalue=useContext(ctx);return<p>{value}</p>;};

useDisposed

This hook returns a boolean read-only observable that is set totrue when the parent computation gets disposed of.

Read upstream documentation.

Interface:

functionuseDisposed():ObservableReadonly<boolean>;

Usage:

import{useDisposed}from'voby';useDisposed// => Same as require ( 'oby' ).disposed

useEffect

This hook registers a function to be called when any of its dependencies change. If a function is returned it's automatically registered as a cleanup function.

Read upstream documentation.

Interface:

functionuseEffect(fn:()=>(()=>void)|void):(()=>void);

Usage:

import{useEffect}from'voby';useEffect// => Same as require ( 'oby' ).effect

useMemo

This hook is the crucial other ingredient that we need, other than observables themselves, to have a powerful reactive system that can track dependencies and re-execute computations when needed.

This hook registers a function to be called when any of its dependencies change, and the return of that function is wrapped in a read-only observable and returned.

Read upstream documentation.

Interface:

functionuseMemo<T>(fn:()=>T,options?:MemoOptions<T|undefined>):ObservableReadonly<T>;

Usage:

import{useMemo}from'voby';useMemo// => Same as require ( 'oby' ).memo

usePromise

This hook wraps a promise in an observable, so that you can be notified when it resolves or rejects.

This hook usesuseResource internally, so it's significant forSuspense too.

Interface:

functionusePromise<T>(promise:FunctionMaybe<Promise<T>>):ObservableReadonly<Resource<T>>;

Usage:

import{usePromise}from'voby';constApp=()=>{constrequest=fetch('https://my.api').then(res=>res.json(0));constresource=usePromise(request);return()=>{conststate=resource();if(state.pending)return<p>pending...</p>;if(state.error)return<p>{state.error.message}</p>;return<p>{JSON.stringify(state.value)}</p>};};

useReadonly

This hook creates a read-only observable out of another observable.

Read upstream documentation.

Interface:

functionuseReadonly<T>(observable:Observable<T>|ObservableReadonly<T>):ObservableReadonly<T>;

Usage:

import{useReadonly}from'voby';useReadonly// => Same as require ( 'oby' ).readonly

useResolved

This hook receives a value, or an array of values, potentially wrapped in functions and/or observables, and unwraps it/them.

If no callback is used then it returns the unwrapped value, otherwise it returns whatever the callback returns.

This is useful for handling reactive and non reactive values the same way. Usually if the value is a function, or always for convenience, you'd want to wrap theuseResolved call in auseMemo, to maintain reactivity.

This is potentially a more convenient version of$$, made especially for handling nicely arguments passed that your hooks receive that may or may not be observables.

Interface:

The precise interface for this function is insane, you can find it here:https://github.com/fabiospampinato/voby/blob/master/src/hooks/use_resolved.ts

Usage:

import{$,useResolved}from'voby';useResolved(123);// => 123useResolved($(123));// => 123useResolved(()=>123);// => 123useResolved(()=>123,false);// => () => 123useResolved($(123),value=>321);// => 321useResolved([$(123),()=>123],(a,b)=>321);// => 321

useResource

This hook wraps the result of a function call with an observable, handling the cases where the function throws, the result is an observable, the result is a promise or an observale that resolves to a promise, and the promise rejects, so that you don't have to worry about these issues.

This basically provides a unified way to handle sync and async results, observable and non observable results, and functions that throw and don't throw.

This function is also the mechanism through whichSuspense understands if there are things loading under the hood or not.

When thevalue property is read while fetching, or when thelatest property is read the first time, or after an error, while fetching, thenSuspense boundaries will be triggered.

When thevalue property or thelatest property are read after the fetch errored they will throw, triggeringErrorBoundary.

The passed function is tracked and it will be automatically re-executed whenever any of the observables it reads change.

Interface:

functionuseResource<T>(fetcher:(()=>ObservableMaybe<PromiseMaybe<T>>)):Resource<T>;

Usage:

import{useResource}from'voby';constfetcher=()=>fetch('https://my.api');constresource=useResource(fetcher);

useRoot

This hook creates a new computation root, detached from any parent computation.

Read upstream documentation.

Interface:

functionuseRoot<T>(fn:(dispose:()=>void)=>T):T;

Usage:

import{useRoot}from'voby';useRoot// => Same as require ( 'oby' ).root

useSelector

This hook massively optimizesisSelected kind of workloads.

Read upstream documentation.

Interface:

typeSelectorFunction<T>=(value:T)=>ObservableReadonly<boolean>;functionuseSelector<T>(source:()=>T|ObservableReadonly<T>):SelectorFunction<T>;

Usage:

import{useSelector}from'voby';useSelector// => Same as require ( 'oby' ).selector

useSuspended

This hook returns a read-only observable that tells you if the closest suspense boundary is currently suspended or not.

Read upstream documentation.

Interface:

functionuseSuspended():ObservableReadonly<boolean>;

Usage:

import{useSuspended}from'voby';useSuspended// => Same as require ( 'oby' ).suspended

useUntracked

This hook returns an untracked version of a value.

Read upstream documentation.

Interface:

functionuseUntracked<T>(fn:()=>T):()=>T;functionuseUntracked<T>(value:T):()=>T;

Usage:

import{useUntracked}from'voby';useUntracked// => Same as require ( 'oby' ).untracked

Hooksweb

The following web hooks are provided.

Most of these are just reactive alternatives to native web APIs.

useAbortController

This hook is just an alternative tonew AbortController () that automatically aborts itself when the parent computation is disposed.

Interface:

functionuseAbortController(signals?:ArrayMaybe<AbortSignal>):AbortController;

Usage:

import{useAbortController}from'voby';constcontroller=useAbortController();

useAbortSignal

This hook is just a convenient alternative touseAbortController, if you are only interested in its signal, which is automatically aborted when the parent computation is disposed.

Interface:

functionuseAbortSignal(signals?:ArrayMaybe<AbortSignal>):AbortSignal;

Usage:

import{useAbortSignal}from'voby';constsignal=useAbortSignal();

useAnimationFrame

This hook is just an alternative torequestAnimationFrame that automatically clears itself when the parent computation is disposed.

Interface:

functionuseAnimationFrame(callback:ObservableMaybe<FrameRequestCallback>):Disposer;

Usage:

import{useAnimationFrame}from'voby';useAnimationFrame(()=>console.log('called'));

useAnimationLoop

This hook is just a version ofuseAnimationFrame that loops until the parent computation is disposed.

Interface:

functionuseAnimationLoop(callback:ObservableMaybe<FrameRequestCallback>):Disposer;

Usage:

import{useAnimationLoop}from'voby';useAnimationLoop(()=>console.log('called'));

useEventListener

This hook is just an alternative toaddEventListener that automatically clears itself when the parent computation is disposed.

Interface:

functionuseEventListener(target:FunctionMaybe<EventTarget>,event:FunctionMaybe<string>,handler:ObservableMaybe<(event:Event)=>void>,options?:FunctionMaybe<true|AddEventListenerOptions>):Disposer;

Usage:

import{useEventListener}from'voby';useEventListener(document,'click',console.log);

useFetch

This hook wraps the output of a fetch request in an observable, so that you can be notified when it resolves or rejects. The request is also aborted automatically when the parent computation gets disposed of.

This hook usesuseResource internally, so it's significant forSuspense too.

Interface:

functionuseFetch(request:FunctionMaybe<RequestInfo>,init?:FunctionMaybe<RequestInit>):ObservableReadonly<Resource<Response>>;

Usage:

import{useFetch}from'voby';constApp=()=>{constresource=useFetch('https://my.api');return()=>{conststate=resource();if(state.pending)return<p>pending...</p>;if(state.error)return<p>{state.error.message}</p>;return<p>Status:{state.value.status}</p>};};

useIdleCallback

This hook is just an alternative torequestIdleCallback that automatically clears itself when the parent computation is disposed.

Interface:

functionuseIdleCallback(callback:ObservableMaybe<IdleRequestCallback>,options?:FunctionMaybe<IdleRequestOptions>):Disposer;

Usage:

import{useIdleCallback}from'voby';useIdleCallback(()=>console.log('called'));

useIdleLoop

This hook is just a version ofuseIdleCallback that loops until the parent computation is disposed.

Interface:

functionuseIdleLoop(callback:ObservableMaybe<IdleRequestCallback>,options?:FunctionMaybe<IdleRequestOptions>):Disposer;

Usage:

import{useIdleLoop}from'voby';useIdleLoop(()=>console.log('called'));

useInterval

This hook is just an alternative tosetInterval that automatically clears itself when the parent computation is disposed.

Interface:

functionuseInterval(callback:ObservableMaybe<Callback>,ms?:FunctionMaybe<number>):Disposer;

Usage:

import{useInterval}from'voby';useInterval(()=>console.log('called'),1000);

useMicrotask

This hook is just an alternative toqueueMicrotask that automatically clears itself when the parent computation is disposed, and that ensures things like contexts, error boundaries etc. keep working inside the microtask.

Interface:

functionuseMicrotask(fn:()=>void):void;

Usage:

import{useMicrotask}from'voby';useMicrotask(()=>console.log('called'));

useTimeout

This hook is just an alternative tosetTimeout that automatically clears itself when the parent computation is disposed.

Interface:

functionuseTimeout(callback:ObservableMaybe<Callback>,ms?:FunctionMaybe<number>):Disposer;

Usage:

import{useTimeout}from'voby';useTimeout(()=>console.log('called'),1000);

Types

Context

This type describes the object thatcreateContext gives you.

Interface:

typeContext<T=unknown>={Provider(props:{value:T,children:JSX.Element}):JSX.Element};

Usage:

import{useContext}from'voby';importtype{Context}from'voby';// Create an alternative useContext that throws if the context is not availableconstuseNonNullableContext=<T>(context:Context<T>):NonNullable<T>=>{constvalue=useContext(context);if(value===null||value===undefined)thrownewError('Missing context');returnvalue;};

Directive

This type describes the object thatcreateDirective gives you.

Interface:

typeDirective<Argumentsextendsunknown[]=[]>={Provider:(props:{children:JSX.Element})=>JSX.Element,ref:( ...args:Arguments)=>((ref:Element)=>void),register:()=>void};

Usage:

import{$$,useEffect}from'voby';importtype{Directive,FunctionMaybe}from'voby';// Example hook for turning a directive into a hookconstuseDirective=<Textendsunknown[]=[]>(directive:Directive<T>)=>{return(ref:FunctionMaybe<Element|undefined>, ...args:T):void=>{useEffect(()=>{consttarget=$$(ref);if(!target)return;directive.ref( ...args)(target);});};};

DirectiveOptions

This type describes the options object that thecreateDirective function accepts.

Interface:

typeDirectiveOptions={immediate?:boolean// If `true` the directive is called as soon as the node is created, otherwise it also waits for that node to be attached to the DOM};

Usage:

import{createDirective}from'voby';// Create an regular, non-immediate, directiveconstTooltipDirective=createDirective('tooltip',(ref,title:string)=>{// Implementation...});// Create an immediate directiveconstTooltipDirectiveImmediate=createDirective('tooltip',(ref,title:string)=>{// Implementation...},{immediate:true});

EffectOptions

This type describes the options object that theuseEffect hook accepts.

Interface:

typeEffectOptions={suspense?:boolean,sync?:boolean|'init'};

Usage:

import{useEffect}from'voby';// Make a regular asynchronous effectuseEffect(()=>{// Do something...});// Make a synchronous effect, which is strongly discourageduseEffect(()=>{// Do something...},{sync:true});// Make an asynchronous effect that's executed immediately on creation, which is useful in edge casesuseEffect(()=>{// Do something...},{sync:'init'});// Make an effect that won't be paused by `Suspense`, which is useful in edge casesuseEffect(()=>{// Do something...},{suspense:false});

FunctionMaybe

This type says that something can be the value itself or a function that returns that value.

It's useful at times since some components, likeIf, acceptwhen conditions wrapped inFunctionMaybe.

Interface:

typeFunctionMaybe<T>=(()=>T)|T;

Usage:

importtype{FunctionMaybe}from'voby';constSomeConditionalComponent=(when:FunctionMaybe<boolean>,value:string):JSX.Element=>{return(<Ifwhen={when}>{value}</If>);};

Observable

This type says that something is a regular observable, which can be updated via its setter.

Interface:

typeObservable<T>={():T,(value:T):T,(fn:(value:T)=>T):T,readonly[ObservableSymbol]:true};

Usage:

importtype{Observable}from'voby';constfn=(value:Observable<boolean>):void=>{value();// Gettingvalue(true);// Setting};

ObservableLike

This type says that something has the same shape as a regular observable, but it may not actually be an observable.

Interface:

typeObservableLike<T>={():T,(value:T):T,(fn:(value:T)=>T):T};

Usage:

importtype{ObservableLike}from'voby';constfn=(value:ObservableLike<boolean>):void=>{value();// Gettingvalue(true);// Setting};

ObservableReadonly

This type says that something is a read-only observable, which can only be read but not updated.

Interface:

typeObservableReadonly<T>={():T,readonly[ObservableSymbol]:true};

Usage:

importtype{ObservableReadonly}from'voby';constfn=(value:ObservableReadonly<boolean>):void=>{value();// Gettingvalue(true);// This will throw!};

ObservableReadonlyLike

This type says that something hsa the same shape as a read-only observable, but it may not actually be an observable.

Interface:

typeObservableReadonlyLike<T>={():T};

Usage:

importtype{ObservableReadonlyLike}from'voby';constfn=(value:ObservableReadonlyLike<boolean>):void=>{value();// Gettingvalue(true);// This is not supported!};

ObservableMaybe

This type says that something can be the value itself or an observable to that value.

This is super useful if you want to write components and hooks that can accept either plain values or observables to those values.

Interface:

typeObservableMaybe<T>=Observable<T>|ObservableReadonly<T>|T;

Usage:

importtype{ObservableMaybe}from'voby';constButton=({ label}:{label:ObservableMaybe<string>}):JSX.Element=>{return<button>{label}</button>;};

MemoOptions

This type describes the options object that theuseMemo hook accepts.

Interface:

typeMemoOptions<T>={equals?:((value:T,valuePrev:T)=>boolean)|false,sync?:boolean};

Usage:

import{useMemo}from'voby';// Make a regular asynchronous memouseMemo(()=>{// Do something...});// Make a synchronous memo, which is strongly discourageduseMemo(()=>{// Do something...},{sync:true});

ObservableOptions

This type describes the options object that various functions can accept to tweak how the underlying observable works.

Interface:

typeObservableOptions<T>={equals?:((value:T,valuePrev:T)=>boolean)|false};

Usage:

importtype{Observable,ObservableOptions}from'voby';import{$}from'voby';constcreateTimestamp=(options?:ObservableOptions):Observable<number>=>{return$(Date.now(),options);};

Resource

This is the type of object thatuseResource,usePromise anduseFetch will return you.

It's an object that tells if whether the resource is loading or not, whether an error happened or not, if what the eventual resulting value is.

It's a read-only observable that holds the resulting object, but it also comes with helper methods for retrieving specific keys out of the object, which can make some code much cleaner.

Helper methods are memoized automatically for you.

Interface:

typeResourceStaticPending<T>={pending:true,error?:never,value?:never,latest?:T};typeResourceStaticRejected={pending:false,error:Error,value?:never,latest?:never};typeResourceStaticResolved<T>={pending:false,error?:never,value:T,latest:T};typeResourceStatic<T>=ResourceStaticPending<T>|ResourceStaticRejected|ResourceStaticResolved<T>;typeResourceFunction<T>={pending():boolean,error():Error|undefined,value():T|undefined,latest():T|undefined};typeResource<T>=ObservableReadonly<ResourceStatic<T>>&ResourceFunction<T>;

Usage:

importtype{ObservableReadonly,Resource}from'voby';constresource:Resource<Response>=useResource(()=>fetch('https://my.api'));// Reading the static objectresource().pending;// => true | falseresource().error;// => Error | undefinedresource().value;// => Whatever the resource will resolve toresource().latest;// => Whatever the resource will resolve to, or the previous known resolved value if the resource is pending// Using helper methodsresource.pending();// => true | falseresource.error();// => Error | undefinedresource.value();// => Whatever the resource will resolve toresource.latest();// => Whatever the resource will resolve to, or the previous known resolved value if the resource is pending

StoreOptions

This type describes the options object that thestore function accepts.

Interface:

typeStoreOptions={unwrap?:boolean};

Usage:

importtype{StoreOptions}from'voby';import{store}from'voby';constcreateStore=<T>(value:T,options?:StoreOptions):T=>{returnstore(value,options);};

Extras

Extra features and details.

Contributing

If you'd like to contribute to this repo you should take the following steps to install Voby locally:

git clone https://github.com/vobyjs/voby.gitcd vobynpm installnpm run compile

Then you can run any of the demos locally like this:

# Playgroundnpm run dev# Counternpm run dev:counter# Benchmarknpm run dev:benchmark

Globals

The following globals are supported.

  • VOBY: iftrue, then Voby is used in the current client page. This is also used internally to detect if Voby has been loaded multiple times within the same page, which is not supported.

JSX

JSX is supported out of the box, as a rule of thumb it's very similar to how React's JSX works, but with some differences.

  • The value provided to an attribute can always be either just the plain value itself, an observable to that value, or a function to that value. If an observable or a function is provided then that attribute will update itself in a fine-grained manner.
  • There's no "key" attribute because it's unnecessary.
  • Only refs in the function form are supported, so you are incentivized to simply use observables for them too.
  • The "ref" attribute can also accept an array of functions to call, for convenience.
  • Refs are called on the next microtask, making it so the node you'll get will probably be attached to the DOM already. For getting a more immediate reference you can use an "immediate"directive.
  • You can simply just use "class" instead of "className".
  • The "class" attribute can also accept an object of classes or an array of classes, for convenience.
  • SVGs are supported out of the box and will also be updated in a fine-grained manner.
  • The "innerHTML", "outerHTML", "textContent" and "className" props are forbidden on native elements, as they are largely just footguns or non-idiomatic.
  • A React-like "dangerouslySetInnerHTML" attribute is supported for setting some raw HTML.
  • Numbers set as values for style properties that require a unit to be provided will automatically be suffixed with "px".
  • Using CSS variables in the "style" object is supported out of the box.
  • The following events are delegated, automatically:beforeinput,click,dblclick,focusin,focusout,input,keydown,keyup,mousedown,mouseup.
  • Events always bubble according to the natural DOM hierarchy, there's no special bubbling logic forPortal.
  • Class components, but with no lifecycle callbacks, are supported too. They got thrown away with the bath water by other frameworks, but organizing internal methods in a class and assigning that class to refs automatically is actually a really nice feature.

Tree Shaking

Voby is released as a tree-shakeable ESM module. The functions you don't use simply won't be included in the final bundle.

TypeScript

There are two main actions needed to make Voby work with TypeScript.

  1. Voby is an ESM-only framework, so youmight need to mark your package as ESM too in order to use it, you can do that by putting the following in yourpackage.json:
    "type": "module"
  2. You should instruct TypeScript to load the correct JSX types by putting the following in yourtsconfig.json:
     {"compilerOptions": {"jsx":"react-jsx","jsxImportSource":"voby"   } }
  3. Optionally, if you don't want to use a bundler or if you are using a bundler for which a plugin hasn't been written yet you can just define a "React" variable in scope and just use the JSX transform for React:
    import*asReactfrom'voby';

Thanks

  • reactively: for teaching me the awesome push/pull hybrid algorithm that this library is currently using.
  • S: for paving the way to this awesome reactive way of writing software.
  • sinuous/observable: for making me fall in love with Observables and providing a good implementation that this library was originally based on.
  • solid: for being a great sort of reference implementation, popularizing Signal-based reactivity, and having built a great community.
  • trkl: for being so inspiringly small.

License

MIT © Fabio Spampinato

About

A high-performance framework with fine-grained observable/signal-based reactivity for building rich applications.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors5


[8]ページ先頭

©2009-2025 Movatter.jp