| 1 |
import React, { useCallback, useEffect } from 'react' |
| 2 |
import { __ } from '@wordpress/i18n' |
| 3 |
import domReady from '@wordpress/dom-ready' |
| 4 |
import { useSnippetForm } from '../../../hooks/useSnippetForm' |
| 5 |
|
| 6 |
export const EDITOR_ID = 'snippet_description' |
| 7 |
|
| 8 |
const TOOLBAR_BUTTONS = [ |
| 9 |
[ |
| 10 |
'bold', |
| 11 |
'italic', |
| 12 |
'underline', |
| 13 |
'strikethrough', |
| 14 |
'blockquote', |
| 15 |
'bullist', |
| 16 |
'numlist', |
| 17 |
'alignleft', |
| 18 |
'aligncenter', |
| 19 |
'alignright', |
| 20 |
'link', |
| 21 |
'wp_adv', |
| 22 |
'code_snippets' |
| 23 |
], |
| 24 |
[ |
| 25 |
'formatselect', |
| 26 |
'forecolor', |
| 27 |
'pastetext', |
| 28 |
'removeformat', |
| 29 |
'charmap', |
| 30 |
'outdent', |
| 31 |
'indent', |
| 32 |
'undo', |
| 33 |
'redo', |
| 34 |
'spellchecker' |
| 35 |
] |
| 36 |
] |
| 37 |
|
| 38 |
const initializeEditor = (onChange: (content: string) => void) => { |
| 39 |
window.wp.editor?.initialize(EDITOR_ID, { |
| 40 |
mediaButtons: window.CODE_SNIPPETS_EDIT?.descEditorOptions.mediaButtons, |
| 41 |
quicktags: true, |
| 42 |
tinymce: { |
| 43 |
toolbar: TOOLBAR_BUTTONS.map(line => line.join(' ')), |
| 44 |
setup: editor => { |
| 45 |
editor.on('change', () => onChange(editor.getContent())) |
| 46 |
} |
| 47 |
} |
| 48 |
}) |
| 49 |
} |
| 50 |
|
| 51 |
const DescriptionEditorTextarea: React.FC = () => { |
| 52 |
const { snippet, setSnippet, isReadOnly } = useSnippetForm() |
| 53 |
|
| 54 |
const handleChange = useCallback( |
| 55 |
(desc: string) => setSnippet(previous => ({ ...previous, desc })), |
| 56 |
[setSnippet] |
| 57 |
) |
| 58 |
|
| 59 |
useEffect(() => { |
| 60 |
domReady(() => initializeEditor(handleChange)) |
| 61 |
}, [handleChange]) |
| 62 |
|
| 63 |
return ( |
| 64 |
<textarea |
| 65 |
id={EDITOR_ID} |
| 66 |
className="wp-editor-area" |
| 67 |
onChange={event => handleChange(event.target.value)} |
| 68 |
autoComplete="off" |
| 69 |
disabled={isReadOnly} |
| 70 |
rows={window.CODE_SNIPPETS_EDIT?.descEditorOptions.rows} |
| 71 |
cols={40} |
| 72 |
value={snippet.desc} |
| 73 |
/> |
| 74 |
) |
| 75 |
} |
| 76 |
|
| 77 |
export const DescriptionEditor: React.FC = () => |
| 78 |
window.CODE_SNIPPETS_EDIT?.enableDescription |
| 79 |
? <div className="snippet-description-container"> |
| 80 |
<h2> |
| 81 |
<label htmlFor={EDITOR_ID}> |
| 82 |
{__('Description', 'code-snippets')} |
| 83 |
</label> |
| 84 |
</h2> |
| 85 |
|
| 86 |
<DescriptionEditorTextarea /> |
| 87 |
</div> |
| 88 |
: null |
| 89 |
|