webapp/src/components/Editor/Editor.tsx

394 lines
11 KiB
TypeScript
Raw Normal View History

import type { Doc } from 'yjs/dist/src/utils/Doc'
import { HocuspocusProvider } from '@hocuspocus/provider'
import { isTextSelection } from '@tiptap/core'
2023-03-08 16:35:13 +00:00
import { Bold } from '@tiptap/extension-bold'
import { BubbleMenu } from '@tiptap/extension-bubble-menu'
import { BulletList } from '@tiptap/extension-bullet-list'
import { CharacterCount } from '@tiptap/extension-character-count'
import { Collaboration } from '@tiptap/extension-collaboration'
import { CollaborationCursor } from '@tiptap/extension-collaboration-cursor'
import { Document } from '@tiptap/extension-document'
import { Dropcursor } from '@tiptap/extension-dropcursor'
import { FloatingMenu } from '@tiptap/extension-floating-menu'
import Focus from '@tiptap/extension-focus'
2023-03-08 16:35:13 +00:00
import { Gapcursor } from '@tiptap/extension-gapcursor'
import { HardBreak } from '@tiptap/extension-hard-break'
import { Heading } from '@tiptap/extension-heading'
import { Highlight } from '@tiptap/extension-highlight'
import { HorizontalRule } from '@tiptap/extension-horizontal-rule'
import { Image } from '@tiptap/extension-image'
import { Italic } from '@tiptap/extension-italic'
2023-03-08 16:35:13 +00:00
import { Link } from '@tiptap/extension-link'
import { ListItem } from '@tiptap/extension-list-item'
import { OrderedList } from '@tiptap/extension-ordered-list'
2023-03-08 16:35:13 +00:00
import { Paragraph } from '@tiptap/extension-paragraph'
import { Placeholder } from '@tiptap/extension-placeholder'
import { Strike } from '@tiptap/extension-strike'
import { Text } from '@tiptap/extension-text'
import { Underline } from '@tiptap/extension-underline'
import { createEffect, createSignal, onCleanup } from 'solid-js'
import { createTiptapEditor, useEditorHTML } from 'solid-tiptap'
import uniqolor from 'uniqolor'
import * as Y from 'yjs'
import { useEditorContext } from '../../context/editor'
import { useLocalize } from '../../context/localize'
import { useSession } from '../../context/session'
import { useSnackbar } from '../../context/snackbar'
import { handleImageUpload } from '../../utils/handleImageUpload'
2024-02-04 11:25:21 +00:00
import { BlockquoteBubbleMenu, FigureBubbleMenu, IncutBubbleMenu } from './BubbleMenu'
import { EditorFloatingMenu } from './EditorFloatingMenu'
2024-02-04 11:25:21 +00:00
import { TextBubbleMenu } from './TextBubbleMenu'
import Article from './extensions/Article'
import { CustomBlockquote } from './extensions/CustomBlockquote'
import { Figcaption } from './extensions/Figcaption'
import { Figure } from './extensions/Figure'
import { Footnote } from './extensions/Footnote'
import { Iframe } from './extensions/Iframe'
import { Span } from './extensions/Span'
import { ToggleTextWrap } from './extensions/ToggleTextWrap'
import { TrailingNode } from './extensions/TrailingNode'
2023-05-07 13:47:10 +00:00
import './Prosemirror.scss'
2023-03-08 16:35:13 +00:00
2023-07-24 14:09:04 +00:00
type Props = {
shoutId: number
2023-03-08 16:35:13 +00:00
initialContent?: string
2023-03-23 17:15:50 +00:00
onChange: (text: string) => void
2023-03-08 16:35:13 +00:00
}
const allowedImageTypes = new Set([
'image/bmp',
'image/gif',
'image/jpeg',
'image/jpg',
'image/png',
'image/tiff',
'image/webp',
'image/x-icon',
])
2023-05-05 20:05:50 +00:00
const yDocs: Record<string, Doc> = {}
2023-03-29 15:36:12 +00:00
const providers: Record<string, HocuspocusProvider> = {}
2023-03-08 16:35:13 +00:00
2023-07-24 14:09:04 +00:00
export const Editor = (props: Props) => {
2023-03-08 16:35:13 +00:00
const { t } = useLocalize()
2023-11-30 08:07:31 +00:00
const { author } = useSession()
2023-05-11 11:43:14 +00:00
const [isCommonMarkup, setIsCommonMarkup] = createSignal(false)
const [shouldShowTextBubbleMenu, setShouldShowTextBubbleMenu] = createSignal(false)
2023-03-29 08:51:27 +00:00
2024-02-04 17:40:15 +00:00
const { showSnackbar } = useSnackbar()
const docName = `shout-${props.shoutId}`
2023-03-29 08:51:27 +00:00
2023-05-05 20:05:50 +00:00
if (!yDocs[docName]) {
yDocs[docName] = new Y.Doc()
}
2023-03-29 10:14:39 +00:00
if (!providers[docName]) {
2023-03-29 15:36:12 +00:00
providers[docName] = new HocuspocusProvider({
2023-04-11 13:57:48 +00:00
url: 'wss://hocuspocus.discours.io',
2023-03-29 15:36:12 +00:00
name: docName,
document: yDocs[docName],
2023-03-29 15:36:12 +00:00
})
2023-03-29 10:14:39 +00:00
}
2023-03-08 16:35:13 +00:00
const editorElRef: {
current: HTMLDivElement
} = {
current: null,
2023-03-08 16:35:13 +00:00
}
2023-05-04 12:16:39 +00:00
const textBubbleMenuRef: {
current: HTMLDivElement
} = {
current: null,
2023-05-04 12:16:39 +00:00
}
const incutBubbleMenuRef: {
current: HTMLElement
} = {
current: null,
}
const figureBubbleMenuRef: {
current: HTMLElement
} = {
current: null,
}
const blockquoteBubbleMenuRef: {
current: HTMLElement
2023-03-08 16:35:13 +00:00
} = {
current: null,
2023-03-08 16:35:13 +00:00
}
const floatingMenuRef: {
current: HTMLDivElement
} = {
current: null,
2023-03-08 16:35:13 +00:00
}
const handleClipboardPaste = async () => {
try {
const clipboardItems = await navigator.clipboard.read()
if (clipboardItems.length === 0) return
const [clipboardItem] = clipboardItems
const { types } = clipboardItem
const imageType = types.find((type) => allowedImageTypes.has(type))
if (!imageType) return
const blob = await clipboardItem.getType(imageType)
const extension = imageType.split('/')[1]
const file = new File([blob], `clipboardImage.${extension}`)
const uplFile = {
source: blob.toString(),
name: file.name,
size: file.size,
file,
}
showSnackbar({ body: t('Uploading image') })
const result = await handleImageUpload(uplFile)
editor()
.chain()
.focus()
.insertContent({
type: 'figure',
attrs: { 'data-type': 'image' },
content: [
{
type: 'image',
attrs: { src: result.url },
},
{
type: 'figcaption',
content: [{ type: 'text', text: result.originalFilename }],
},
],
})
.run()
} catch (error) {
console.error('[Paste Image Error]:', error)
}
}
const { initialContent } = props
2023-03-08 16:35:13 +00:00
const editor = createTiptapEditor(() => ({
element: editorElRef.current,
2023-07-24 14:09:04 +00:00
editorProps: {
attributes: {
class: 'articleEditor',
},
transformPastedHTML(html) {
return html.replaceAll(/<img.*?>/g, '')
},
handlePaste: () => {
handleClipboardPaste()
return false
},
2023-07-24 14:09:04 +00:00
},
2023-03-08 16:35:13 +00:00
extensions: [
Document,
Text,
Paragraph,
Dropcursor,
CustomBlockquote,
2023-03-08 16:35:13 +00:00
Bold,
Italic,
Span,
ToggleTextWrap,
2023-03-08 16:35:13 +00:00
Strike,
2023-05-04 17:38:50 +00:00
HorizontalRule.configure({
HTMLAttributes: {
class: 'horizontalRule',
},
2023-05-04 17:38:50 +00:00
}),
2023-03-08 16:35:13 +00:00
Underline,
Link.extend({
inclusive: false,
}).configure({
autolink: true,
openOnClick: false,
2023-03-20 09:19:14 +00:00
}),
2023-03-22 07:47:51 +00:00
Heading.configure({
levels: [2, 3, 4],
2023-03-22 07:47:51 +00:00
}),
2023-03-08 16:35:13 +00:00
BulletList,
OrderedList,
ListItem,
2023-03-29 08:51:27 +00:00
Collaboration.configure({
document: yDocs[docName],
2023-03-29 08:51:27 +00:00
}),
2023-03-29 10:14:39 +00:00
CollaborationCursor.configure({
provider: providers[docName],
user: {
2023-11-30 08:07:31 +00:00
name: author().name,
color: uniqolor(author().slug).color,
},
2023-03-29 10:14:39 +00:00
}),
2023-03-08 16:35:13 +00:00
Placeholder.configure({
placeholder: t('Add a link or click plus to embed media'),
2023-03-08 16:35:13 +00:00
}),
Focus,
Gapcursor,
HardBreak,
2023-05-09 17:31:28 +00:00
Highlight.configure({
multicolor: true,
HTMLAttributes: {
class: 'highlight',
},
2023-05-09 17:31:28 +00:00
}),
Image,
Iframe,
Figure,
Figcaption,
Footnote,
ToggleTextWrap,
CharacterCount.configure(), // https://github.com/ueberdosis/tiptap/issues/2589#issuecomment-1093084689
2023-04-20 13:58:56 +00:00
BubbleMenu.configure({
2023-05-04 12:16:39 +00:00
pluginKey: 'textBubbleMenu',
element: textBubbleMenuRef.current,
2023-05-07 13:47:10 +00:00
shouldShow: ({ editor: e, view, state, from, to }) => {
2023-05-04 15:09:09 +00:00
const { doc, selection } = state
const { empty } = selection
const isEmptyTextBlock = doc.textBetween(from, to).length === 0 && isTextSelection(selection)
if (isEmptyTextBlock) {
e.chain().focus().removeTextWrap({ class: 'highlight-fake-selection' }).run()
}
setIsCommonMarkup(e.isActive('figcaption'))
const result =
(view.hasFocus() &&
!empty &&
!isEmptyTextBlock &&
!e.isActive('image') &&
!e.isActive('figure')) ||
e.isActive('footnote') ||
2024-01-18 07:02:37 +00:00
(e.isActive('figcaption') && !empty)
setShouldShowTextBubbleMenu(result)
return result
2023-07-18 11:21:55 +00:00
},
tippyOptions: {
sticky: true,
},
}),
BubbleMenu.configure({
pluginKey: 'blockquoteBubbleMenu',
element: blockquoteBubbleMenuRef.current,
2023-05-29 17:14:58 +00:00
shouldShow: ({ editor: e, state }) => {
const { selection } = state
const { empty } = selection
return empty && e.isActive('blockquote')
2023-09-25 10:16:06 +00:00
},
tippyOptions: {
offset: [0, 0],
placement: 'top',
getReferenceClientRect: () => {
const selectedElement = editor().view.dom.querySelector('.has-focus')
if (selectedElement) {
return selectedElement.getBoundingClientRect()
}
},
},
}),
BubbleMenu.configure({
pluginKey: 'incutBubbleMenu',
element: incutBubbleMenuRef.current,
2023-05-29 17:14:58 +00:00
shouldShow: ({ editor: e, state }) => {
const { selection } = state
const { empty } = selection
return empty && e.isActive('article')
2023-09-25 10:16:06 +00:00
},
tippyOptions: {
offset: [0, -16],
placement: 'top',
getReferenceClientRect: () => {
const selectedElement = editor().view.dom.querySelector('.has-focus')
if (selectedElement) {
return selectedElement.getBoundingClientRect()
}
},
},
2023-05-04 12:16:39 +00:00
}),
BubbleMenu.configure({
pluginKey: 'imageBubbleMenu',
element: figureBubbleMenuRef.current,
2023-05-07 13:47:10 +00:00
shouldShow: ({ editor: e, view }) => {
2023-05-04 15:09:09 +00:00
return view.hasFocus() && e.isActive('image')
},
2023-04-20 13:58:56 +00:00
}),
FloatingMenu.configure({
tippyOptions: {
placement: 'left',
2023-04-20 13:58:56 +00:00
},
element: floatingMenuRef.current,
2023-05-08 17:21:06 +00:00
}),
TrailingNode,
Article,
],
enablePasteRules: [Link],
content: initialContent ?? null,
2023-03-08 16:35:13 +00:00
}))
2024-02-04 17:40:15 +00:00
const { countWords, setEditor } = useEditorContext()
setEditor(editor)
const html = useEditorHTML(() => editor())
createEffect(() => {
props.onChange(html())
if (html()) {
countWords({
characters: editor().storage.characterCount.characters(),
words: editor().storage.characterCount.words(),
})
}
})
onCleanup(() => {
2024-01-25 19:16:38 +00:00
editor()?.destroy()
})
2023-03-08 16:35:13 +00:00
return (
<>
2023-08-23 22:31:39 +00:00
<div class="row">
<div class="col-md-5" />
2023-08-23 22:31:39 +00:00
<div class="col-md-12">
<div ref={(el) => (editorElRef.current = el)} id="editorBody" />
</div>
</div>
2023-05-11 11:43:14 +00:00
<TextBubbleMenu
shouldShow={shouldShowTextBubbleMenu()}
2023-05-11 11:43:14 +00:00
isCommonMarkup={isCommonMarkup()}
editor={editor()}
ref={(el) => (textBubbleMenuRef.current = el)}
/>
<BlockquoteBubbleMenu
ref={(el) => {
blockquoteBubbleMenuRef.current = el
}}
editor={editor()}
/>
<FigureBubbleMenu
editor={editor()}
ref={(el) => {
figureBubbleMenuRef.current = el
}}
/>
<IncutBubbleMenu
editor={editor()}
ref={(el) => {
incutBubbleMenuRef.current = el
}}
/>
2023-03-08 16:35:13 +00:00
<EditorFloatingMenu editor={editor()} ref={(el) => (floatingMenuRef.current = el)} />
</>
2023-03-08 16:35:13 +00:00
)
}