| 1 |
import React, { useState } from 'react' |
| 2 |
import classnames from 'classnames' |
| 3 |
import { __ } from '@wordpress/i18n' |
| 4 |
import { WithRestAPIContext } from '../../hooks/useRestAPI' |
| 5 |
import { fetchQueryParam, updateQueryParams } from '../../utils/urls' |
| 6 |
import { Toolbar } from '../common/Toolbar' |
| 7 |
import { UploadForm } from './UploadForm/UploadForm' |
| 8 |
import { MigrateForm } from './MigrateForm/MigrateForm' |
| 9 |
import type { ReactNode } from 'react' |
| 10 |
|
| 11 |
const TABS = ['upload', 'migrate'] as const |
| 12 |
|
| 13 |
type TabType = typeof TABS[number] |
| 14 |
|
| 15 |
const TAB_CONTENT: Record<TabType, ReactNode> = { |
| 16 |
upload: <UploadForm />, |
| 17 |
migrate: <MigrateForm /> |
| 18 |
} |
| 19 |
|
| 20 |
const TAB_LABELS: Record<TabType, string> = { |
| 21 |
upload: __('Upload snippets', 'code-snippets'), |
| 22 |
migrate: __('Migrate from other plugins', 'code-snippets') |
| 23 |
} |
| 24 |
|
| 25 |
const isValidTab = (value: string): value is TabType => |
| 26 |
TABS.includes(value as TabType) |
| 27 |
|
| 28 |
const getDefaultTab = (): TabType => { |
| 29 |
const tabParam = fetchQueryParam('tab') |
| 30 |
return tabParam && isValidTab(tabParam) ? tabParam : TABS[0] |
| 31 |
} |
| 32 |
|
| 33 |
export const ImportMenu: React.FC = () => { |
| 34 |
const [activeTab, setActiveTab] = useState<TabType>(getDefaultTab) |
| 35 |
|
| 36 |
return ( |
| 37 |
<> |
| 38 |
<Toolbar /> |
| 39 |
<> |
| 40 |
<h2>{__('Import Snippets', 'code-snippets')}</h2> |
| 41 |
|
| 42 |
<hr className="wp-header-end" /> |
| 43 |
|
| 44 |
<nav |
| 45 |
className="nav-tab-wrapper" |
| 46 |
aria-label={__('Import sources', 'code-snippets')} |
| 47 |
> |
| 48 |
{TABS.map(tab => |
| 49 |
<button |
| 50 |
key={tab} |
| 51 |
type="button" |
| 52 |
className={classnames('nav-tab', { 'nav-tab-active': tab === activeTab })} |
| 53 |
onClick={() => { |
| 54 |
setActiveTab(tab) |
| 55 |
updateQueryParams({ tab }) |
| 56 |
}} |
| 57 |
> |
| 58 |
{TAB_LABELS[tab]} |
| 59 |
</button>)} |
| 60 |
</nav> |
| 61 |
|
| 62 |
<WithRestAPIContext> |
| 63 |
{TABS.map(tab => |
| 64 |
<div key={tab} className={classnames('import-snippets-section', { 'active-section': tab === activeTab })}> |
| 65 |
{TAB_CONTENT[tab]} |
| 66 |
</div>)} |
| 67 |
</WithRestAPIContext> |
| 68 |
</> |
| 69 |
</> |
| 70 |
) |
| 71 |
} |
| 72 |
|