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