/
rich-text-image.ts
211 lines (185 loc) · 6.76 KB
/
rich-text-image.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { Image } from '@tiptap/extension-image'
import { Plugin, PluginKey, Selection } from '@tiptap/pm/state'
import { ReactNodeViewRenderer } from '@tiptap/react'
import type { NodeViewProps } from '@tiptap/react'
/**
* The properties that describe `RichTextImage` node attributes.
*/
type RichTextImageAttributes = {
/**
* Additional metadata about an image attachment upload.
*/
metadata?: {
/**
* A unique ID for the image attachment.
*/
attachmentId: string
/**
* Specifies if the image attachment failed to upload.
*/
isUploadFailed: boolean
/**
* The upload progress for the image attachment.
*/
uploadProgress: number
}
} & Pick<HTMLImageElement, 'src'> &
Pick<Partial<HTMLImageElement>, 'alt' | 'title'>
/**
* Augment the official `@tiptap/core` module with extra commands, relevant for this extension, so
* that the compiler knows about them.
*/
declare module '@tiptap/core' {
interface Commands<ReturnType> {
richTextImage: {
/**
* Inserts an image into the editor with the given attributes.
*/
insertImage: (attributes: RichTextImageAttributes) => ReturnType
/**
* Updates the attributes for an existing image in the editor.
*/
updateImage: (
attributes: Partial<RichTextImageAttributes> &
Required<Pick<RichTextImageAttributes, 'metadata'>>,
) => ReturnType
}
}
}
/**
* The options available to customize the `RichTextImage` extension.
*/
type RichTextImageOptions = {
/**
* A list of accepted MIME types for images pasting.
*/
acceptedImageMimeTypes: string[]
/**
* Renders the image node inline (e.g., <p><img src="doist.jpg"></p>). By default images are on
* the same level as paragraphs.
*/
inline: boolean
/**
* Custom HTML attributes that should be added to the rendered HTML tag.
*/
HTMLAttributes: Record<string, string>
/**
* A React component to render inside the interactive node view.
*/
NodeViewComponent?: React.ComponentType<NodeViewProps>
/**
* The event handler that is fired when an image file is pasted.
*/
onImageFilePaste?: (file: File) => void
}
/**
* Custom extension that extends the built-in `Image` extension to add support for image pasting,
* and also adds the ability to pass aditional metadata about an image attachment upload.
*/
const RichTextImage = Image.extend<RichTextImageOptions>({
draggable: true,
addOptions() {
return {
...this.parent?.(),
acceptedImageMimeTypes: ['image/gif', 'image/jpeg', 'image/jpg', 'image/png'],
NodeViewComponent: undefined,
}
},
addAttributes() {
return {
...this.parent?.(),
metadata: {
default: undefined,
rendered: false,
},
}
},
addCommands() {
const { name: nodeTypeName } = this
return {
...this.parent?.(),
insertImage(attributes) {
return ({ editor, commands }) => {
const selectionAtEnd = Selection.atEnd(editor.state.doc)
return commands.insertContent([
{
type: nodeTypeName,
attrs: attributes,
},
// Insert a blank paragraph after the image when at the end of the document
...(editor.state.selection.to === selectionAtEnd.to
? [{ type: 'paragraph' }]
: []),
])
}
},
updateImage(attributes) {
return ({ commands }) => {
return commands.command(({ tr }) => {
tr.doc.descendants((node, position) => {
const { metadata } = node.attrs as {
metadata: RichTextImageAttributes['metadata']
}
// Update the image attributes to the corresponding node
if (
node.type.name === nodeTypeName &&
metadata?.attachmentId === attributes.metadata?.attachmentId
) {
tr.setNodeMarkup(position, node.type, {
...node.attrs,
...attributes,
})
}
})
return true
})
}
},
}
},
addNodeView() {
const { NodeViewComponent } = this.options
// Do not add a node view if component was not specified
if (!NodeViewComponent) {
return () => ({})
}
// Render the node view with the provided React component
return ReactNodeViewRenderer(NodeViewComponent, {
as: 'div',
className: `Typist-${this.type.name}`,
})
},
addProseMirrorPlugins() {
const { acceptedImageMimeTypes, onImageFilePaste } = this.options
return [
new Plugin({
key: new PluginKey(this.name),
props: {
handlePaste(_, event) {
// Do not handle the event if we don't have a callback
if (!onImageFilePaste) {
return false
}
const pastedFiles = Array.from(event.clipboardData?.files || [])
// Do not handle the event if no files were pasted
if (pastedFiles.length === 0) {
return false
}
let wasPasteHandled = false
// Invoke the callback for every pasted file that is an accepted image type
pastedFiles.forEach((pastedFile) => {
if (acceptedImageMimeTypes.includes(pastedFile.type)) {
onImageFilePaste(pastedFile)
wasPasteHandled = true
}
})
// Suppress the default handling behaviour if at least one image was handled
return wasPasteHandled
},
},
}),
]
},
})
export { RichTextImage }
export type { RichTextImageAttributes, RichTextImageOptions }