/** * What every CRM screen shares: the design kit (`ui`, src/admin/kit), the * frame's own pieces (`kit`: SectionHeader, SettingsForm), navigation, the * frame's header, and one query cache. * * The frame (src/admin/shell/App.jsx) hands these to a screen as props and * puts them on a context here, so a deeply nested row can use `useUi()` * instead of passing them down. The names are the ones Saddle's frame used, * so the screens did not change when CRM left it. */ import { createContext, useContext, useMemo } from '@wordpress/element'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const Ctx = createContext( null ); /** * Whether an API error means the thing is not there (a deleted subscriber, * an unknown route): asking again cannot help. * * @param {*} error The error a query threw. * @return {boolean} Whether it was a 404. */ export function isNotFound( error ) { return ( error?.data?.status === 404 || [ 'not_found', 'rest_no_route' ].includes( error?.code ) ); } /** * Retry a failed query once, never a 404. * * @param {number} failures How many times it has failed. * @param {*} error The last error. * @return {boolean} Whether to try again. */ export function retryQuery( failures, error ) { return failures < 1 && ! isNotFound( error ); } const client = new QueryClient( { defaultOptions: { queries: { staleTime: 30000, retry: retryQuery, refetchOnWindowFocus: false, }, }, } ); export function UiProvider( { ui, kit, navigate, header, children } ) { const value = useMemo( () => ( { ui, kit, navigate, header } ), [ ui, kit, navigate, header ] ); return ( { children } ); } /** * The kit's `ui` primitives, `kit`, `navigate` and `header`. * * @return {{ui: Object, kit: Object, navigate: Function, header: ?Object}} The shared context. */ export function useUi() { const value = useContext( Ctx ); if ( ! value ) { throw new Error( 'useUi() needs a Mailpuff screen around it.' ); } return value; } /** * One of the kit's icons, or a harmless empty element when the kit does not * have it. Icons never carry meaning on their own here. * * @param {string} name Icon name without a suffix, such as `Plus`. * @return {Function} A component. */ export function useIcon( name ) { const { ui } = useUi(); return ui.icons?.[ name ] || EmptyIcon; } function EmptyIcon() { return null; }