File size: 10,870 Bytes
2daf8de | 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | import { act, render } from '@testing-library/react'
import { Editor, Node } from '@tiptap/core'
import Document from '@tiptap/extension-document'
import Paragraph from '@tiptap/extension-paragraph'
import Text from '@tiptap/extension-text'
import React, { useEffect, useState } from 'react'
import { afterEach, describe, expect, it } from 'vitest'
import { EditorContent } from './EditorContent.js'
import { NodeViewContent } from './NodeViewContent.js'
import { NodeViewWrapper } from './NodeViewWrapper.js'
import { ReactNodeViewRenderer } from './ReactNodeViewRenderer.js'
import type { ReactNodeViewProps } from './types.js'
const renderedPositions: Array<number | undefined> = []
const renderErrors: unknown[] = []
const bumpHandles = new Map<string, () => void>()
const explodingIds = new Set<string>()
// Optional hook run inside the click handler before the replace commands.
let beforeReplace: (() => void) | undefined
const ContainerComponent = (props: ReactNodeViewProps) => {
const [, setTick] = useState(0)
const id = props.node.attrs.id as string
useEffect(() => {
bumpHandles.set(id, () => setTick(tick => tick + 1))
setTick(tick => tick + 1)
return () => {
bumpHandles.delete(id)
}
}, [id])
if (explodingIds.has(id)) {
throw new Error(`render bomb in container ${id}`)
}
// Calling getPos in the render path is what crashes with React 19.
try {
renderedPositions.push(props.getPos())
} catch (error) {
renderErrors.push(error)
throw error
}
const replaceSelf = () => {
beforeReplace?.()
// setState first so React has pending sync work when the
// transactions below run.
setTick(tick => tick + 1)
const pos = props.getPos()
if (typeof pos !== 'number') {
return
}
// The first transaction destroys this node view while its component is
// still mounted. The second one constructs a new node view, whose
// ReactRenderer flushSync then re-renders pending components while
// ProseMirror's view tree is mid-update.
props.editor.commands.deleteRange({ from: pos, to: pos + props.node.nodeSize })
props.editor.commands.insertContentAt(0, {
type: 'container',
attrs: { id: 'fresh' },
content: [{ type: 'item', content: [{ type: 'paragraph' }] }],
})
}
return React.createElement(
NodeViewWrapper,
null,
React.createElement('button', {
type: 'button',
'data-testid': `replace-${id}`,
onClick: replaceSelf,
}),
React.createElement(NodeViewContent),
)
}
const ItemComponent = () => {
return React.createElement(NodeViewWrapper, null, React.createElement(NodeViewContent))
}
const WidgetComponent = () => {
return React.createElement(NodeViewWrapper, null)
}
const ReactParagraphComponent = () => {
return React.createElement(NodeViewWrapper, null, React.createElement(NodeViewContent))
}
const ReactParagraph = Paragraph.extend({
addNodeView() {
return ReactNodeViewRenderer(ReactParagraphComponent)
},
})
const Container = Node.create({
name: 'container',
group: 'block',
content: 'item+',
addAttributes() {
return {
id: { default: null },
}
},
parseHTML() {
return [{ tag: 'div[data-type="container"]' }]
},
renderHTML() {
return ['div', { 'data-type': 'container' }, 0]
},
addNodeView() {
return ReactNodeViewRenderer(ContainerComponent)
},
})
const Item = Node.create({
name: 'item',
group: 'block',
content: 'paragraph+',
parseHTML() {
return [{ tag: 'div[data-type="item"]' }]
},
renderHTML() {
return ['div', { 'data-type': 'item' }, 0]
},
addNodeView() {
return ReactNodeViewRenderer(ItemComponent)
},
})
const Widget = Node.create({
name: 'widget',
group: 'block',
atom: true,
parseHTML() {
return [{ tag: 'div[data-type="widget"]' }]
},
renderHTML() {
return ['div', { 'data-type': 'widget' }]
},
addNodeView() {
return ReactNodeViewRenderer(WidgetComponent)
},
})
const createEditorWithContainers = () => {
return new Editor({
extensions: [Document, Paragraph, Text, Container, Item],
content:
'<div data-type="container" id="a"><div data-type="item"><p>first</p></div></div>' +
'<div data-type="container" id="b"><div data-type="item"><p>second</p></div></div>',
})
}
const createEditorWithReactParagraph = () => {
return new Editor({
extensions: [Document, ReactParagraph, Text],
content: '<p>Hello</p>',
})
}
const createEditorWithWidget = () => {
return new Editor({
extensions: [Document, Paragraph, Text, Widget],
content: '<p>abc</p><div data-type="widget"></div>',
})
}
const flushMicrotasks = async () => {
await act(async () => {
await Promise.resolve()
})
}
const flushAnimationFrame = async () => {
await act(async () => {
await new Promise<void>(resolve => {
requestAnimationFrame(() => resolve())
})
})
}
const clickReplace = (id: string) => {
document
.querySelector(`[data-testid="replace-${id}"]`)!
.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }))
}
describe('ReactNodeViewRenderer', () => {
afterEach(() => {
renderedPositions.length = 0
renderErrors.length = 0
bumpHandles.clear()
explodingIds.clear()
beforeReplace = undefined
document.body.innerHTML = ''
})
it('renders nested node views and resolves getPos during render', async () => {
const editor = createEditorWithContainers()
const { container } = render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
expect(container.querySelector('[data-node-view-wrapper]')).not.toBeNull()
expect(renderedPositions.length).toBeGreaterThan(0)
expect(renderedPositions).toContain(0)
editor.destroy()
})
it('keeps new React paragraph content connected while its portal is queued', async () => {
const editor = createEditorWithReactParagraph()
const { container } = render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
editor.commands.setTextSelection(6)
editor.commands.splitBlock()
const secondParagraphPosition = editor.state.doc.firstChild!.nodeSize
expect(editor.state.selection.from).toBe(secondParagraphPosition + 1)
const contentElements = container.querySelectorAll('[data-node-view-content-react]')
expect(contentElements).toHaveLength(2)
expect(contentElements[1].isConnected).toBe(true)
editor.commands.insertContent('Second')
expect(editor.state.doc.child(0).textContent).toBe('Hello')
expect(editor.state.doc.child(1).textContent).toBe('Second')
await flushMicrotasks()
expect(contentElements[1].parentElement?.hasAttribute('data-node-view-content')).toBe(true)
editor.destroy()
})
it('resolves getPos to undefined while the view desc is detached mid-update', async () => {
const editor = createEditorWithContainers()
const { container } = render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
// Recreate the state ProseMirror's view tree goes through while it
// updates: the desc has a parent but is not in parent.children yet.
// getPos then walks past the end of the children array and throws.
const desc = (container.querySelector('.react-renderer') as any).pmViewDesc
const siblings = desc.parent.children
siblings.splice(siblings.indexOf(desc), 1)
renderedPositions.length = 0
await act(async () => {
bumpHandles.get('a')?.()
})
// put the tree back so teardown works on a consistent view
siblings.unshift(desc)
expect(renderErrors).toEqual([])
expect(renderedPositions).toEqual([undefined])
editor.destroy()
})
it('does not select the node view when the selection covers its former position', async () => {
const editor = createEditorWithWidget()
const { container } = render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
// The widget starts at position 5 and moves to 8 when text is typed above it.
editor.commands.insertContentAt(4, 'def')
editor.commands.setTextSelection({ from: 5, to: 6 })
await flushAnimationFrame()
const widget = container.querySelector('.node-widget')!
expect(widget.classList.contains('ProseMirror-selectednode')).toBe(false)
editor.destroy()
})
it('selects the node view when it is selected at its new position', async () => {
const editor = createEditorWithWidget()
const { container } = render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
editor.commands.insertContentAt(4, 'def')
editor.commands.setNodeSelection(8)
await flushAnimationFrame()
const widget = container.querySelector('.node-widget')!
expect(widget.classList.contains('ProseMirror-selectednode')).toBe(true)
editor.destroy()
})
it('does not crash when node views are created while React has pending updates', async () => {
const editor = createEditorWithContainers()
const { container } = render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
expect(() => clickReplace('b')).not.toThrow()
await flushMicrotasks()
// getPos must not blow up inside the synchronous React flush.
expect(renderErrors).toEqual([])
// The editor and the React tree must stay intact and usable.
expect(editor.state.doc.firstChild?.attrs.id).toBe('fresh')
expect(container.querySelector('.tiptap')).not.toBeNull()
expect(
editor.commands.insertContentAt(editor.state.doc.content.size, { type: 'paragraph' }),
).toBe(true)
editor.destroy()
})
it('keeps the editor intact when a component throws during the synchronous flush', async () => {
const editor = createEditorWithContainers()
render(React.createElement(EditorContent, { editor }))
await flushMicrotasks()
// Make container "a" throw on its next render and give it a pending
// update, so the new node view's flushSync renders it mid-transaction.
beforeReplace = () => {
explodingIds.add('a')
bumpHandles.get('a')?.()
}
let clickError: unknown
try {
clickReplace('b')
} catch (error) {
clickError = error
}
await flushMicrotasks()
// React 19 reports the render error via onUncaughtError instead of
// rethrowing, so nothing may propagate into the ProseMirror transaction.
expect(clickError).toBeUndefined()
// The ProseMirror transaction must complete even though a component
// render threw during the flush.
expect(editor.state.doc.firstChild?.attrs.id).toBe('fresh')
expect(
editor.commands.insertContentAt(editor.state.doc.content.size, { type: 'paragraph' }),
).toBe(true)
editor.destroy()
})
})
|