Welcome to mirror list, hosted at ThFree Co, Russian Federation.

copy_paste_spec.js « extensions « content_editor « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f8faa7869c05cf63ccbcc1091444b1ff5b7cb54c (plain)
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
import CopyPaste from '~/content_editor/extensions/copy_paste';
import CodeBlockHighlight from '~/content_editor/extensions/code_block_highlight';
import Loading from '~/content_editor/extensions/loading';
import Diagram from '~/content_editor/extensions/diagram';
import Frontmatter from '~/content_editor/extensions/frontmatter';
import Heading from '~/content_editor/extensions/heading';
import Bold from '~/content_editor/extensions/bold';
import Italic from '~/content_editor/extensions/italic';
import { VARIANT_DANGER } from '~/alert';
import eventHubFactory from '~/helpers/event_hub_factory';
import { ALERT_EVENT } from '~/content_editor/constants';
import waitForPromises from 'helpers/wait_for_promises';
import MarkdownSerializer from '~/content_editor/services/markdown_serializer';
import {
  createTestEditor,
  createDocBuilder,
  waitUntilNextDocTransaction,
  sleep,
} from '../test_utils';

const CODE_BLOCK_HTML = '<pre class="js-syntax-highlight" lang="javascript">var a = 2;</pre>';
const CODE_SUGGESTION_HTML =
  '<pre data-lang-params="-0+0" class="js-syntax-highlight language-suggestion" lang="suggestion">Suggested code</pre>';
const DIAGRAM_HTML =
  '<img data-diagram="nomnoml" data-diagram-src="data:text/plain;base64,WzxmcmFtZT5EZWNvcmF0b3IgcGF0dGVybl0=">';
const FRONTMATTER_HTML = '<pre lang="yaml" data-lang-params="frontmatter">key: value</pre>';
const PARAGRAPH_HTML =
  '<p dir="auto">Some text with <strong>bold</strong> and <em>italic</em> text.</p>';

