| 1 |
import React from 'react' |
| 2 |
import { __ } from '@wordpress/i18n' |
| 3 |
import { Button } from '../../common/Button' |
| 4 |
import { useSnippetsAPI } from '../../../hooks/useSnippets' |
| 5 |
import { downloadSnippetExportFile } from '../../../utils/files' |
| 6 |
import { useSnippetForm } from '../../../hooks/useSnippetForm' |
| 7 |
import type { SnippetsExport } from '../../../types/SnippetsExport' |
| 8 |
import type { AxiosResponse } from 'axios' |
| 9 |
|
| 10 |
export const ExportButtons: React.FC = () => { |
| 11 |
const api = useSnippetsAPI() |
| 12 |
const { snippet, isWorking, setIsWorking, handleRequestError } = useSnippetForm() |
| 13 |
|
| 14 |
const handleFileResponse = (response: AxiosResponse<string | SnippetsExport>) => { |
| 15 |
const data = response.data |
| 16 |
setIsWorking(false) |
| 17 |
console.info('file response', response) |
| 18 |
|
| 19 |
if ('string' === typeof data) { |
| 20 |
downloadSnippetExportFile(data, snippet) |
| 21 |
} else { |
| 22 |
const JSON_INDENT_SPACES = 2 |
| 23 |
downloadSnippetExportFile(JSON.stringify(data, undefined, JSON_INDENT_SPACES), snippet, 'json') |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
return ( |
| 28 |
<> |
| 29 |
<Button |
| 30 |
name="export_snippet" |
| 31 |
onClick={() => { |
| 32 |
setIsWorking(true) |
| 33 |
|
| 34 |
api.export(snippet) |
| 35 |
.then(handleFileResponse) |
| 36 |
// translators: %s: error message. |
| 37 |
.catch((error: unknown) => handleRequestError(error, __('Could not download export file.', 'code-snippets'))) |
| 38 |
}} |
| 39 |
disabled={isWorking} |
| 40 |
> |
| 41 |
{__('Export', 'code-snippets')} |
| 42 |
</Button> |
| 43 |
|
| 44 |
{window.CODE_SNIPPETS_EDIT?.enableDownloads ? |
| 45 |
<Button |
| 46 |
name="export_snippet_code" |
| 47 |
onClick={() => { |
| 48 |
api.exportCode(snippet) |
| 49 |
.then(handleFileResponse) |
| 50 |
// translators: %s: error message. |
| 51 |
.catch((error: unknown) => handleRequestError(error, __('Could not download file.', 'code-snippets'))) |
| 52 |
}} |
| 53 |
disabled={isWorking} |
| 54 |
> |
| 55 |
{__('Export Code', 'code-snippets')} |
| 56 |
</Button> : ''} |
| 57 |
</> |
| 58 |
) |
| 59 |
} |
| 60 |
|