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

code_block_spec.js « wrappers « components « content_editor « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1f15dc17f7f909e691b44579c6efae40ae1d822f (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
386
387
388
389
390
391
392
393
394
395
396
397
import { nextTick } from 'vue';
import { NodeViewWrapper, NodeViewContent } from '@tiptap/vue-2';
import { mountExtended } from 'helpers/vue_test_utils_helper';
import { stubComponent } from 'helpers/stub_component';
import eventHubFactory from '~/helpers/event_hub_factory';
import SandboxedMermaid from '~/behaviors/components/sandboxed_mermaid.vue';
import CodeBlockHighlight from '~/content_editor/extensions/code_block_highlight';
import Diagram from '~/content_editor/extensions/diagram';
import CodeSuggestion from '~/content_editor/extensions/code_suggestion';
import CodeBlockWrapper from '~/content_editor/components/wrappers/code_block.vue';
import codeBlockLanguageLoader from '~/content_editor/services/code_block_language_loader';
import { emitEditorEvent, createTestEditor, mockChainedCommands } from '../../test_utils';

// Disabled due to eslint reporting errors for inline snapshots
/* eslint-disable no-irregular-whitespace */

const SAMPLE_README_CONTENT = `# Sample README

This is a sample README.

## Usage

\`\`\`yaml
foo: bar
\`\`\`
`;

jest.mock('~/content_editor/services/code_block_language_loader');
jest.mock('~/content_editor/services/utils', () => ({
  memoizedGet: jest.fn().mockResolvedValue(SAMPLE_README_CONTENT),
}));

describe('content/components/wrappers/code_block', () => {
  const language = 'yaml';
  let wrapper;
  let updateAttributesFn;
  let tiptapEditor;
  let contentEditor;
  let eventHub;

  const buildEditor = () => {
    tiptapEditor = createTestEditor({ extensions: [CodeBlockHighlight, Diagram, CodeSuggestion] });
    contentEditor = { renderDiagram: jest.fn().mockResolvedValue('url/to/some/diagram') };
    eventHub = eventHubFactory();
  };

  const createWrapper = (nodeAttrs = { language }) => {
    updateAttributesFn = jest.fn();

    wrapper = mountExtended(CodeBlockWrapper, {
      propsData: {
        editor: tiptapEditor,
        node: {
          attrs: nodeAttrs,
        },
        updateAttributes: updateAttributesFn,
      },
      stubs: {
        NodeViewContent: stubComponent(NodeViewContent),
        NodeViewWrapper: stubComponent(NodeViewWrapper),
      },
      provide: {
        contentEditor,
        tiptapEditor,
        eventHub,
      },
    });
  };

  beforeEach(() => {
    buildEditor();

    codeBlockLanguageLoader.findOrCreateLanguageBySyntax.mockReturnValue({ syntax: language });
  });

  it('renders a node-view-wrapper as a pre element', () => {
    createWrapper();

    expect(wrapper.findComponent(NodeViewWrapper).props().as).toBe('pre');
    expect(wrapper.findComponent(NodeViewWrapper).classes()).toContain('gl-relative');
  });

  it('adds content-editor-code-block class to the pre element', () => {
    createWrapper();
    expect(wrapper.findComponent(NodeViewWrapper).classes()).toContain('content-editor-code-block');
  });

  it('renders a node-view-content as a code element', () => {
    createWrapper();

    expect(wrapper.findComponent(NodeViewContent).props().as).toBe('code');
  });

  it('renders label indicating that code block is frontmatter', () => {
    createWrapper({ isFrontmatter: true, language });

    const label = wrapper.findByTestId('frontmatter-label');

    expect(label.text()).toEqual('frontmatter:yaml');
    expect(label.attributes('contenteditable')).toBe('false');
    expect(label.classes()).toEqual(['gl-absolute', 'gl-top-0', 'gl-right-3']);
  });

  it('loads code block’s syntax highlight language', async () => {
    createWrapper();

    expect(codeBlockLanguageLoader.loadLanguage).toHaveBeenCalledWith(language);

    await nextTick();

    expect(updateAttributesFn).toHaveBeenCalledWith({ language });
  });

  describe('diagrams', () => {
    beforeEach(() => {
      jest.spyOn(tiptapEditor, 'isActive').mockReturnValue(true);
    });

    it('does not render a preview if showPreview: false', () => {
      createWrapper({ language: 'plantuml', isDiagram: true, showPreview: false });

      expect(wrapper.findComponent({ ref: 'diagramContainer' }).exists()).toBe(false);
    });

    it('does not update preview when diagram is not active', async () => {
      createWrapper({ language: 'plantuml', isDiagram: true, showPreview: true });

      await emitEditorEvent({ event: 'transaction', tiptapEditor });
      await nextTick();

      expect(wrapper.find('img').attributes('src')).toBe('url/to/some/diagram');
      expect(wrapper.findByTestId('sandbox-preview').attributes('contenteditable')).toBe(
        String(false),
      );

      jest.spyOn(tiptapEditor, 'isActive').mockReturnValue(false);

      const alternateUrl = 'url/to/another/diagram';

      contentEditor.renderDiagram.mockResolvedValue(alternateUrl);

      await emitEditorEvent({ event: 'transaction', tiptapEditor });
      await nextTick();

      expect(wrapper.find('img').attributes('src')).toBe('url/to/some/diagram');
    });

    it('renders an image with preview for a plantuml/kroki diagram', async () => {
      createWrapper({ language: 'plantuml', isDiagram: true, showPreview: true });

      await emitEditorEvent({ event: 'transaction', tiptapEditor });
      await nextTick();

      expect(wrapper.find('img').attributes('src')).toBe('url/to/some/diagram');
      expect(wrapper.findComponent(SandboxedMermaid).exists()).toBe(false);
    });

    it('renders an iframe with preview for a mermaid diagram', async () => {
      createWrapper({ language: 'mermaid', isDiagram: true, showPreview: true });

      await emitEditorEvent({ event: 'transaction', tiptapEditor });
      await nextTick();

      expect(wrapper.findComponent(SandboxedMermaid).props('source')).toBe('');
      expect(wrapper.find('img').exists()).toBe(false);
    });
  });

  describe('code suggestions', () => {
    const nodeAttrs = { language: 'suggestion', isCodeSuggestion: true, langParams: '-0+0' };
    const findCodeSuggestionBoxText = () =>
      wrapper.findByTestId('code-suggestion-box').text().replace(/\s+/gm, ' ');
    const findCodeDeleted = () =>
      wrapper
        .findByTestId('suggestion-deleted')
        .findAll('code')
        .wrappers.map((w) => w.html())
        .join('\n');
    const findCodeAdded = () =>
      wrapper
        .findByTestId('suggestion-added')
        .findAll('code')
        .wrappers.map((w) => w.html())
        .join('\n');

    let commands;

    const clickButton = async ({ button, expectedLangParams }) => {
      await button.trigger('click');

      expect(commands.updateAttributes).toHaveBeenCalledWith('codeSuggestion', {
        langParams: expectedLangParams,
      });
      expect(commands.run).toHaveBeenCalled();

      await wrapper.setProps({ node: { attrs: { ...nodeAttrs, langParams: expectedLangParams } } });
      await emitEditorEvent({ event: 'transaction', tiptapEditor });
    };

    beforeEach(async () => {
      contentEditor = {
        codeSuggestionsConfig: {
          canSuggest: true,
          line: { new_line: 5 },
          lines: [{ new_line: 5 }],
          showPopover: false,
          diffFile: {
            view_path:
              '/gitlab-org/gitlab-test/-/blob/468abc807a2b2572f43e72c743b76cee6db24025/README.md',
          },
        },
      };

      commands = mockChainedCommands(tiptapEditor, ['updateAttributes', 'run']);

      createWrapper(nodeAttrs);
      await emitEditorEvent({ event: 'transaction', tiptapEditor });
    });

    it('shows a code suggestion block', () => {
      expect(wrapper.findByTestId('code-suggestion-box').attributes('contenteditable')).toBe(
        'false',
      );
      expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 5 to 5');
      expect(findCodeDeleted()).toMatchInlineSnapshot(`
        <code
          data-line-number="5"
        >
          ## Usage​
        </code>
      `);
      expect(findCodeAdded()).toMatchInlineSnapshot(`
        <code
          data-line-number="5"
        >
          ​
        </code>
      `);
    });

    describe('decrement line start button', () => {
      let button;

      beforeEach(() => {
        button = wrapper.findByTestId('decrement-line-start');
      });

      it('decrements the start line number', async () => {
        await clickButton({ button, expectedLangParams: '-1+0' });

        expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 4 to 5');
        expect(findCodeDeleted()).toMatchInlineSnapshot(`
          <code
            data-line-number="4"
          >
            ​
          </code>
        `);
      });

      it('is disabled if the start line is already 1', async () => {
        expect(button.attributes('disabled')).toBeUndefined();

        await clickButton({ button, expectedLangParams: '-1+0' });
        await clickButton({ button, expectedLangParams: '-2+0' });
        await clickButton({ button, expectedLangParams: '-3+0' });
        await clickButton({ button, expectedLangParams: '-4+0' });

        expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 1 to 5');
        expect(findCodeDeleted()).toMatchInlineSnapshot(`
          <code
            data-line-number="1"
          >
            # Sample README​
          </code>
        `);

        expect(button.attributes('disabled')).toBe('disabled');
      });
    });

    describe('increment line start button', () => {
      let decrementButton;
      let button;

      beforeEach(() => {
        decrementButton = wrapper.findByTestId('decrement-line-start');
        button = wrapper.findByTestId('increment-line-start');
      });

      it('is disabled if the start line is already the current line', async () => {
        expect(button.attributes('disabled')).toBe('disabled');

        // decrement once, increment once
        await clickButton({ button: decrementButton, expectedLangParams: '-1+0' });
        expect(button.attributes('disabled')).toBeUndefined();
        await clickButton({ button, expectedLangParams: '-0+0' });

        expect(button.attributes('disabled')).toBe('disabled');
      });

      it('increments the start line number', async () => {
        // decrement twice, increment once
        await clickButton({ button: decrementButton, expectedLangParams: '-1+0' });
        await clickButton({ button: decrementButton, expectedLangParams: '-2+0' });
        await clickButton({ button, expectedLangParams: '-1+0' });

        expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 4 to 5');
        expect(findCodeDeleted()).toMatchInlineSnapshot(`
          <code
            data-line-number="4"
          >
            ​
          </code>
        `);
      });
    });

    describe('decrement line end button', () => {
      let incrementButton;
      let button;

      beforeEach(() => {
        incrementButton = wrapper.findByTestId('increment-line-end');
        button = wrapper.findByTestId('decrement-line-end');
      });

      it('is disabled if the line end is already the current line', async () => {
        expect(button.attributes('disabled')).toBe('disabled');

        // increment once, decrement once
        await clickButton({ button: incrementButton, expectedLangParams: '-0+1' });
        expect(button.attributes('disabled')).toBeUndefined();
        await clickButton({ button, expectedLangParams: '-0+0' });

        expect(button.attributes('disabled')).toBe('disabled');
      });

      it('increments the end line number', async () => {
        // increment twice, decrement once
        await clickButton({ button: incrementButton, expectedLangParams: '-0+1' });
        await clickButton({ button: incrementButton, expectedLangParams: '-0+2' });
        await clickButton({ button, expectedLangParams: '-0+1' });

        expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 5 to 6');
        expect(findCodeDeleted()).toMatchInlineSnapshot(`
          <code
            data-line-number="5"
          >
            ## Usage​
          </code>
        `);
      });
    });

    describe('increment line end button', () => {
      let button;

      beforeEach(() => {
        button = wrapper.findByTestId('increment-line-end');
      });

      it('decrements the start line number', async () => {
        await clickButton({ button, expectedLangParams: '-0+1' });

        expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 5 to 6');
        expect(findCodeDeleted()).toMatchInlineSnapshot(`
          <code
            data-line-number="5"
          >
            ## Usage​
          </code>
        `);
      });

      it('is disabled if the end line is EOF', async () => {
        expect(button.attributes('disabled')).toBeUndefined();

        await clickButton({ button, expectedLangParams: '-0+1' });
        await clickButton({ button, expectedLangParams: '-0+2' });
        await clickButton({ button, expectedLangParams: '-0+3' });
        await clickButton({ button, expectedLangParams: '-0+4' });

        expect(findCodeSuggestionBoxText()).toContain('Suggested change From line 5 to 9');
        expect(findCodeDeleted()).toMatchInlineSnapshot(`
          <code
            data-line-number="5"
          >
            ## Usage​
          </code>
        `);

        expect(button.attributes('disabled')).toBe('disabled');
      });
    });
  });
});