UNPKG

one

Version:

One is a React framework for web, iOS, and Android apps.

71 lines (70 loc) • 2.52 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var useBackgroundComputation_exports = {}; __export(useBackgroundComputation_exports, { useBackgroundComputation: () => useBackgroundComputation }); module.exports = __toCommonJS(useBackgroundComputation_exports); var import_react = require("react"); var import_createLatestComputation = require("./createLatestComputation.cjs"); function useBackgroundComputation(definition, input) { const [state, setState] = (0, import_react.useState)({ phase: "idle", revision: 0 }); const owner = (0, import_react.useRef)(null); const submitted = (0, import_react.useRef)(null); const active = input !== null; (0, import_react.useLayoutEffect)(() => { if (!active) return; const computation = (0, import_createLatestComputation.createLatestComputation)(definition, (changed) => { setState(changed.phase === "ready" ? { phase: "ready", revision: changed.result.revision } : changed); }); owner.current = computation; return () => { owner.current = null; submitted.current = null; computation.dispose(); }; }, [active, definition]); (0, import_react.useLayoutEffect)(() => { if (input === null) return; submitted.current = { input, factory: definition }; owner.current?.update(input); }, [ active, definition, input ]); const getCurrent = (0, import_react.useCallback)(() => owner.current?.getCurrent() ?? null, []); const matches = active && submitted.current?.input === input && submitted.current.factory === definition; if (matches && state.phase === "failed") throw state.error; const current = owner.current?.getCurrent(); const result = matches && state.phase === "ready" && current && state.revision === current.revision ? current : null; return { result, getCurrent }; }