describe('content_editor/extensions/copy_paste', () => {
  let tiptapEditor;
  let doc;
  let p;
  let bold;
  let italic;
  let loading;
  let heading;
  let codeBlock;
  let renderMarkdown;
  let resolveRenderMarkdownPromise;
  let resolveRenderMarkdownPromiseAndWait;

  let eventHub;
  const defaultData = { 'text/plain': '**bold text**' };

  beforeEach(() => {
    eventHub = eventHubFactory();
    renderMarkdown = jest.fn().mockImplementation(
      () =>
        new Promise((resolve) => {
          resolveRenderMarkdownPromise = resolve;
          resolveRenderMarkdownPromiseAndWait = (data) =>
            waitUntilNextDocTransaction({ tiptapEditor, action: () => resolve(data) });
        }),
    );

    jest.spyOn(eventHub, '$emit');

    tiptapEditor = createTestEditor({
      extensions: [
        Bold,
        Italic,
        Loading,
        CodeBlockHighlight,
        Diagram,
        Frontmatter,
        Heading,
        CopyPaste.configure({ renderMarkdown, eventHub, serializer: new MarkdownSerializer() }),
      ],
    });

    ({
      builders: { doc, p, bold, italic, heading, loading, codeBlock },
    } = createDocBuilder({
      tiptapEditor,
      names: {
        bold: { markType: Bold.name },
        italic: { markType: Italic.name },
        loading: { nodeType: Loading.name },
        heading: { nodeType: Heading.name },
        codeBlock: { nodeType: CodeBlockHighlight.name },
      },
    }));
  });

  const buildClipboardEvent = ({ eventName = 'paste', data = {}, types = ['text/plain'] } = {}) => {
    return Object.assign(new Event(eventName), {
      clipboardData: {
        types,
        getData: jest.fn((type) => data[type] || defaultData[type]),
        setData: jest.fn(),
        clearData: jest.fn(),
      },
    });
  };

  const triggerPasteEventHandler = (event) => {
    return new Promise((resolve) => {
      tiptapEditor.view.someProp('handlePaste', (eventHandler) => {
        resolve(eventHandler(tiptapEditor.view, event));
      });
    });
  };

  const triggerPasteEventHandlerAndWaitForTransaction = (event) => {
    return waitUntilNextDocTransaction({
      tiptapEditor,
      action: () => {
        tiptapEditor.view.someProp('handlePaste', (eventHandler) => {
          return eventHandler(tiptapEditor.view, event);
        });
      },
    });
  };

  it.each`
    types                                                | data                                                  | formatDesc
    ${['text/plain']}                                    | ${{}}                                                 | ${'plain text'}
    ${['text/plain', 'text/html']}                       | ${{}}                                                 | ${'html format'}
    ${['text/plain', 'text/html', 'vscode-editor-data']} | ${{ 'vscode-editor-data': '{ "mode": "markdown" }' }} | ${'vscode markdown'}
    ${['text/plain', 'text/html', 'vscode-editor-data']} | ${{ 'vscode-editor-data': '{ "mode": "ruby" }' }}     | ${'vscode snippet'}
  `('handles $formatDesc', async ({ types, data }) => {
    expect(await triggerPasteEventHandler(buildClipboardEvent({ types, data }))).toBe(true);
  });

  it.each`
    nodeType            | html                    | handled  | desc
    ${'codeBlock'}      | ${CODE_BLOCK_HTML}      | ${false} | ${'does not handle'}
    ${'codeSuggestion'} | ${CODE_SUGGESTION_HTML} | ${false} | ${'does not handle'}
    ${'diagram'}        | ${DIAGRAM_HTML}         | ${false} | ${'does not handle'}
    ${'frontmatter'}    | ${FRONTMATTER_HTML}     | ${false} | ${'does not handle'}
    ${'paragraph'}      | ${PARAGRAPH_HTML}       | ${true}  | ${'handles'}
  `('$desc paste if currently a `$nodeType` is in focus', async ({ html, handled }) => {
    tiptapEditor.commands.insertContent(html);

    expect(await triggerPasteEventHandler(buildClipboardEvent())).toBe(handled);
  });

  describe.each`
    eventName | expectedDoc
    ${'cut'}  | ${() => doc(p())}
    ${'copy'} | ${() => doc(p('Some text with ', bold('bold'), ' and ', italic('italic'), ' text.'))}
  `('when $eventName event is triggered', ({ eventName, expectedDoc }) => {
    let event;
    beforeEach(() => {
      event = buildClipboardEvent({ eventName });

      jest.spyOn(event, 'preventDefault');
      jest.spyOn(event, 'stopPropagation');

      tiptapEditor.commands.insertContent(PARAGRAPH_HTML);
      tiptapEditor.commands.selectAll();
      tiptapEditor.view.dispatchEvent(event);
    });

    it('prevents default', () => {
      expect(event.preventDefault).toHaveBeenCalled();
      expect(event.stopPropagation).toHaveBeenCalled();
    });

    it('sets the clipboard data', () => {
      expect(event.clipboardData.setData).toHaveBeenCalledWith(
        'text/plain',
        'Some text with bold and italic text.',
      );
      expect(event.clipboardData.setData).toHaveBeenCalledWith('text/html', PARAGRAPH_HTML);
      expect(event.clipboardData.setData).toHaveBeenCalledWith(
        'text/x-gfm',
        'Some text with **bold** and _italic_ text.',
      );
    });

    it('modifies the document', () => {
      expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc().toJSON());
    });
  });

  describe('when pasting raw markdown source', () => {
    it('shows a loading indicator while markdown is being processed', async () => {
      const expectedDoc = doc(p(loading({ id: expect.any(String) })));

      await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());

      expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
    });

    it('pastes in the correct position if some content is added before the markdown is processed', async () => {
      const expectedDoc = doc(p(bold('some markdown'), 'some content'));
      const resolvedValue = '<strong>some markdown</strong>';

      await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());

      tiptapEditor.commands.insertContent('some content');
      await resolveRenderMarkdownPromiseAndWait(resolvedValue);

      expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
      expect(tiptapEditor.state.selection.from).toEqual(26); // end of the document
    });

    it('does not paste anything if the loading indicator is deleted before the markdown is processed', async () => {
      const expectedDoc = doc(p());

      await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());
      tiptapEditor.chain().selectAll().deleteSelection().run();
      resolveRenderMarkdownPromise('some markdown');

      // wait some time to be sure no transaction happened
      await sleep();
      expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
    });

    describe('when rendering markdown succeeds', () => {
      let resolvedValue;

      beforeEach(() => {
        resolvedValue = '<strong>bold text</strong>';
      });

      it('transforms pasted text into a prosemirror node', async () => {
        const expectedDoc = doc(p(bold('bold text')));

        await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());
        await resolveRenderMarkdownPromiseAndWait(resolvedValue);

        expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
      });

      describe('when pasting inline content in an existing paragraph', () => {
        it('inserts the inline content next to the existing paragraph content', async () => {
          const expectedDoc = doc(p('Initial text and', bold('bold text')));

          tiptapEditor.commands.setContent('Initial text and ');

          await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());
          await resolveRenderMarkdownPromiseAndWait(resolvedValue);

          expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
        });
      });

      describe('when pasting inline content and there is text selected', () => {
        it('inserts the block content after the existing paragraph', async () => {
          const expectedDoc = doc(p('Initial text', bold('bold text')));

          tiptapEditor.commands.setContent('Initial text and ');
          tiptapEditor.commands.setTextSelection({ from: 13, to: 17 });

          await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());
          await resolveRenderMarkdownPromiseAndWait(resolvedValue);

          expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
        });
      });

      describe('when pasting block content in an existing paragraph', () => {
        beforeEach(() => {
          resolvedValue = '<h1>Heading</h1><p><strong>bold text</strong></p>';
        });

        it('inserts the block content after the existing paragraph', async () => {
          const expectedDoc = doc(
            p('Initial text and'),
            heading({ level: 1 }, 'Heading'),
            p(bold('bold text')),
          );

          tiptapEditor.commands.setContent('Initial text and ');

          await triggerPasteEventHandlerAndWaitForTransaction(buildClipboardEvent());
          await resolveRenderMarkdownPromiseAndWait(resolvedValue);

          expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
        });
      });
    });

    describe('when pasting html content', () => {
      it('strips out any stray div, pre, span tags', async () => {
        const resolvedValue =
          '<div><span dir="auto"><strong>bold text</strong></span></div><pre><code>some code</code></pre>';

        const expectedDoc = doc(p(bold('bold text')), p('some code'));

        await triggerPasteEventHandlerAndWaitForTransaction(
          buildClipboardEvent({
            types: ['text/html'],
            data: {
              'text/html':
                '<div><span dir="auto"><strong>bold text</strong></span></div><pre><code>some code</code></pre>',
            },
          }),
        );
        await resolveRenderMarkdownPromiseAndWait(resolvedValue);

        expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
      });
    });

    describe('when pasting text/x-gfm', () => {
      it('processes the content as markdown, even if html content exists', async () => {
        const resolvedValue = '<strong>bold text</strong>';
        const expectedDoc = doc(p(bold('bold text')));

        await triggerPasteEventHandlerAndWaitForTransaction(
          buildClipboardEvent({
            types: ['text/x-gfm'],
            data: {
              'text/x-gfm': '**bold text**',
              'text/plain': 'irrelevant text',
              'text/html': '<div>some random irrelevant html</div>',
            },
          }),
        );
        await resolveRenderMarkdownPromiseAndWait(resolvedValue);

        expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
      });
    });

    describe('when pasting vscode-editor-data', () => {
      it('pastes the content as a code block', async () => {
        const resolvedValue =
          '<div class="gl-relative markdown-code-block js-markdown-code">&#x000A;<pre data-sourcepos="1:1-3:3" data-canonical-lang="ruby" class="code highlight js-syntax-highlight language-ruby" lang="ruby" v-pre="true"><code><span id="LC1" class="line" lang="ruby"><span class="nb">puts</span> <span class="s2">"Hello World"</span></span></code></pre>&#x000A;<copy-code></copy-code>&#x000A;</div>';

        const expectedDoc = doc(
          codeBlock(
            { language: 'ruby', class: 'code highlight js-syntax-highlight language-ruby' },
            'puts "Hello World"',
          ),
        );

        await triggerPasteEventHandlerAndWaitForTransaction(
          buildClipboardEvent({
            types: ['vscode-editor-data', 'text/plain', 'text/html'],
            data: {
              'vscode-editor-data': '{ "version": 1, "mode": "ruby" }',
              'text/plain': 'puts "Hello World"',
              'text/html':
                '<meta charset=\'utf-8\'><div style="color: #d4d4d4;background-color: #1e1e1e;font-family: \'Fira Code\', Menlo, Monaco, \'Courier New\', monospace, Menlo, Monaco, \'Courier New\', monospace;font-weight: normal;font-size: 14px;line-height: 21px;white-space: pre;"><div><span style="color: #dcdcaa;">puts</span><span style="color: #d4d4d4;"> </span><span style="color: #ce9178;">"Hello world"</span></div></div>',
            },
          }),
        );
        await resolveRenderMarkdownPromiseAndWait(resolvedValue);

        expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
      });

      it('pastes as regular markdown if language is markdown', async () => {
        const resolvedValue = '<p><strong>bold text</strong></p>';

        const expectedDoc = doc(p(bold('bold text')));

        await triggerPasteEventHandlerAndWaitForTransaction(
          buildClipboardEvent({
            types: ['vscode-editor-data', 'text/plain', 'text/html'],
            data: {
              'vscode-editor-data': '{ "version": 1, "mode": "markdown" }',
              'text/plain': '**bold text**',
              'text/html': '<p><strong>bold text</strong></p>',
            },
          }),
        );
        await resolveRenderMarkdownPromiseAndWait(resolvedValue);

        expect(tiptapEditor.state.doc.toJSON()).toEqual(expectedDoc.toJSON());
      });
    });

    describe('when rendering markdown fails', () => {
      beforeEach(() => {
        renderMarkdown.mockRejectedValueOnce();
      });

      it(`triggers ${ALERT_EVENT} event`, async () => {
        await triggerPasteEventHandler(buildClipboardEvent());
        await waitForPromises();

        expect(eventHub.$emit).toHaveBeenCalledWith(ALERT_EVENT, {
          message: expect.any(String),
          variant: VARIANT_DANGER,
        });
      });
    });
  });
});