import { type FormEvent, Fragment, type PropsWithChildren, useCallback, useEffect, useMemo, useRef, useState, use, type Usable, } from 'react' import { useRouter } from 'next/navigation' import { Button } from '@keystar/ui/button' import { AlertDialog, DialogContainer, DialogTrigger } from '@keystar/ui/dialog' import { Icon } from '@keystar/ui/icon' import { fileWarningIcon } from '@keystar/ui/icon/icons/fileWarningIcon' import { Box, VStack } from '@keystar/ui/layout' import { ProgressCircle } from '@keystar/ui/progress' import { SlotProvider } from '@keystar/ui/slots' import { toastQueue } from '@keystar/ui/toast' import { Heading, Text } from '@keystar/ui/typography' import { gql, useMutation } from '../../../../admin-ui/apollo' import { CreateButtonLink } from '../../../../admin-ui/components/CreateButtonLink' import { ErrorDetailsDialog } from '../../../../admin-ui/components/Errors' import { GraphQLErrorNotice } from '../../../../admin-ui/components/GraphQLErrorNotice' import { PageContainer } from '../../../../admin-ui/components/PageContainer' import { useKeystone, useList, useListItem } from '../../../../admin-ui/context' import { deserializeItemToValue, Fields, serializeValueToOperationItem, useHasChanges, useInvalidFields, } from '../../../../admin-ui/utils' import type { ActionMeta, BaseListTypeInfo, ConditionalFilter, ConditionalFilterCase, ListMeta, } from '../../../../types' import { BaseToolbar, ColumnLayout, ItemPageHeader, StickySidebar } from './common' export * from './common' type ItemPageProps = { params: Usable<{ id: string listKey: string }> } function useEventCallback unknown>(callback: Func): Func { const callbackRef = useRef(callback) const cb = useCallback((...args: any[]) => { return callbackRef.current(...args) }, []) useEffect(() => { callbackRef.current = callback }) return cb as any } function DeleteButton({ list, itemId, itemLabel, }: { list: ListMeta itemId: string itemLabel: string }) { const [errorDialogValue, setErrorDialogValue] = useState(null) const { adminPath } = useKeystone() const router = useRouter() const [deleteItem] = useMutation( gql`mutation ($id: ID!) { ${list.graphql.names.deleteMutationName}(where: { id: $id }) { id } }`, { variables: { id: itemId } } ) return ( { try { await deleteItem() } catch (err: any) { toastQueue.critical('Unable to delete item', { actionLabel: 'Details', onAction: () => setErrorDialogValue(err), shouldCloseOnAction: true, }) return } toastQueue.neutral(`${list.singular} deleted.`, { timeout: 5000, }) router.push(list.isSingleton ? `${adminPath}/` : `${adminPath}/${list.path}`) }} > Are you sure you want to delete {itemLabel} ? This action cannot be undone. setErrorDialogValue(null)} isDismissable> {errorDialogValue && ( )} ) } function ItemNotFound(props: PropsWithChildren) { return ( Not found {props.children} ) } function ResetButton(props: { onReset: () => void; hasChanges?: boolean }) { return ( Are you sure? Lost changes cannot be recovered. ) } function ItemForm({ listKey, initialValue, itemLabel, onSaveSuccess, fieldModes, fieldPositions, isRequireds, }: { listKey: string initialValue: Record itemLabel: string onSaveSuccess: () => void fieldModes: Record> isRequireds: Record> fieldPositions: Record }) { const list = useList(listKey) const itemId = initialValue.id as string const [updateError, setUpdateError] = useState(null) const [update, { loading, error }] = useMutation( gql`mutation ($id: ID!, $data: ${list.graphql.names.updateInputName}!) { item: ${list.graphql.names.updateMutationName}(where: { id: $id }, data: $data) { id } }`, { errorPolicy: 'all' } ) const [value, setValue] = useState(() => initialValue) function resetValueState() { setValue(() => initialValue) } useEffect(() => resetValueState(), [initialValue]) const invalidFields = useInvalidFields(list.fields, value, isRequireds) const [forceValidation, setForceValidation] = useState(false) const onSave = useEventCallback(async (e: FormEvent) => { if (e.target !== e.currentTarget) return e.preventDefault() const newForceValidation = invalidFields.size !== 0 setForceValidation(newForceValidation) if (newForceValidation) return const { errors } = await update({ variables: { id: itemId, data: serializeValueToOperationItem('update', list.fields, value, initialValue), }, }) const error = errors?.find(x => x.path === undefined || x.path?.length === 1) if (error) { toastQueue.critical('Unable to save item', { actionLabel: 'Details', onAction: () => setUpdateError(new Error(error.message)), shouldCloseOnAction: true, }) return } toastQueue.positive(`Saved changes to ${list.singular.toLocaleLowerCase()}.`, { timeout: 5000, }) onSaveSuccess() }) const hasChangedFields = useHasChanges('update', list.fields, value, initialValue) return (
{/* Workaround for react-aria "bug" where pressing enter in a form field moves focus to the submit button. See: https://github.com/adobe/react-spectrum/issues/5940 */} {!list.hideDelete ? ( ) : null} setUpdateError(null)} isDismissable> {updateError && }
) } export function ItemPage({ params }: ItemPageProps) { const { listKey, id } = use<{ listKey: string; id: string }>(params) return } export function ItemPageInternal({ id, listKey: _listKey }: { id: string; listKey: string }) { const { adminPath, listsKeyByPath } = useKeystone() const listKey = listsKeyByPath[_listKey] const list = useList(listKey) const router = useRouter() const id_ = id as string const [itemId] = Array.isArray(id_) ? id_ : [id_] const { data, error, loading, refetch } = useListItem(listKey, itemId ?? null) const item = data?.item const itemLabel_ = item?.[list.labelField] ?? item?.id const itemLabel = typeof itemLabel_ === 'string' ? itemLabel_ : (itemId ?? '') const pageLoading = loading || itemId === undefined const pageLabel = itemLabel || itemId const pageTitle = list.isSingleton || typeof pageLabel !== 'string' ? list.label : pageLabel const initialValue = useMemo(() => { if (!item) return null return deserializeItemToValue(list.fields, item) }, [list.fields, data?.item]) const { actionsInContext, fieldModes, fieldPositions, isRequireds } = useMemo(() => { const actionModes = Object.fromEntries( Object.entries(list.actions).map(([k, v]) => [k, v.itemView.actionMode]) ) const fieldModes = Object.fromEntries( Object.entries(list.fields).map(([k, v]) => [k, v.itemView.fieldMode]) ) const fieldPositions = Object.fromEntries( Object.entries(list.fields).map(([k, v]) => [k, v.itemView.fieldPosition]) ) const isRequireds = Object.fromEntries( Object.entries(list.fields).map(([k, v]) => [k, v.itemView.isRequired]) ) for (const field of data?.keystone.adminMeta.list?.fields ?? []) { if (!field.itemView) continue fieldModes[field.key] = field.itemView.fieldMode fieldPositions[field.key] = field.itemView.fieldPosition isRequireds[field.key] = field.itemView.isRequired } for (const action of data?.keystone.adminMeta.list?.actions ?? []) { if (!action.itemView) continue actionModes[action.key] = action.itemView.actionMode } // actions within context of an item const actionsInContext = list.actions .map(action => ({ ...action, itemView: { ...action.itemView, actionMode: actionModes[action.key], }, })) .filter(action => action.itemView.actionMode !== 'hidden') return { actionsInContext, fieldModes, fieldPositions, isRequireds, } }, [data?.keystone.adminMeta, list.fields]) function onAction(action: ActionMeta, resultId: string | null) { const { navigation } = action.itemView if ((navigation === 'follow' && resultId === itemId) || navigation === 'refetch') { refetch() } else if (navigation === 'follow' && resultId) { router.push(`${adminPath}/${list.path}/${resultId}`) } else { router.push(list.isSingleton ? `${adminPath}/` : `${adminPath}/${list.path}`) } } return ( } > {pageLoading ? ( ) : ( {item == null && (list.isSingleton ? ( itemId === '1' ? ( “{list.label}” doesn’t exist, or you don’t have access to it. {!list.hideCreate && } ) : ( An item with ID “{itemId}” does not exist. ) ) : ( The item with ID “{itemId}” doesn’t exist, or you don’t have access to it. ))} {initialValue && ( )} )} ) }