import React, { useState, useCallback, useEffect, useMemo } from 'react' import { useMonacoEditor } from '../../../../hooks/useMonacoEditor' import { ContentEditorHTMLEditorMonacoEditorProps } from './interfaces' import nodeToEditorComponentObject from '../../ContentProxy/hooks/useContentEditable/helpers/nodeToEditorComponentObject' import { Button } from '@procraft/ui/dist/Button' import Btn from '@mui/material/Button' import { ContentEditorHTMLEditorMonacoEditorStyled } from './styles' import { RedactorComponentObject } from '../../../..' import { NodeToHtml } from './helpers/NodeToHtml' /** * Здесь с редактированием есть сразу несколько сложных моментов: * * 1. Редактируемый HTML - это чистый текст. Он в себе не содержит информацию является ли это содержимым * реакт-компонента или нет. То есть если открыли для редактирования какой-то HTML-узел, в котором выводятся * реакт-компоненты, то их содержимое будет переведено в обычный HTML, теряя при этом всю динамику. * 2. Сложно учитывать какой именно узел редактируется. То есть, к примеру, если мы открыли какой-то * узел и заменили весь код на несколько HTML-элементов, то будет сложно понять что именно надо будет заменить * в исходной структуре и куда вставить новые элементы. * 3. Возможно придется вставить проверку на наличие в редактируемом узле реакт-компонентов. Если такие есть, то следует запретить редактирование. * 4. В случае, если количество элементов после редактирования будет больше 1 или меньше одного, надо будет вставлять новое содержимое дочерним контентом * текущего элемента. */ export const ContentEditorHTMLEditorMonacoEditor: React.FC< ContentEditorHTMLEditorMonacoEditorProps > = ({ active, element, object, updateObject, parent, updateParent, toggleModalCollapse, }) => { const [source, setSource] = useState(NodeToHtml(element)) const [error, setError] = useState(null) const [isDirty, setIsDirty] = useState(false) // Отслеживаем измненения в объекте useEffect(() => { object setSource(NodeToHtml(element)) }, [element, object, setSource]) const { editorJsx, resetValue, getValue, editor } = useMonacoEditor({ active, language: 'html', source, }) useEffect(() => { setIsDirty(getValue() !== source) }, [getValue, source]) useEffect(() => { const model = editor?.getModel() if (model) { setIsDirty(model.getValue() !== source) const modelOnChange = model.onDidChangeContent((_event) => { const v = model.getValue() setIsDirty(v !== source) setError(null) }) return () => modelOnChange.dispose() } }, [editor, source]) /** * Сохранение изменений */ const saveValue = useCallback(() => { try { /** * Создаем ноду и передаем содержимое как HTML */ const value = getValue() const template = global.document.createElement('div') template.innerHTML = value const newObject = nodeToEditorComponentObject(template) if (!newObject) { setError(new Error('Не был получен объект')) return } const components = newObject.components if (components.length === 1) { updateObject(object, components[0]) } else { /** * Если нет родительского объекта, то выдаем ошибку */ if (!parent || !updateParent) { const error = new Error( `Количество дочерних элементов должно быть 1, а получено ${template.childNodes.length}` ) console.error(error, value, template.children) setError(error) return } else { const parentComponents = [...parent.components] const index = parentComponents.findIndex((n) => n === object) if (index === -1) { setError(new Error('Не найден индекс текущего объекта')) return } const args: Array = [index, 1] // eslint-disable-next-line prefer-spread parentComponents.splice.apply( parentComponents, // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore args.concat(components) ) updateParent(parent, { components: parentComponents, }) } } } catch (error) { setError(error as Error) } }, [object, parent, updateObject, updateParent, getValue]) const buttons = useMemo(() => { return [ , , ] }, [isDirty, resetValue, saveValue]) const copyTemplateCode = useCallback(() => { const {component, components, name, props} = object const code = JSON.stringify({component, components, name, props}, null, 2) navigator.clipboard.writeText(code) }, [object]) const copyTemplateCodeBtn = useMemo(() => { return ( </> Код в буфер (разр.) ) }, [copyTemplateCode]) const hideCodeEditor = useMemo(() => { return ( Свернуть редактор ) }, [toggleModalCollapse]) return ( <>
{editorJsx}
{hideCodeEditor} {process.env.NODE_ENV === 'development' && copyTemplateCodeBtn}
{error ?
{error.message}
: null} {buttons}
) }