| 1 |
import { __ } from '@wordpress/i18n'; |
| 2 |
import { useSelect } from '@wordpress/data'; |
| 3 |
import type { Post } from '@wordpress/core-data/src/entity-types'; |
| 4 |
import type { Form } from '../../CampaignForm/resources/types'; |
| 5 |
import useSWR from 'swr'; |
| 6 |
import { addQueryArgs } from '@wordpress/url'; |
| 7 |
import apiFetch from '@wordpress/api-fetch'; |
| 8 |
|
| 9 |
export interface FormOption extends Form { |
| 10 |
label: string; |
| 11 |
value: number; |
| 12 |
isLegacyTemplate: boolean; |
| 13 |
} |
| 14 |
|
| 15 |
/** |
| 16 |
* @since 4.3.0 |
| 17 |
*/ |
| 18 |
export default function useFormOptions(campaignId?: number): { |
| 19 |
formOptions: FormOption[]; |
| 20 |
isResolving: boolean; |
| 21 |
} { |
| 22 |
const { forms, isResolving } = useSelect((select) => { |
| 23 |
const query = { per_page: 100 }; |
| 24 |
return { |
| 25 |
// @ts-ignore |
| 26 |
forms: select('core').getEntityRecords<Post[]>('postType', 'give_forms', query), |
| 27 |
// @ts-ignore |
| 28 |
isResolving: select('core/data').getIsResolving('core', 'getEntityRecords', [ |
| 29 |
'postType', |
| 30 |
'give_forms', |
| 31 |
query, |
| 32 |
]), |
| 33 |
}; |
| 34 |
}, []); |
| 35 |
|
| 36 |
const { data, isLoading } = useSWR<{ items: { id: number }[] }>( |
| 37 |
campaignId |
| 38 |
? addQueryArgs('/give-api/v2/admin/forms', { |
| 39 |
campaignId, |
| 40 |
status: 'publish', |
| 41 |
}) as string |
| 42 |
: null, |
| 43 |
(path) => apiFetch({ path }) |
| 44 |
); |
| 45 |
|
| 46 |
const campaignFormIds = data?.items?.map((form) => form.id) ?? []; |
| 47 |
|
| 48 |
const filteredForms = |
| 49 |
campaignId && campaignFormIds.length > 0 |
| 50 |
? forms?.filter((form) => campaignFormIds.includes(form?.id)) |
| 51 |
: forms; |
| 52 |
|
| 53 |
const formOptions: FormOption[] = |
| 54 |
filteredForms?.map(({ title, id, formTemplate, isLegacyForm, link, name }) => ({ |
| 55 |
label: __(title?.rendered || name || 'Untitled Form', 'give'), |
| 56 |
value: id, |
| 57 |
isLegacyForm, |
| 58 |
isLegacyTemplate: isLegacyForm && formTemplate === 'legacy', |
| 59 |
link, |
| 60 |
})) ?? []; |
| 61 |
|
| 62 |
return { |
| 63 |
formOptions: |
| 64 |
isResolving || isLoading |
| 65 |
? [{ label: __('Loading...', 'give'), value: 0 } as FormOption] |
| 66 |
: formOptions, |
| 67 |
isResolving: isResolving || isLoading, |
| 68 |
}; |
| 69 |
} |
| 70 |
|