@pie-lib/editable-html-tip-tap 2.2.0-beta.8 → 2.2.0-beta.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/EditableHtml.test.jsx +0 -588
  3. package/src/__tests__/constants.test.js +0 -19
  4. package/src/__tests__/div-to-paragraph-conversion.test.jsx +0 -125
  5. package/src/__tests__/extensions.test.js +0 -208
  6. package/src/__tests__/index.test.jsx +0 -154
  7. package/src/__tests__/size-utils.test.js +0 -64
  8. package/src/__tests__/theme.test.js +0 -17
  9. package/src/components/__tests__/AltDialog.test.jsx +0 -147
  10. package/src/components/__tests__/CharacterPicker.test.jsx +0 -270
  11. package/src/components/__tests__/CssIcon.test.jsx +0 -46
  12. package/src/components/__tests__/DragInTheBlank.test.jsx +0 -255
  13. package/src/components/__tests__/ExplicitConstructedResponse.test.jsx +0 -209
  14. package/src/components/__tests__/ImageToolbar.test.jsx +0 -128
  15. package/src/components/__tests__/InlineDropdown.test.jsx +0 -557
  16. package/src/components/__tests__/InsertImageHandler.test.js +0 -161
  17. package/src/components/__tests__/MediaDialog.test.jsx +0 -293
  18. package/src/components/__tests__/MediaToolbar.test.jsx +0 -74
  19. package/src/components/__tests__/MediaWrapper.test.jsx +0 -81
  20. package/src/components/__tests__/MenuBar.test.jsx +0 -250
  21. package/src/components/__tests__/RespArea.test.jsx +0 -122
  22. package/src/components/__tests__/TableIcons.test.jsx +0 -149
  23. package/src/components/__tests__/TextAlign.test.jsx +0 -167
  24. package/src/components/__tests__/TiptapContainer.test.jsx +0 -138
  25. package/src/components/__tests__/characterUtils.test.js +0 -166
  26. package/src/components/__tests__/choice.test.jsx +0 -171
  27. package/src/components/__tests__/custom-popper.test.jsx +0 -82
  28. package/src/components/__tests__/done-button.test.jsx +0 -54
  29. package/src/components/__tests__/toolbar-buttons.test.jsx +0 -234
  30. package/src/components/respArea/DragInTheBlank/__tests__/choice.test.jsx +0 -72
  31. package/src/components/respArea/__tests__/MathTemplated.test.jsx +0 -210
  32. package/src/extensions/__tests__/css.test.js +0 -196
  33. package/src/extensions/__tests__/custom-toolbar-wrapper.test.jsx +0 -180
  34. package/src/extensions/__tests__/divNode.test.js +0 -87
  35. package/src/extensions/__tests__/ensure-empty-root-div.test.js +0 -57
  36. package/src/extensions/__tests__/ensure-list-item-content-is-div.test.js +0 -44
  37. package/src/extensions/__tests__/extended-list-item.test.js +0 -13
  38. package/src/extensions/__tests__/extended-table-cell.test.js +0 -22
  39. package/src/extensions/__tests__/extended-table.test.js +0 -183
  40. package/src/extensions/__tests__/image-component.test.jsx +0 -346
  41. package/src/extensions/__tests__/image.test.js +0 -237
  42. package/src/extensions/__tests__/math.test.js +0 -900
  43. package/src/extensions/__tests__/media-node-view.test.jsx +0 -298
  44. package/src/extensions/__tests__/media.test.js +0 -271
  45. package/src/extensions/__tests__/responseArea.test.js +0 -655
  46. package/src/utils/__tests__/helper.test.js +0 -126
  47. package/src/utils/__tests__/toolbar.test.js +0 -43
