UNPKG

@wordpress/widget-dashboard

Version:

Stateless rendering engine for widget dashboards: the WidgetDashboard compound component and its grid-settings kit.

57 lines (56 loc) • 1.94 kB
import { useCallback } from "@wordpress/element"; import { useObservableValue } from "@wordpress/compose"; import { useDashboardInternalContext } from "../../context/dashboard-context.mjs"; import { setActionPending } from "../../utils/pending-actions-map.mjs"; // packages/widget-dashboard/src/components/widget-actions/use-run-actions.ts const NONE = /* @__PURE__ */ new Set(); function isThenable(value) { return typeof value?.then === "function"; } /** * Logs a callback failure with the instance and the action it belongs to. * The rejection is passed through so a plain object stays inspectable. * * Hosts have no notices capability yet, so this is the only surface. * * @param {string} uuid The instance. * @param {string} actionId The action. * @param {unknown} error Whatever the callback threw or rejected with. */ function logActionFailure(uuid, actionId, error) { console.error(`Widget ${uuid} action "${actionId}" failed.`, error); } /** * Runs an instance's callback actions and tracks, by `id`, the ones whose * promise has not settled. The state lives with the instance, so it * survives the surface that ran the action unmounting. * * @param {string} uuid The instance. */ function useRunActions(uuid) { const { pendingActions } = useDashboardInternalContext(); const pendingIds = useObservableValue(pendingActions, uuid) ?? NONE; return { run: useCallback(async (action) => { let result; try { result = action.callback(); } catch (error) { logActionFailure(uuid, action.id, error); return; } if (!isThenable(result)) return; setActionPending(pendingActions, uuid, action.id, true); try { await result; } catch (error) { logActionFailure(uuid, action.id, error); } finally { setActionPending(pendingActions, uuid, action.id, false); } }, [pendingActions, uuid]), pendingIds }; } export { useRunActions }; //# sourceMappingURL=use-run-actions.mjs.map