| 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 |
icon: string |
| 15 |
title?: string |
| 16 |
makeRequest: (snippet: Snippet) => Promise<SnippetsExport | string> |
| 17 |
} |
| 18 |
|
| 19 |
const ExportButton: React.FC<ExportButtonProps> = ({ name, label, icon, title, makeRequest }) => { |
| 20 |
const { snippet, isWorking, setIsWorking, handleRequestError } = useSnippetForm() |
| 21 |
|
| 22 |
const handleClick = () => { |
| 23 |
setIsWorking(true) |
| 24 |
|
| 25 |
makeRequest(snippet) |
| 26 |
.then(response => downloadSnippetExportFile(response, snippet)) |
| 27 |
// translators: %s: error message. |
| 28 |
.catch((error: unknown) => handleRequestError(error, __('Could not download export file.', 'code-snippets'))) |
| 29 |
.finally(() => setIsWorking(false)) |
| 30 |
} |
| 31 |
|
| 32 |
return ( |
| 33 |
<Button name={name} onClick={handleClick} disabled={isWorking} title={title}> |
| 34 |
<span className={`dashicons ${icon}`} aria-hidden="true" /> |
| 35 |
{label} |
| 36 |
</Button> |
| 37 |
) |
| 38 |
} |
| 39 |
|
| 40 |
export const ExportButtons: React.FC = () => { |
| 41 |
const api = useSnippetsAPI() |
| 42 |
const { snippet } = useSnippetForm() |
| 43 |
|
| 44 |
return ( |
| 45 |
<div className="snippet-export-buttons"> |
| 46 |
<ExportButton |
| 47 |
name="export_snippet" |
| 48 |
label={__('Export', 'code-snippets')} |
| 49 |
icon="dashicons-upload" |
| 50 |
title={__('Download snippet as JSON', 'code-snippets')} |
| 51 |
makeRequest={api.export} |
| 52 |
/> |
| 53 |
|
| 54 |
{window.CODE_SNIPPETS_EDIT?.enableDownloads && 'cond' !== getSnippetType(snippet) && ( |
| 55 |
<ExportButton |
| 56 |
name="export_snippet_code" |
| 57 |
label={__('Download', 'code-snippets')} |
| 58 |
icon="dashicons-download" |
| 59 |
makeRequest={api.exportCode} |
| 60 |
/>)} |
| 61 |
</div> |
| 62 |
) |
| 63 |
} |
| 64 |
|