import type { AdminViewServerPropsOnly, BuildFormStateArgs, BuildTableStateArgs, Data, DocumentPreferences, DocumentSlots, FormState, Params, RenderDocumentVersionsProperties, ServerFunction, ServerFunctionClient, SlugifyServerFunctionArgs, } from 'payload' import type { Slugify } from 'payload/shared' import React, { createContext, useCallback } from 'react' import type { RenderFieldServerFnArgs, RenderFieldServerFnReturnType, } from '../../forms/fieldSchemasToFormState/serverFunctions/renderFieldServerFn.js' import type { buildFormStateHandler } from '../../utilities/buildFormState.js' import type { buildTableStateHandler } from '../../utilities/buildTableState.js' import type { CopyDataFromLocaleArgs } from '../../utilities/copyDataFromLocale.js' import type { getUpcomingScheduledPublishHandler, GetUpcomingScheduledPublishHandlerArgs, schedulePublishHandler, SchedulePublishHandlerArgs, } from '../../utilities/schedulePublishHandler.js' import { reduceToSerializableFields } from '../../forms/Form/reduceToSerializableFields.js' type GetFormStateClient = ( args: { signal?: AbortSignal } & Omit, ) => ReturnType type SchedulePublishClient = ( args: { signal?: AbortSignal } & Omit, ) => ReturnType type GetUpcomingScheduledPublishClient = ( args: { signal?: AbortSignal } & Omit, ) => ReturnType type GetTableStateClient = ( args: { signal?: AbortSignal } & Omit, ) => ReturnType type SlugifyClient = ( args: { signal?: AbortSignal } & Omit, ) => ReturnType export type RenderDocumentResult = { data: any Document: React.ReactNode preferences: DocumentPreferences } type RenderDocumentBaseArgs = { collectionSlug: string disableActions?: boolean docID: number | string drawerSlug?: string initialData?: Data initialState?: FormState overrideEntityVisibility?: boolean paramsOverride?: AdminViewServerPropsOnly['params'] redirectAfterCreate?: boolean redirectAfterDelete: boolean redirectAfterDuplicate: boolean redirectAfterRestore?: boolean searchParams?: Params /** * Properties specific to the versions view */ versions?: RenderDocumentVersionsProperties } export type RenderDocumentServerFunction = ServerFunction< RenderDocumentBaseArgs, Promise > type RenderDocumentServerFunctionHookFn = ( // No req or importMap - those are augmented by handleServerFunctions args: { signal?: AbortSignal } & RenderDocumentBaseArgs, ) => Promise type CopyDataFromLocaleClient = ( args: { signal?: AbortSignal } & Omit, ) => Promise<{ data: Data }> type GetDocumentSlots = (args: { collectionSlug: string id?: number | string signal?: AbortSignal }) => Promise type RenderFieldClient = (args: RenderFieldServerFnArgs) => Promise type SwitchLanguageClient = (lang: string) => Promise export type ServerFunctionsContextType = { _internal_renderField: RenderFieldClient copyDataFromLocale: CopyDataFromLocaleClient getDocumentSlots: GetDocumentSlots getFormState: GetFormStateClient getTableState: GetTableStateClient getUpcomingScheduledPublish: GetUpcomingScheduledPublishClient renderDocument: RenderDocumentServerFunctionHookFn schedulePublish: SchedulePublishClient serverFunction: ServerFunctionClient slugify: SlugifyClient switchLanguage: SwitchLanguageClient } export const ServerFunctionsContext = createContext( undefined, ) export const useServerFunctions = () => { const context = React.use(ServerFunctionsContext) if (context === undefined) { throw new Error('useServerFunctions must be used within a ServerFunctionsProvider') } return context } export const ServerFunctionsProvider: React.FC<{ children: React.ReactNode serverFunction: ServerFunctionClient }> = ({ children, serverFunction }) => { if (!serverFunction) { throw new Error('ServerFunctionsProvider requires a serverFunction prop') } const getDocumentSlots = useCallback( async ({ signal: _signal, ...args }) => await serverFunction({ name: 'render-document-slots', args, }), [serverFunction], ) const schedulePublish = useCallback( async (args) => { const { signal: remoteSignal, ...rest } = args try { if (!remoteSignal?.aborted) { const result = await serverFunction({ name: 'schedule-publish', args: { ...rest, date: rest.date ? new Date(rest.date.getTime()) : rest.date, } satisfies SchedulePublishHandlerArgs, }) if (!remoteSignal?.aborted) { return result } } } catch (_err) { console.error(_err) // eslint-disable-line no-console } let error = `Error scheduling ${rest.type}` if (rest.doc) { error += ` for document with ID ${rest.doc.value} in collection ${rest.doc.relationTo}` } return { error } }, [serverFunction], ) const getUpcomingScheduledPublish = useCallback( async (args) => { const { signal: remoteSignal, ...rest } = args if (remoteSignal?.aborted) { return [] } const result = (await serverFunction({ name: 'get-upcoming-scheduled-publish', args: rest, })) as Awaited> return remoteSignal?.aborted ? [] : result }, [serverFunction], ) const getFormState = useCallback( async (args) => { const { signal: remoteSignal, ...rest } = args try { if (!remoteSignal?.aborted) { const result = (await serverFunction({ name: 'form-state', args: { ...rest, documentFormState: reduceToSerializableFields(rest.documentFormState), formState: reduceToSerializableFields(rest.formState), initialBlockFormState: reduceToSerializableFields(rest.initialBlockFormState), } satisfies Parameters[0], })) as Awaited> // TODO: infer this type when `strictNullChecks` is enabled if (!remoteSignal?.aborted) { const file = rest.formState?.file if (typeof File !== 'undefined' && result.state?.file) { if (file?.initialValue instanceof File) { result.state.file.initialValue = file.initialValue } if (file?.value instanceof File) { result.state.file.value = file.value } } return result } } } catch (_err) { console.error(_err) // eslint-disable-line no-console } return { state: null } }, [serverFunction], ) const getTableState = useCallback( async (args) => { const { signal: remoteSignal, ...rest } = args try { if (!remoteSignal?.aborted) { const result = (await serverFunction({ name: 'table-state', args: rest, })) as Awaited> // TODO: infer this type when `strictNullChecks` is enabled if (!remoteSignal?.aborted) { return result } } } catch (_err) { console.error(_err) // eslint-disable-line no-console } // return { state: args.formState } }, [serverFunction], ) const renderDocument = useCallback( async ({ signal: _signal, ...rest }) => { try { const result = (await serverFunction({ name: 'render-document', args: { ...rest, initialState: reduceToSerializableFields(rest.initialState), } satisfies RenderDocumentBaseArgs, })) as Awaited> // TODO: infer this type when `strictNullChecks` is enabled return result } catch (_err) { console.error(_err) // eslint-disable-line no-console } }, [serverFunction], ) const copyDataFromLocale = useCallback( async (args) => { const { signal: remoteSignal, ...rest } = args const result = (await serverFunction({ name: 'copy-data-from-locale', args: rest, })) as Data if (!remoteSignal?.aborted) { return { data: result } } }, [serverFunction], ) const _internal_renderField = useCallback( async (args) => { try { const result = (await serverFunction({ name: 'render-field', args, })) as RenderFieldServerFnReturnType return result } catch (_err) { console.error(_err) // eslint-disable-line no-console } }, [serverFunction], ) const slugify = useCallback( async ({ signal: _signal, ...rest }) => { try { const result = (await serverFunction({ name: 'slugify', args: { ...rest, } satisfies SlugifyServerFunctionArgs, })) as Awaited> // TODO: infer this type when `strictNullChecks` is enabled return result } catch (_err) { console.error(_err) // eslint-disable-line no-console } }, [serverFunction], ) const switchLanguage = useCallback( async (lang) => { await serverFunction({ name: 'switch-language', args: { lang }, }) }, [serverFunction], ) return ( {children} ) }