| 1 |
import React from 'react' |
| 2 |
import { __ } from '@wordpress/i18n' |
| 3 |
import { useSnippetsAPI } from '../../../../hooks/useSnippetsAPI' |
| 4 |
import { getSnippetType } from '../../../../utils/snippets/snippets' |
| 5 |
import { useSnippetForm } from '../../SnippetForm/WithSnippetFormContext' |
| 6 |
import { downloadSnippetExportFile } from '../../../../utils/files' |
| 7 |
import { Button } from '../../../common/Button' |
| 8 |
import type { SnippetsExport } from '../../../../types/schema/SnippetsExport' |
| 9 |
import type { Snippet } from '../../../../types/Snippet' |
| 10 |
|
| 11 |
interface ExportButtonProps { |
| 12 |
name: string |
| 13 |
label: string |
| 14 |
makeRequest: (snippet: Snippet) => Promise<SnippetsExport | string> |
| 15 |
} |
| 16 |
|
| 17 |
const ExportButton: React.FC<ExportButtonProps> = ({ name, label, makeRequest }) => { |
| 18 |
const { snippet, isWorking, setIsWorking, handleRequestError } = useSnippetForm() |
| 19 |
|
| 20 |
const handleClick = () => { |
| 21 |
setIsWorking(true) |
| 22 |
|
| 23 |
makeRequest(snippet) |
| 24 |
.then(response => downloadSnippetExportFile(response, snippet)) |
| 25 |
// translators: %s: error message. |
| 26 |
.catch((error: unknown) => handleRequestError(error, __('Could not download export file.', 'code-snippets'))) |
| 27 |
.finally(() => setIsWorking(false)) |
| 28 |
} |
| 29 |
|
| 30 |
return ( |
| 31 |
<Button name={name} onClick={handleClick} disabled={isWorking}> |
| 32 |
{label} |
| 33 |
</Button> |
| 34 |
) |
| 35 |
} |
| 36 |
|
| 37 |
export const ExportButtons: React.FC = () => { |
| 38 |
const api = useSnippetsAPI() |
| 39 |
const { snippet } = useSnippetForm() |
| 40 |
|
| 41 |
return ( |
| 42 |
<div className="snippet-export-buttons"> |
| 43 |
<ExportButton |
| 44 |
name="export_snippet" |
| 45 |
label={__('Export', 'code-snippets')} |
| 46 |
makeRequest={api.export} |
| 47 |
/> |
| 48 |
|
| 49 |
{window.CODE_SNIPPETS_EDIT?.enableDownloads && 'cond' !== getSnippetType(snippet) && ( |
| 50 |
<ExportButton |
| 51 |
name="export_snippet_code" |
| 52 |
label={__('Download Code', 'code-snippets')} |
| 53 |
makeRequest={api.exportCode} |
| 54 |
/>)} |
| 55 |
</div> |
| 56 |
) |
| 57 |
} |
| 58 |
|