ErrorBoundary
1 year ago
Icons
9 months ago
Notifications
11 months ago
Tabs
9 months ago
store
1 year ago
AdminDetailsPage.module.scss
8 months ago
AdminSection.tsx
1 year ago
ConfirmationDialog.tsx
9 months ago
DefaultPrimaryActionButton.tsx
1 year ago
index.tsx
9 months ago
types.ts
9 months ago
index.tsx
258 lines
| 1 | /** |
| 2 | * External Dependencies |
| 3 | */ |
| 4 | import {useEffect, useRef, useState} from 'react'; |
| 5 | import {FormProvider, SubmitHandler, useForm, useFormContext, useFormState} from 'react-hook-form'; |
| 6 | import {ajvResolver} from '@givewp/admin/ajv'; |
| 7 | |
| 8 | import {SlotFillProvider} from '@wordpress/components'; |
| 9 | import {useDispatch} from '@wordpress/data'; |
| 10 | import {__} from '@wordpress/i18n'; |
| 11 | import {PluginArea} from '@wordpress/plugins'; |
| 12 | import apiFetch from '@wordpress/api-fetch'; |
| 13 | import {JSONSchemaType} from 'ajv'; |
| 14 | |
| 15 | /** |
| 16 | * Internal Dependencies |
| 17 | */ |
| 18 | import {Spinner as GiveSpinner} from '@givewp/components'; |
| 19 | import styles from './AdminDetailsPage.module.scss'; |
| 20 | import AdminSection, {AdminSectionField} from './AdminSection'; |
| 21 | import DefaultPrimaryActionButton from './DefaultPrimaryActionButton'; |
| 22 | import ErrorBoundary from './ErrorBoundary'; |
| 23 | import {BreadcrumbSeparatorIcon, DotsIcons} from './Icons'; |
| 24 | import NotificationPlaceholder from './Notifications'; |
| 25 | import TabsRouter from './Tabs/Router'; |
| 26 | import TabList from './Tabs/TabList'; |
| 27 | import TabPanels from './Tabs/TabPanels'; |
| 28 | import {AdminDetailsPageProps} from './types'; |
| 29 | import {prepareDefaultValuesFromSchema} from '@givewp/admin/utils'; |
| 30 | |
| 31 | import './store'; |
| 32 | |
| 33 | /** |
| 34 | * @since 4.4.0 |
| 35 | */ |
| 36 | export default function AdminDetailsPage<T extends Record<string, any>>({ |
| 37 | objectId, |
| 38 | objectType, |
| 39 | objectTypePlural, |
| 40 | useObjectEntityRecord, |
| 41 | shouldSaveForm, |
| 42 | breadcrumbUrl, |
| 43 | breadcrumbTitle, |
| 44 | pageTitle, |
| 45 | StatusBadge, |
| 46 | PrimaryActionButton = DefaultPrimaryActionButton, |
| 47 | SecondaryActionButton, |
| 48 | ContextMenuItems, |
| 49 | tabDefinitions, |
| 50 | children, |
| 51 | }: AdminDetailsPageProps<T>) { |
| 52 | const [resolver, setResolver] = useState({}); |
| 53 | const [isSaving, setIsSaving] = useState(false); |
| 54 | const [isLoading, setIsLoading] = useState(true); |
| 55 | const [schema, setSchema] = useState<JSONSchemaType<any> | null>(null); |
| 56 | const [showContextMenu, setShowContextMenu] = useState<boolean>(false); |
| 57 | const contextMenuButtonRef = useRef<HTMLButtonElement>(null); |
| 58 | const contextMenuRef = useRef<HTMLDivElement>(null); |
| 59 | |
| 60 | const dispatch = useDispatch(`givewp/admin-details-page-notifications`); |
| 61 | |
| 62 | exposeAdminComponentsAndHooks(); |
| 63 | |
| 64 | useEffect(() => { |
| 65 | if (!objectId) { |
| 66 | return; |
| 67 | } |
| 68 | |
| 69 | apiFetch({ |
| 70 | path: `/givewp/v3/${objectTypePlural}/${objectId}`, |
| 71 | method: 'OPTIONS', |
| 72 | }).then(({schema}: {schema: JSONSchemaType<any>}) => { |
| 73 | setSchema(schema); |
| 74 | setResolver({ |
| 75 | resolver: ajvResolver(schema), |
| 76 | }); |
| 77 | }); |
| 78 | }, [objectId, objectTypePlural]); |
| 79 | |
| 80 | const {record, hasResolved, save, edit} = useObjectEntityRecord(objectId); |
| 81 | |
| 82 | const methods = useForm<T>({ |
| 83 | mode: 'onBlur', |
| 84 | shouldFocusError: true, |
| 85 | ...resolver, |
| 86 | }); |
| 87 | |
| 88 | const {formState, handleSubmit, reset} = methods; |
| 89 | |
| 90 | // Close context menu when clicked outside |
| 91 | useEffect(() => { |
| 92 | const handleClickOutside = (e: MouseEvent) => { |
| 93 | if (!showContextMenu) { |
| 94 | return; |
| 95 | } |
| 96 | |
| 97 | if ( |
| 98 | e.target instanceof HTMLElement && |
| 99 | !contextMenuButtonRef.current?.contains(e.target) && |
| 100 | !contextMenuRef.current?.contains(e.target) |
| 101 | ) { |
| 102 | setShowContextMenu(false); |
| 103 | contextMenuButtonRef.current?.blur(); |
| 104 | } |
| 105 | }; |
| 106 | |
| 107 | document.addEventListener('click', handleClickOutside); |
| 108 | |
| 109 | return () => { |
| 110 | document.removeEventListener('click', handleClickOutside); |
| 111 | }; |
| 112 | }, [showContextMenu]); |
| 113 | |
| 114 | // Set default values when entity is loaded |
| 115 | useEffect(() => { |
| 116 | if (hasResolved && schema && record) { |
| 117 | const preparedRecord = prepareDefaultValuesFromSchema(record, (schema as any)?.properties) as T; |
| 118 | reset(preparedRecord); |
| 119 | setIsLoading(false); |
| 120 | } |
| 121 | }, [hasResolved, !!schema, !!record]); |
| 122 | |
| 123 | const onSubmit: SubmitHandler<T> = async (data) => { |
| 124 | const shouldSave = shouldSaveForm ? shouldSaveForm(formState.isDirty, data) : formState.isDirty; |
| 125 | |
| 126 | if (shouldSave) { |
| 127 | setIsSaving(true); |
| 128 | edit(data); |
| 129 | |
| 130 | try { |
| 131 | // @ts-ignore |
| 132 | const response: T = await save(); |
| 133 | setIsSaving(false); |
| 134 | |
| 135 | const preparedRecord = prepareDefaultValuesFromSchema(response, (schema as any)?.properties) as T; |
| 136 | reset(preparedRecord); |
| 137 | |
| 138 | dispatch.addSnackbarNotice({ |
| 139 | id: `save-success`, |
| 140 | content: __(`${objectType.charAt(0).toUpperCase() + objectType.slice(1)} updated`, 'give'), |
| 141 | }); |
| 142 | } catch (err) { |
| 143 | console.error('🔴 Save failed with error:', err); |
| 144 | setIsSaving(false); |
| 145 | |
| 146 | dispatch.addSnackbarNotice({ |
| 147 | id: `save-error`, |
| 148 | type: 'error', |
| 149 | content: __(`${objectType.charAt(0).toUpperCase() + objectType.slice(1)} update failed`, 'give'), |
| 150 | }); |
| 151 | } |
| 152 | } |
| 153 | }; |
| 154 | |
| 155 | if (isLoading) { |
| 156 | return ( |
| 157 | <div className={styles.loadingContainer}> |
| 158 | <div className={styles.loadingContainerContent}> |
| 159 | <GiveSpinner /> |
| 160 | <div className={styles.loadingContainerContentText}>{__(`Loading ${objectType}...`, 'give')}</div> |
| 161 | </div> |
| 162 | </div> |
| 163 | ); |
| 164 | } |
| 165 | |
| 166 | return ( |
| 167 | <ErrorBoundary> |
| 168 | <FormProvider {...methods}> |
| 169 | <SlotFillProvider> |
| 170 | <form id={'givewp-details-form'} onSubmit={handleSubmit(onSubmit)}> |
| 171 | <article className={`interface-interface-skeleton__content ${styles.page}`}> |
| 172 | <TabsRouter tabDefinitions={tabDefinitions}> |
| 173 | <header className={styles.pageHeader}> |
| 174 | <div className={styles.breadcrumb}> |
| 175 | <a href={breadcrumbUrl}> |
| 176 | {objectTypePlural.charAt(0).toUpperCase() + objectTypePlural.slice(1)} |
| 177 | </a> |
| 178 | <BreadcrumbSeparatorIcon /> |
| 179 | <span>{breadcrumbTitle || record?.name}</span> |
| 180 | </div> |
| 181 | <div className={styles.flexContainer}> |
| 182 | <div className={styles.flexRow}> |
| 183 | <h1 className={styles.pageTitle}>{pageTitle || record?.name}</h1> |
| 184 | {StatusBadge && <StatusBadge />} |
| 185 | </div> |
| 186 | |
| 187 | <div className={`${styles.flexRow} ${styles.justifyContentEnd}`}> |
| 188 | {SecondaryActionButton && ( |
| 189 | <SecondaryActionButton |
| 190 | className={`button button-tertiary ${styles.secondaryActionButton}`} |
| 191 | /> |
| 192 | )} |
| 193 | |
| 194 | <PrimaryActionButton |
| 195 | isSaving={isSaving} |
| 196 | formState={formState} |
| 197 | className={`button button-primary ${styles.primaryActionButton}`} |
| 198 | /> |
| 199 | |
| 200 | {ContextMenuItems && ( |
| 201 | <> |
| 202 | <button |
| 203 | ref={contextMenuButtonRef} |
| 204 | className={`button button-secondary ${styles.contextMenuButton}`} |
| 205 | onClick={(e) => { |
| 206 | e.preventDefault(); |
| 207 | setShowContextMenu(!showContextMenu); |
| 208 | }} |
| 209 | > |
| 210 | <DotsIcons /> |
| 211 | </button> |
| 212 | |
| 213 | {!isSaving && showContextMenu && ( |
| 214 | <div ref={contextMenuRef} className={styles.contextMenu}> |
| 215 | <ContextMenuItems className={styles.contextMenuItem} /> |
| 216 | </div> |
| 217 | )} |
| 218 | </> |
| 219 | )} |
| 220 | </div> |
| 221 | </div> |
| 222 | <TabList tabDefinitions={tabDefinitions} /> |
| 223 | </header> |
| 224 | |
| 225 | <TabPanels tabDefinitions={tabDefinitions} /> |
| 226 | |
| 227 | {children} |
| 228 | </TabsRouter> |
| 229 | </article> |
| 230 | </form> |
| 231 | |
| 232 | <NotificationPlaceholder type="snackbar" /> |
| 233 | |
| 234 | <PluginArea scope={`givewp-${objectType}-details-page`} /> |
| 235 | </SlotFillProvider> |
| 236 | </FormProvider> |
| 237 | </ErrorBoundary> |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | const exposeAdminComponentsAndHooks = (): void => { |
| 242 | (window as any).givewp = (window as any).givewp || {}; |
| 243 | (window as any).givewp.admin = (window as any).givewp.admin || {}; |
| 244 | (window as any).givewp.admin.components = (window as any).givewp.admin.components || {}; |
| 245 | (window as any).givewp.admin.hooks = (window as any).givewp.admin.hooks || {}; |
| 246 | |
| 247 | Object.assign((window as any).givewp.admin, { |
| 248 | components: { |
| 249 | AdminSection, |
| 250 | AdminSectionField, |
| 251 | }, |
| 252 | hooks: { |
| 253 | useFormContext, |
| 254 | useFormState, |
| 255 | }, |
| 256 | }); |
| 257 | }; |
| 258 |