UNPKG

react-code-canvas

Version:

A browser-based canvas for rendering React components at runtime

38 lines (37 loc) 2.03 kB
import { ReactElement } from 'react'; import { RunnerOptions } from './types'; export type UseRunnerProps = RunnerOptions & { /** whether to cache previous element when error occurs with current code */ disableCache?: boolean; /** called whenever the current code fails to produce output: either it threw, * or it evaluated cleanly but never called `render(...)` / set a default * export. Both are reported the moment evaluation returns. * * Throws are reported every time they occur, because each is a distinct * failure the host may need to react to. The "rendered nothing" case is * reported at most once per mount, so editor keystrokes through a * half-written component don't spam it. */ onError?: (error: string) => void; /** Evaluate the initial code on the next macrotask instead of during the * first render. * * Transform + eval are synchronous, so by default the very first commit * already contains the finished output and a loading state can never be * painted. Deferring the first evaluation commits an empty pending state, * lets the browser paint it, then evaluates — which is what makes a loader * actually visible. Costs one macrotask on initial mount, so it is opt-in: * only turn it on when something is actually rendered during that window. * * Applies to the first evaluation only. Later code changes (editor * keystrokes) stay synchronous, so typing does not flash a loader. */ deferFirstRender?: boolean; }; export type UseRunnerReturn = { element: ReactElement | null; error: string | null; /** true once the current code has produced real (non-null) content at least once; * stays true afterwards even if a later edit errors, so callers can show a * loading state only before the very first successful render. */ hasRendered: boolean; }; export declare const useRunner: ({ code, scope, disableCache, onError, deferFirstRender, }: UseRunnerProps) => UseRunnerReturn;