import { css } from '@emotion/css' import React, { ChangeEvent, useCallback, useMemo } from 'react' import { Descendant, Editor, Point, Range, Element as SlateElement, Transforms, createEditor, } from 'slate' import { withHistory } from 'slate-history' import { Editable, ReactEditor, RenderElementProps, Slate, useReadOnly, useSlateStatic, withReact, } from 'slate-react' import { CheckListItemElement as CheckListItemType, CustomEditor, RenderElementPropsFor, } from './custom-types.d' const initialValue: Descendant[] = [ { type: 'paragraph', children: [ { text: 'With Slate you can build complex block types that have their own embedded content and behaviors, like rendering checkboxes inside check list items!', }, ], }, { type: 'check-list-item', checked: true, children: [{ text: 'Slide to the left.' }], }, { type: 'check-list-item', checked: true, children: [{ text: 'Slide to the right.' }], }, { type: 'check-list-item', checked: false, children: [{ text: 'Criss-cross.' }], }, { type: 'check-list-item', checked: true, children: [{ text: 'Criss-cross!' }], }, { type: 'check-list-item', checked: false, children: [{ text: 'Cha cha real smooth…' }], }, { type: 'check-list-item', checked: false, children: [{ text: "Let's go to work!" }], }, { type: 'paragraph', children: [{ text: 'Try it out for yourself!' }], }, ] const CheckListsExample = () => { const renderElement = useCallback( (props: RenderElementProps) => , [] ) const editor = useMemo( () => withChecklists(withHistory(withReact(createEditor()))), [] ) return ( ) } const withChecklists = (editor: CustomEditor) => { const { deleteBackward } = editor editor.deleteBackward = (...args) => { const { selection } = editor if (selection && Range.isCollapsed(selection)) { const [match] = Editor.nodes(editor, { match: n => !Editor.isEditor(n) && SlateElement.isElement(n) && n.type === 'check-list-item', }) if (match) { const [, path] = match const start = Editor.start(editor, path) if (Point.equals(selection.anchor, start)) { const newProperties: Partial = { type: 'paragraph', } Transforms.setNodes(editor, newProperties, { match: n => !Editor.isEditor(n) && SlateElement.isElement(n) && n.type === 'check-list-item', }) return } } } deleteBackward(...args) } return editor } const Element = (props: RenderElementProps) => { const { attributes, children, element } = props switch (element.type) { case 'check-list-item': return default: return

{children}

} } const CheckListItemElement = ({ attributes, children, element, }: RenderElementPropsFor) => { const { checked } = element const editor = useSlateStatic() const readOnly = useReadOnly() return (
) => { const path = ReactEditor.findPath(editor, element) const newProperties: Partial = { checked: event.target.checked, } Transforms.setNodes(editor, newProperties, { at: path }) }} /> {children}
) } export default CheckListsExample