@@ -1,900 +0,0 @@
1
- import React from 'react';
2
- import { render, waitFor, fireEvent, act } from '@testing-library/react';
3
- import { EnsureTextAfterMathPlugin, MathNode, MathNodeView, ZeroWidthSpaceHandlingPlugin } from '../math';
4
- import * as toolbarUtils from '../../utils/toolbar';
5
-
6
- jest.mock('@tiptap/react', () => ({
7
- NodeViewWrapper: ({ children, ...props }) => (
8
- <div data-testid="node-view-wrapper" {...props}>
9
- {children}
10
- </div>
11
- ),
12
- ReactNodeViewRenderer: jest.fn((component) => component),
13
- }));
14
-
15
- const mockCreatePortal = jest.fn((node) => node);
16
- jest.mock('react-dom', () => ({
17
- ...jest.requireActual('react-dom'),
18
- createPortal: (...args) => mockCreatePortal(...args),
19
- }));
20
-
21
- jest.mock('@pie-lib/math-toolbar', () => {
22
- const React = require('react');
23
- return {
24
- MathPreview: ({ latex }) => <div data-testid="math-preview">{latex}</div>,
25
- MathToolbar: ({ latex, onChange, onDone }) => {
26
- const [localLatex, setLocalLatex] = React.useState(latex);
27
- return (
28
- <div data-testid="math-toolbar">
29
- <input
30
- data-testid="math-input"
31
- value={localLatex}
32
- onChange={(e) => {
33
- setLocalLatex(e.target.value);
34
- onChange(e.target.value);
35
- }}
36
- />
37
- <button data-testid="done-button" onClick={() => onDone(localLatex)}>
38
- Done
39
- </button>
40
- </div>
41
- );
42
- },
43
- };
44
- });
45
-
46
- jest.mock('@pie-lib/math-rendering', () => ({
47
- wrapMath: (latex, wrapper) => latex,
48
- }));
49
-
50
- jest.mock('@tiptap/core', () => ({
51
- Node: {
52
- create: jest.fn((config) => config),
53
- },
54
- }));
55
-
56
- jest.mock('prosemirror-state', () => ({
57
- Plugin: jest.fn(function (config) {
58
- return config;
59
- }),
60
- PluginKey: jest.fn(function (key) {
61
- this.key = key;
62
- }),
63
- TextSelection: {
64
- create: jest.fn((doc, pos) => ({ type: 'text', pos })),
65
- },
66
- NodeSelection: {
67
- create: jest.fn((doc, pos) => ({ type: 'node', pos })),
68
- },
69
- }));
70
-
71
- describe('MathNode', () => {
72
- describe('configuration', () => {
73
- it('has correct name', () => {
74
- expect(MathNode.name).toBe('math');
75
- });
76
-
77
- it('is inline', () => {
78
- expect(MathNode.inline).toBe(true);
79
- });
80
-
81
- it('is in inline group', () => {
82
- expect(MathNode.group).toBe('inline');
83
- });
84
-
85
- it('is atomic', () => {
86
- expect(MathNode.atom).toBe(true);
87
- });
88
- });
89
-
90
- describe('addAttributes', () => {
91
- it('returns required attributes', () => {
92
- const attributes = MathNode.addAttributes();
93
-
94
- expect(attributes).toHaveProperty('latex');
95
- expect(attributes).toHaveProperty('wrapper');
96
- expect(attributes).toHaveProperty('html');
97
-
98
- expect(attributes.latex).toEqual({ default: '' });
99
- expect(attributes.wrapper).toEqual({ default: null });
100
- expect(attributes.html).toEqual({ default: null });
101
- });
102
- });
103
-
104
- describe('parseHTML', () => {
105
- it('returns parsing rules for latex', () => {
106
- const rules = MathNode.parseHTML();
107
-
108
- expect(Array.isArray(rules)).toBe(true);
109
- expect(rules).toHaveLength(2);
110
- expect(rules[0]).toHaveProperty('tag', 'span[data-latex]');
111
- });
112
-
113
- it('returns parsing rules for mathml', () => {
114
- const rules = MathNode.parseHTML();
115
- expect(rules[1]).toHaveProperty('tag', 'span[data-type="mathml"]');
116
- });
117
- });
118
-
119
- describe('renderHTML', () => {
120
- it('renders mathml when html attribute is present', () => {
121
- const result = MathNode.renderHTML({
122
- HTMLAttributes: {
123
- html: '<math><mi>x</mi></math>',
124
- },
125
- });
126
-
127
- expect(result[0]).toBe('span');
128
- expect(result[1]).toHaveProperty('data-type', 'mathml');
129
- });
130
-
131
- it('renders latex when html attribute is not present', () => {
132
- const result = MathNode.renderHTML({
133
- HTMLAttributes: {
134
- latex: 'x^2',
135
- },
136
- });
137
-
138
- expect(result[0]).toBe('span');
139
- expect(result[1]).toHaveProperty('data-latex', '');
140
- expect(result[1]).toHaveProperty('data-raw', 'x^2');
141
- });
142
- });
143
-
144
- describe('addCommands', () => {
145
- it('returns insertMath command', () => {
146
- const commands = MathNode.addCommands();
147
-
148
- expect(commands).toHaveProperty('insertMath');
149
- expect(typeof commands.insertMath).toBe('function');
150
- });
151
-
152
- it('insertMath opens the toolbar after inserting a math node', () => {
153
- const setToolbarOpenedSpy = jest.spyOn(toolbarUtils, 'setToolbarOpened');
154
- const mathNode = { type: { name: 'math' }, nodeSize: 1 };
155
- const tr = {
156
- insert: jest.fn().mockReturnThis(),
157
- setSelection: jest.fn().mockReturnThis(),
158
- doc: {},
159
- };
160
- const editor = {
161
- view: {
162
- state: {
163
- schema: { nodes: { math: { create: jest.fn(() => mathNode) } } },
164
- selection: { $from: { pos: 1 } },
165
- },
166
- },
167
- };
168
- const dispatch = jest.fn();
169
- const insertMath = MathNode.addCommands().insertMath('x^2');
170
-
171
- insertMath({ tr, editor, dispatch });
172
-
173
- expect(tr.insert).toHaveBeenCalledWith(1, mathNode);
174
- expect(tr.setSelection).toHaveBeenCalled();
175
- expect(dispatch).toHaveBeenCalledWith(tr);
176
- expect(setToolbarOpenedSpy).toHaveBeenCalledWith(editor, true);
177
-
178
- setToolbarOpenedSpy.mockRestore();
179
- });
180
- });
181
-
182
- describe('addNodeView', () => {
183
- it('returns ReactNodeViewRenderer result', () => {
184
- const result = MathNode.addNodeView();
185
-
186
- expect(result).toBeDefined();
187
- });
188
- });
189
-
190
- describe('addProseMirrorPlugins', () => {
191
- it('registers ensure-text-after-math and zero-width-space plugins', () => {
192
- const plugins = MathNode.addProseMirrorPlugins();
193
-
194
- expect(plugins).toHaveLength(2);
195
- expect(plugins[0].appendTransaction).toBeDefined();
196
- expect(plugins[1].props.handleKeyDown).toBeDefined();
197
- });
198
- });
199
- });
200
-
201
- describe('EnsureTextAfterMathPlugin', () => {
202
- it('inserts a zero-width space after a math node when no text follows', () => {
203
- const plugin = EnsureTextAfterMathPlugin('math');
204
- const textNode = { type: { name: 'text' } };
205
- const mathNode = { type: { name: 'math' }, nodeSize: 3 };
206
- const tr = { insert: jest.fn() };
207
-
208
- const newState = {
209
- schema: { text: jest.fn((value) => ({ type: textNode.type, text: value })) },
210
- tr,
211
- doc: {
212
- descendants: (cb) => cb(mathNode, 5),
213
- nodeAt: jest.fn(() => null),
214
- },
215
- };
216
-
217
- const result = plugin.appendTransaction([{ docChanged: true }], {}, newState);
218
-
219
- expect(tr.insert).toHaveBeenCalledWith(8, expect.anything());
220
- expect(result).toBe(tr);
221
- });
222
-
223
- it('does not insert when text already follows the math node', () => {
224
- const plugin = EnsureTextAfterMathPlugin('math');
225
- const tr = { insert: jest.fn() };
226
- const mathNode = { type: { name: 'math' }, nodeSize: 3 };
227
-
228
- const newState = {
229
- schema: { text: jest.fn() },
230
- tr,
231
- doc: {
232
- descendants: (cb) => cb(mathNode, 5),
233
- nodeAt: jest.fn(() => ({ type: { name: 'text' } })),
234
- },
235
- };
236
-
237
- const result = plugin.appendTransaction([{ docChanged: true }], {}, newState);
238
-
239
- expect(tr.insert).not.toHaveBeenCalled();
240
- expect(result).toBeNull();
241
- });
242
-
243
- it('returns null when the document did not change', () => {
244
- const plugin = EnsureTextAfterMathPlugin('math');
245
-
246
- const result = plugin.appendTransaction([{ docChanged: false }], {}, {});
247
- expect(result).toBeNull();
248
- });
249
- });
250
-
251
- describe('ZeroWidthSpaceHandlingPlugin', () => {
252
- const createDocWithMathAndZwsp = (resolveOverrides = {}) => ({
253
- resolve: jest.fn((pos) => ({
254
- nodeAfter: null,
255
- nodeBefore: null,
256
- pos,
257
- ...resolveOverrides[pos],
258
- })),
259
- nodeAt: jest.fn((pos) => {
260
- if (pos === 1) {
261
- return { type: { name: 'text' }, textContent: '\u200b' };
262
- }
263
- if (pos === 0) {
264
- return { type: { name: 'math' }, nodeSize: 1 };
265
- }
266
- return null;
267
- }),
268
- });
269
-
270
- const createDocWithRegularTextBeforeCursor = () => ({
271
- resolve: jest.fn((pos) => ({ nodeAfter: null, nodeBefore: null, pos })),
272
- nodeAt: jest.fn((pos) => {
273
- if (pos === 1) {
274
- return { type: { name: 'text' }, textContent: 'a' };
275
- }
276
- return null;
277
- }),
278
- });
279
-
280
- const createView = ({ state: stateOverrides = {} } = {}) => {
281
- const dispatch = jest.fn();
282
- const tr = {
283
- delete: jest.fn().mockReturnThis(),
284
- setSelection: jest.fn().mockReturnThis(),
285
- };
286
-
287
- return {
288
- state: {
289
- selection: { from: 2, empty: true },
290
- doc: createDocWithMathAndZwsp(),
291
- tr,
292
- ...stateOverrides,
293
- },
294
- dispatch,
295
- };
296
- };
297
-
298
- describe('Backspace', () => {
299
- it('deletes the inline node and zero-width space before the cursor', () => {
300
- const view = createView();
301
- const handled = ZeroWidthSpaceHandlingPlugin.props.handleKeyDown(view, { key: 'Backspace' });
302
-
303
- expect(handled).toBe(true);
304
- expect(view.state.tr.delete).toHaveBeenCalledWith(0, 2);
305
- expect(view.dispatch).toHaveBeenCalledWith(view.state.tr);
306
- });
307
-
308
- it('returns false when regular text precedes the cursor', () => {
309
- const view = createView({
310
- state: {
311
- doc: createDocWithRegularTextBeforeCursor(),
312
- },
313
- });
314
-
315
- const handled = ZeroWidthSpaceHandlingPlugin.props.handleKeyDown(view, { key: 'Backspace' });
316
-
317
- expect(handled).toBe(false);
318
- expect(view.state.tr.delete).not.toHaveBeenCalled();
319
- expect(view.dispatch).not.toHaveBeenCalled();
320
- });
321
- });
322
-
323
- describe('ArrowLeft', () => {
324
- it('selects the inline node before a zero-width space', () => {
325
- const mathNode = { nodeSize: 3 };
326
- const view = createView({
327
- state: {
328
- doc: createDocWithMathAndZwsp({
329
- 0: { nodeAfter: mathNode, nodeBefore: null, pos: 0 },
330
- }),
331
- },
332
- });
333
- const { NodeSelection } = require('prosemirror-state');
334
-
335
- const handled = ZeroWidthSpaceHandlingPlugin.props.handleKeyDown(view, { key: 'ArrowLeft' });
336
-
337
- expect(handled).toBe(true);
338
- expect(view.state.doc.resolve).toHaveBeenCalledWith(0);
339
- expect(NodeSelection.create).toHaveBeenCalledWith(view.state.doc, 0);
340
- expect(view.dispatch).toHaveBeenCalled();
341
- });
342
-
343
- it('moves the text cursor before the zero-width space when no inline node precedes it', () => {
344
- const view = createView();
345
- const { TextSelection } = require('prosemirror-state');
346
-
347
- const handled = ZeroWidthSpaceHandlingPlugin.props.handleKeyDown(view, { key: 'ArrowLeft' });
348
-
349
- expect(handled).toBe(true);
350
- expect(view.state.doc.resolve).toHaveBeenCalledWith(0);
351
- expect(TextSelection.create).toHaveBeenCalledWith(view.state.doc, 0);
352
- expect(view.dispatch).toHaveBeenCalled();
353
- });
354
-
355
- it('returns false when regular text precedes the cursor', () => {
356
- const view = createView({
357
- state: {
358
- doc: createDocWithRegularTextBeforeCursor(),
359
- },
360
- });
361
-
362
- const handled = ZeroWidthSpaceHandlingPlugin.props.handleKeyDown(view, { key: 'ArrowLeft' });
363
-
364
- expect(handled).toBe(false);
365
- expect(view.state.tr.setSelection).not.toHaveBeenCalled();
366
- expect(view.dispatch).not.toHaveBeenCalled();
367
- });
368
- });
369
-
370
- it('returns false for unrelated keys', () => {
371
- const view = createView();
372
-
373
- const handled = ZeroWidthSpaceHandlingPlugin.props.handleKeyDown(view, { key: 'Enter' });
374
- expect(handled).toBe(false);
375
- });
376
- });
377
-
378
- describe('MathNodeView', () => {
379
- const createEditorElement = (rect = { top: 0, left: 0, width: 600, height: 400 }) => {
380
- const element = document.createElement('div');
381
- Object.defineProperty(element, 'getBoundingClientRect', {
382
- value: jest.fn(() => rect),
383
- configurable: true,
384
- });
385
- return element;
386
- };
387
-
388
- const createMockEditor = () => ({
389
- state: {
390
- selection: {
391
- from: 0,
392
- to: 1,
393
- node: { type: { name: 'math' } },
394
- },
395
- tr: {
396
- setSelection: jest.fn().mockReturnThis(),
397
- setMeta: jest.fn().mockReturnThis(),
398
- },
399
- doc: {},
400
- },
401
- view: {
402
- coordsAtPos: jest.fn(() => ({ top: 100, left: 50 })),
403
- dispatch: jest.fn(),
404
- },
405
- options: {
406
- element: createEditorElement(),
407
- },
408
- commands: {
409
- focus: jest.fn(),
410
- },
411
- instanceId: 'editor-123',
412
- _toolbarOpened: false,
413
- });
414
-
415
- const mockNode = {
416
- attrs: {
417
- latex: 'x^2',
418
- },
419
- nodeSize: 1,
420
- };
421
-
422
- let defaultProps;
423
-
424
- beforeEach(() => {
425
- jest.clearAllMocks();
426
- mockCreatePortal.mockImplementation((node) => node);
427
- defaultProps = {
428
- node: mockNode,
429
- updateAttributes: jest.fn(),
430
- editor: createMockEditor(),
431
- selected: false,
432
- options: {},
433
- getPos: jest.fn(() => 0),
434
- };
435
- });
436
-
437
- it('renders without crashing', () => {
438
- const { container } = render(<MathNodeView {...defaultProps} />);
439
- expect(container).toBeInTheDocument();
440
- });
441
-
442
- it('renders NodeViewWrapper', () => {
443
- const { getByTestId } = render(<MathNodeView {...defaultProps} />);
444
- expect(getByTestId('node-view-wrapper')).toBeInTheDocument();
445
- });
446
-
447
- it('displays math preview', () => {
448
- const { getByTestId } = render(<MathNodeView {...defaultProps} />);
449
- expect(getByTestId('math-preview')).toBeInTheDocument();
450
- });
451
-
452
- it('shows toolbar when selected', async () => {
453
- const { getByTestId } = render(<MathNodeView {...defaultProps} selected={true} />);
454
- await waitFor(() => {
455
- expect(getByTestId('math-toolbar')).toBeInTheDocument();
456
- });
457
- });
458
-
459
- it('does not show toolbar when not selected', () => {
460
- const { queryByTestId } = render(<MathNodeView {...defaultProps} selected={false} />);
461
- expect(queryByTestId('math-toolbar')).not.toBeInTheDocument();
462
- });
463
-
464
- it('adds data-toolbar-for attribute with editor instanceId', async () => {
465
- const { container } = render(<MathNodeView {...defaultProps} selected={true} />);
466
- await waitFor(() => {
467
- const toolbar = container.querySelector('[data-toolbar-for]');
468
- expect(toolbar).toHaveAttribute('data-toolbar-for', 'editor-123');
469
- });
470
- });
471
-
472
- describe('toolbar positioning', () => {
473
- it('positions relative to portal container using coordsAtPos', async () => {
474
- const { container } = render(<MathNodeView {...defaultProps} selected={true} />);
475
- await waitFor(() => {
476
- const toolbar = container.querySelector('[data-toolbar-for]');
477
- expect(toolbar).toBeInTheDocument();
478
- expect(toolbar.style.top).toBe('100px');
479
- expect(toolbar.style.left).toBe('50px');
480
- });
481
- });
482
-
483
- it('offsets position by portal container getBoundingClientRect', async () => {
484
- const containerEl = document.createElement('div');
485
- containerEl.getBoundingClientRect = jest.fn(() => ({ top: 100, left: 50, width: 600, height: 400 }));
486
-
487
- const editor = {
488
- ...defaultProps.editor,
489
- _tiptapContainerEl: containerEl,
490
- };
491
-
492
- const { container } = render(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
493
- await waitFor(() => {
494
- const toolbar = container.querySelector('[data-toolbar-for]');
495
- expect(toolbar).toBeInTheDocument();
496
- expect(toolbar.style.top).toBe('0px');
497
- expect(toolbar.style.left).toBe('0px');
498
- });
499
- });
500
-
501
- it('applies absolute positioning style to toolbar', async () => {
502
- const { container } = render(<MathNodeView {...defaultProps} selected={true} />);
503
- await waitFor(() => {
504
- const toolbar = container.querySelector('[data-toolbar-for]');
505
- expect(toolbar).toBeInTheDocument();
506
- expect(toolbar.style.position).toBe('absolute');
507
- });
508
- });
509
-
510
- it('renders above other editor overlays with a high z-index', async () => {
511
- const { container } = render(<MathNodeView {...defaultProps} selected={true} />);
512
- await waitFor(() => {
513
- const toolbar = container.querySelector('[data-toolbar-for]');
514
- expect(toolbar).toBeInTheDocument();
515
- expect(toolbar.style.zIndex).toBe('1000');
516
- });
517
- });
518
-
519
- it('updates position from coordsAtPos when selection changes', async () => {
520
- const editor = {
521
- ...defaultProps.editor,
522
- view: {
523
- ...defaultProps.editor.view,
524
- coordsAtPos: jest.fn(() => ({ top: 200, left: 150 })),
525
- dispatch: jest.fn(),
526
- },
527
- };
528
-
529
- const { container } = render(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
530
- await waitFor(() => {
531
- const toolbar = container.querySelector('[data-toolbar-for]');
532
- expect(toolbar).toBeInTheDocument();
533
- expect(toolbar.style.top).toBe('200px');
534
- expect(toolbar.style.left).toBe('150px');
535
- });
536
- });
537
-
538
- it('clamps toolbar position to viewport margins', async () => {
539
- const originalInnerHeight = window.innerHeight;
540
- const originalInnerWidth = window.innerWidth;
541
-
542
- Object.defineProperty(window, 'innerHeight', { configurable: true, writable: true, value: 200 });
543
- Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 300 });
544
-
545
- const editor = {
546
- ...defaultProps.editor,
547
- view: {
548
- ...defaultProps.editor.view,
549
- coordsAtPos: jest.fn(() => ({ top: 190, left: 280, bottom: 195 })),
550
- dispatch: jest.fn(),
551
- },
552
- };
553
-
554
- const { container } = render(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
555
-
556
- let toolbar;
557
- await waitFor(() => {
558
- toolbar = container.querySelector('[data-toolbar-for]');
559
- expect(toolbar).toBeInTheDocument();
560
- });
561
-
562
- Object.defineProperty(toolbar, 'offsetHeight', { configurable: true, value: 100 });
563
- Object.defineProperty(toolbar, 'offsetWidth', { configurable: true, value: 150 });
564
-
565
- await act(async () => {
566
- window.dispatchEvent(new Event('resize'));
567
- await new Promise((resolve) => requestAnimationFrame(resolve));
568
- });
569
-
570
- await waitFor(() => {
571
- expect(parseInt(toolbar.style.top, 10)).toBeLessThanOrEqual(200 - 100 - 8);
572
- expect(parseInt(toolbar.style.left, 10)).toBeLessThanOrEqual(300 - 150 - 8);
573
- expect(parseInt(toolbar.style.top, 10)).toBeGreaterThanOrEqual(8);
574
- expect(parseInt(toolbar.style.left, 10)).toBeGreaterThanOrEqual(8);
575
- });
576
-
577
- Object.defineProperty(window, 'innerHeight', { configurable: true, writable: true, value: originalInnerHeight });
578
- Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: originalInnerWidth });
579
- });
580
-
581
- it('attaches scroll and resize listeners while toolbar is open', async () => {
582
- const addSpy = jest.spyOn(window, 'addEventListener');
583
- render(<MathNodeView {...defaultProps} selected={true} />);
584
- await waitFor(() => {
585
- expect(addSpy).toHaveBeenCalledWith('scroll', expect.any(Function), true);
586
- expect(addSpy).toHaveBeenCalledWith('resize', expect.any(Function));
587
- });
588
- addSpy.mockRestore();
589
- });
590
-
591
- it('portals toolbar into _tiptapContainerEl when available', async () => {
592
- const containerEl = document.createElement('div');
593
- containerEl.getBoundingClientRect = jest.fn(() => ({ top: 0, left: 0, width: 600, height: 400 }));
594
-
595
- const editor = {
596
- ...defaultProps.editor,
597
- _tiptapContainerEl: containerEl,
598
- };
599
-
600
- mockCreatePortal.mockClear();
601
- render(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
602
- await waitFor(() => {
603
- expect(mockCreatePortal).toHaveBeenCalled();
604
- const lastCall = mockCreatePortal.mock.calls[mockCreatePortal.mock.calls.length - 1];
605
- expect(lastCall[1]).toBe(containerEl);
606
- });
607
- });
608
-
609
- it('portals toolbar into document.body when _tiptapContainerEl is not set', async () => {
610
- const editor = {
611
- ...defaultProps.editor,
612
- _tiptapContainerEl: undefined,
613
- };
614
-
615
- mockCreatePortal.mockClear();
616
- render(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
617
- await waitFor(() => {
618
- expect(mockCreatePortal).toHaveBeenCalled();
619
- const lastCall = mockCreatePortal.mock.calls[mockCreatePortal.mock.calls.length - 1];
620
- expect(lastCall[1]).toBe(document.body);
621
- });
622
- });
623
- });
624
-
625
- it('calls updateAttributes when latex changes', async () => {
626
- const { getByTestId } = render(<MathNodeView {...defaultProps} selected={true} />);
627
- await waitFor(() => {
628
- const input = getByTestId('math-input');
629
- fireEvent.change(input, { target: { value: 'y^2' } });
630
- });
631
- expect(defaultProps.updateAttributes).toHaveBeenCalledWith({ latex: 'y^2' });
632
- });
633
-
634
- it('closes toolbar and updates attributes when done', async () => {
635
- const updateAttributes = jest.fn();
636
- const { getByTestId } = render(
637
- <MathNodeView {...defaultProps} updateAttributes={updateAttributes} selected={true} />,
638
- );
639
-
640
- await waitFor(() => {
641
- expect(getByTestId('done-button')).toBeInTheDocument();
642
- });
643
-
644
- const doneButton = getByTestId('done-button');
645
- fireEvent.click(doneButton);
646
-
647
- await waitFor(() => {
648
- expect(updateAttributes).toHaveBeenCalledWith({ latex: 'x^2' });
649
- });
650
- });
651
-
652
- it('sets editor._toolbarOpened when toolbar is shown', async () => {
653
- const { getByTestId } = render(<MathNodeView {...defaultProps} selected={true} />);
654
- await waitFor(() => {
655
- expect(getByTestId('math-toolbar')).toBeInTheDocument();
656
- expect(defaultProps.editor._toolbarOpened).toBe(true);
657
- });
658
- });
659
-
660
- it('unsets editor._toolbarOpened when toolbar is closed and node is not selected', async () => {
661
- const { getByTestId } = render(<MathNodeView {...defaultProps} selected={false} />);
662
-
663
- fireEvent.click(getByTestId('math-preview'));
664
-
665
- await waitFor(() => {
666
- expect(getByTestId('math-toolbar')).toBeInTheDocument();
667
- expect(defaultProps.editor._toolbarOpened).toBe(true);
668
- });
669
-
670
- fireEvent.click(getByTestId('done-button'));
671
-
672
- await waitFor(() => {
673
- expect(defaultProps.editor._toolbarOpened).toBe(false);
674
- });
675
- });
676
-
677
- it('keeps editor._toolbarOpened true while the math node remains selected', async () => {
678
- const { getByTestId } = render(<MathNodeView {...defaultProps} selected={true} />);
679
-
680
- await waitFor(() => {
681
- expect(getByTestId('done-button')).toBeInTheDocument();
682
- expect(defaultProps.editor._toolbarOpened).toBe(true);
683
- });
684
-
685
- fireEvent.click(getByTestId('done-button'));
686
-
687
- await waitFor(() => {
688
- expect(defaultProps.editor._toolbarOpened).toBe(true);
689
- });
690
- });
691
-
692
- it('closes toolbar on outside click and runs handleDone', async () => {
693
- const updateAttributes = jest.fn();
694
- const editor = createMockEditor();
695
- const { TextSelection } = require('prosemirror-state');
696
- const { queryByTestId } = render(
697
- <MathNodeView {...defaultProps} editor={editor} updateAttributes={updateAttributes} selected={true} />,
698
- );
699
-
700
- await waitFor(() => {
701
- expect(queryByTestId('math-toolbar')).toBeInTheDocument();
702
- });
703
-
704
- fireEvent.click(document.body);
705
-
706
- await waitFor(() => {
707
- expect(queryByTestId('math-toolbar')).not.toBeInTheDocument();
708
- expect(updateAttributes).toHaveBeenCalledWith({ latex: 'x^2' });
709
- expect(TextSelection.create).toHaveBeenCalledWith(editor.state.doc, 1);
710
- expect(editor.state.tr.setSelection).toHaveBeenCalled();
711
- expect(editor.view.dispatch).toHaveBeenCalledWith(editor.state.tr);
712
- expect(editor.commands.focus).toHaveBeenCalled();
713
- expect(editor._toolbarOpened).toBe(true);
714
- });
715
- });
716
-
717
- it('re-registers click listener when node changes', async () => {
718
- const addEventListenerSpy = jest.spyOn(document, 'addEventListener');
719
- const removeEventListenerSpy = jest.spyOn(document, 'removeEventListener');
720
- const nodeA = { attrs: { latex: 'x^2' } };
721
- const nodeB = { attrs: { latex: 'y^2' } };
722
-
723
- const { rerender } = render(<MathNodeView {...defaultProps} node={nodeA} selected={true} />);
724
-
725
- await waitFor(() => {
726
- expect(addEventListenerSpy).toHaveBeenCalledWith('click', expect.any(Function));
727
- });
728
-
729
- const initialCallCount = addEventListenerSpy.mock.calls.length;
730
-
731
- rerender(<MathNodeView {...defaultProps} node={nodeB} selected={true} />);
732
-
733
- await waitFor(() => {
734
- expect(removeEventListenerSpy).toHaveBeenCalled();
735
- expect(addEventListenerSpy.mock.calls.length).toBeGreaterThan(initialCallCount);
736
- });
737
-
738
- addEventListenerSpy.mockRestore();
739
- removeEventListenerSpy.mockRestore();
740
- });
741
-
742
- it('does not close toolbar when clicking the math node preview', async () => {
743
- const { getByTestId, queryByTestId } = render(<MathNodeView {...defaultProps} selected={true} />);
744
-
745
- await waitFor(() => {
746
- expect(queryByTestId('math-toolbar')).toBeInTheDocument();
747
- });
748
-
749
- fireEvent.click(getByTestId('math-preview'));
750
-
751
- await waitFor(() => {
752
- expect(queryByTestId('math-toolbar')).toBeInTheDocument();
753
- });
754
- });
755
-
756
- describe('unique math-node class per instance', () => {
757
- let dateNowSpy;
758
-
759
- beforeEach(() => {
760
- let timestamp = 1000;
761
- dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => timestamp++);
762
- });
763
-
764
- afterEach(() => {
765
- dateNowSpy.mockRestore();
766
- });
767
-
768
- // The wrapper is an emotion styled() component, so className also carries
769
- // emotion's generated class - assert on the math-node token, not equality.
770
- it('assigns a timestamp-based class to NodeViewWrapper', () => {
771
- const { getByTestId } = render(<MathNodeView {...defaultProps} />);
772
- const wrapper = getByTestId('node-view-wrapper');
773
-
774
- expect(Array.from(wrapper.classList).some((c) => /^math-node-\d+$/.test(c))).toBe(true);
775
- });
776
-
777
- it('assigns a different class to each MathNodeView instance', () => {
778
- const { getAllByTestId } = render(
779
- <>
780
- <MathNodeView {...defaultProps} />
781
- <MathNodeView {...defaultProps} node={{ attrs: { latex: 'y^2' } }} />
782
- </>,
783
- );
784
-
785
- const wrappers = getAllByTestId('node-view-wrapper');
786
- const mathNodeClass = (el) => Array.from(el.classList).find((c) => c.startsWith('math-node-'));
787
-
788
- expect(mathNodeClass(wrappers[0])).toBe('math-node-1000');
789
- expect(mathNodeClass(wrappers[1])).toBe('math-node-1001');
790
- // and they must differ
791
- expect(mathNodeClass(wrappers[0])).not.toBe(mathNodeClass(wrappers[1]));
792
- });
793
-
794
- it('closes toolbar when clicking a different math node', async () => {
795
- const updateAttributes = jest.fn();
796
- const editorA = createMockEditor();
797
- const editorB = createMockEditor();
798
-
799
- const { getAllByTestId, queryAllByTestId } = render(
800
- <>
801
- <MathNodeView {...defaultProps} editor={editorA} updateAttributes={updateAttributes} selected={false} />
802
- <MathNodeView {...defaultProps} editor={editorB} node={{ attrs: { latex: 'y^2' } }} selected={false} />
803
- </>,
804
- );
805
-
806
- fireEvent.click(getAllByTestId('math-preview')[0]);
807
-
808
- await waitFor(() => {
809
- expect(queryAllByTestId('math-toolbar')).toHaveLength(1);
810
- });
811
-
812
- const secondPreview = getAllByTestId('math-preview')[1];
813
- fireEvent.click(secondPreview);
814
-
815
- await waitFor(() => {
816
- expect(queryAllByTestId('math-toolbar')).toHaveLength(1);
817
- expect(updateAttributes).toHaveBeenCalledWith({ latex: 'x^2' });
818
- expect(editorA._toolbarOpened).toBe(false);
819
- expect(getAllByTestId('math-input')[0]).toHaveValue('y^2');
820
- });
821
- });
822
- });
823
-
824
- describe('selection-based toolbar guard', () => {
825
- it('opens toolbar when selected transitions to true and the editor has a NodeSelection on math', async () => {
826
- const { queryByTestId, rerender } = render(<MathNodeView {...defaultProps} selected={false} />);
827
- expect(queryByTestId('math-toolbar')).not.toBeInTheDocument();
828
-
829
- rerender(<MathNodeView {...defaultProps} selected={true} />);
830
- await waitFor(() => {
831
- expect(queryByTestId('math-toolbar')).toBeInTheDocument();
832
- });
833
- });
834
-
835
- it('does not open toolbar when selected briefly becomes true but editor selection has no node (Cmd+A / drag case)', async () => {
836
- const editor = {
837
- ...defaultProps.editor,
838
- state: {
839
- ...defaultProps.editor.state,
840
- selection: { from: 0, to: 100 }, // no .node — TextSelection / AllSelection shape
841
- },
842
- };
843
-
844
- const { queryByTestId, rerender } = render(<MathNodeView {...defaultProps} editor={editor} selected={false} />);
845
- rerender(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
846
-
847
- await act(async () => {});
848
- expect(queryByTestId('math-toolbar')).not.toBeInTheDocument();
849
- });
850
-
851
- it('does not open toolbar when selected briefly becomes true but NodeSelection targets a non-math node', async () => {
852
- const editor = {
853
- ...defaultProps.editor,
854
- state: {
855
- ...defaultProps.editor.state,
856
- selection: { from: 0, to: 1, node: { type: { name: 'image' } } },
857
- },
858
- };
859
-
860
- const { queryByTestId, rerender } = render(<MathNodeView {...defaultProps} editor={editor} selected={false} />);
861
- rerender(<MathNodeView {...defaultProps} editor={editor} selected={true} />);
862
-
863
- await act(async () => {});
864
- expect(queryByTestId('math-toolbar')).not.toBeInTheDocument();
865
- });
866
- });
867
-
868
- it('does not close toolbar when clicking equation editor dropdown', async () => {
869
- const { queryByTestId } = render(<MathNodeView {...defaultProps} selected={true} />);
870
-
871
- await waitFor(() => {
872
- expect(queryByTestId('math-toolbar')).toBeInTheDocument();
873
- });
874
-
875
- // Simulate MUI Select's portal dropdown container.
876
- const dropdown = document.createElement('div');
877
- dropdown.id = 'equation-editor-select-listbox';
878
- document.body.appendChild(dropdown);
879
-
880
- fireEvent.click(dropdown);
881
-
882
- await waitFor(() => {
883
- expect(queryByTestId('math-toolbar')).toBeInTheDocument();
884
- });
885
-
886
- document.body.removeChild(dropdown);
887
- });
888
-
889
- it('renders with empty latex', () => {
890
- const nodeWithEmptyLatex = { attrs: { latex: '' } };
891
- const { getByTestId } = render(<MathNodeView {...defaultProps} node={nodeWithEmptyLatex} />);
892
- expect(getByTestId('math-preview')).toBeInTheDocument();
893
- });
894
-
895
- it('has correct styling on NodeViewWrapper', () => {
896
- const { getByTestId } = render(<MathNodeView {...defaultProps} />);
897
- const wrapper = getByTestId('node-view-wrapper');
898
- expect(wrapper).toHaveStyle({ display: 'inline-flex', cursor: 'pointer' });
899
- });
900
- });