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

editor_lite_extension_base_spec.js « editor « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1ae8c70c7417a89be760d60960084b6b8ff3bfc1 (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
import { Range } from 'monaco-editor';
import { useFakeRequestAnimationFrame } from 'helpers/fake_request_animation_frame';
import {
  ERROR_INSTANCE_REQUIRED_FOR_EXTENSION,
  EDITOR_TYPE_CODE,
  EDITOR_TYPE_DIFF,
} from '~/editor/constants';
import { EditorLiteExtension } from '~/editor/extensions/editor_lite_extension_base';

describe('The basis for an Editor Lite extension', () => {
  const defaultLine = 3;
  let ext;
  let event;

  const defaultOptions = { foo: 'bar' };
  const findLine = (num) => {
    return document.querySelector(`.line-numbers:nth-child(${num})`);
  };
  const generateLines = () => {
    let res = '';
    for (let line = 1, lines = 5; line <= lines; line += 1) {
      res += `<div class="line-numbers">${line}</div>`;
    }
    return res;
  };
  const generateEventMock = ({ line = defaultLine, el = null } = {}) => {
    return {
      target: {
        element: el || findLine(line),
        position: {
          lineNumber: line,
        },
      },
    };
  };

  beforeEach(() => {
    setFixtures(generateLines());
    event = generateEventMock();
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  describe('constructor', () => {
    it.each`
      description                                                     | instance     | options
      ${'accepts configuration options and instance'}                 | ${{}}        | ${defaultOptions}
      ${'leaves instance intact if no options are passed'}            | ${{}}        | ${undefined}
      ${'does not fail if both instance and the options are omitted'} | ${undefined} | ${undefined}
      ${'throws if only options are passed'}                          | ${undefined} | ${defaultOptions}
    `('$description', ({ instance, options } = {}) => {
      const originalInstance = { ...instance };

      if (instance) {
        if (options) {
          Object.entries(options).forEach((prop) => {
            expect(instance[prop]).toBeUndefined();
          });
          // Both instance and options are passed
          ext = new EditorLiteExtension({ instance, ...options });
          Object.entries(options).forEach(([prop, value]) => {
            expect(ext[prop]).toBeUndefined();
            expect(instance[prop]).toBe(value);
          });
        } else {
          ext = new EditorLiteExtension({ instance });
          expect(instance).toEqual(originalInstance);
        }
      } else if (options) {
        // Options are passed without instance
        expect(() => {
          ext = new EditorLiteExtension({ ...options });
        }).toThrow(ERROR_INSTANCE_REQUIRED_FOR_EXTENSION);
      } else {
        // Neither options nor instance are passed
        expect(() => {
          ext = new EditorLiteExtension();
        }).not.toThrow();
      }
    });

    it('initializes the line highlighting', () => {
      const spy = jest.spyOn(EditorLiteExtension, 'highlightLines');
      ext = new EditorLiteExtension({ instance: {} });
      expect(spy).toHaveBeenCalled();
    });

    it('sets up the line linking for code instance', () => {
      const spy = jest.spyOn(EditorLiteExtension, 'setupLineLinking');
      const instance = {
        getEditorType: jest.fn().mockReturnValue(EDITOR_TYPE_CODE),
        onMouseMove: jest.fn(),
        onMouseDown: jest.fn(),
      };
      ext = new EditorLiteExtension({ instance });
      expect(spy).toHaveBeenCalledWith(instance);
    });

    it('does not set up the line linking for diff instance', () => {
      const spy = jest.spyOn(EditorLiteExtension, 'setupLineLinking');
      const instance = {
        getEditorType: jest.fn().mockReturnValue(EDITOR_TYPE_DIFF),
      };
      ext = new EditorLiteExtension({ instance });
      expect(spy).not.toHaveBeenCalled();
    });
  });

  describe('highlightLines', () => {
    const revealSpy = jest.fn();
    const decorationsSpy = jest.fn();
    const instance = {
      revealLineInCenter: revealSpy,
      deltaDecorations: decorationsSpy,
    };
    const defaultDecorationOptions = { isWholeLine: true, className: 'active-line-text' };

    useFakeRequestAnimationFrame();

    beforeEach(() => {
      delete window.location;
      window.location = new URL(`https://localhost`);
    });

    afterEach(() => {
      window.location.hash = '';
    });

    it.each`
      desc                                               | hash         | shouldReveal | expectedRange
      ${'properly decorates a single line'}              | ${'#L10'}    | ${true}      | ${[10, 1, 10, 1]}
      ${'properly decorates multiple lines'}             | ${'#L7-42'}  | ${true}      | ${[7, 1, 42, 1]}
      ${'correctly highlights if lines are reversed'}    | ${'#L42-7'}  | ${true}      | ${[7, 1, 42, 1]}
      ${'highlights one line if start/end are the same'} | ${'#L7-7'}   | ${true}      | ${[7, 1, 7, 1]}
      ${'does not highlight if there is no hash'}        | ${''}        | ${false}     | ${null}
      ${'does not highlight if the hash is undefined'}   | ${undefined} | ${false}     | ${null}
      ${'does not highlight if hash is incomplete 1'}    | ${'#L'}      | ${false}     | ${null}
      ${'does not highlight if hash is incomplete 2'}    | ${'#L-'}     | ${false}     | ${null}
    `('$desc', ({ hash, shouldReveal, expectedRange } = {}) => {
      window.location.hash = hash;
      EditorLiteExtension.highlightLines(instance);
      if (!shouldReveal) {
        expect(revealSpy).not.toHaveBeenCalled();
        expect(decorationsSpy).not.toHaveBeenCalled();
      } else {
        expect(revealSpy).toHaveBeenCalledWith(expectedRange[0]);
        expect(decorationsSpy).toHaveBeenCalledWith(
          [],
          [
            {
              range: new Range(...expectedRange),
              options: defaultDecorationOptions,
            },
          ],
        );
      }
    });

    it('stores the line  decorations on the instance', () => {
      decorationsSpy.mockReturnValue('foo');
      window.location.hash = '#L10';
      expect(instance.lineDecorations).toBeUndefined();
      EditorLiteExtension.highlightLines(instance);
      expect(instance.lineDecorations).toBe('foo');
    });
  });

  describe('setupLineLinking', () => {
    const instance = {
      onMouseMove: jest.fn(),
      onMouseDown: jest.fn(),
      deltaDecorations: jest.fn(),
      lineDecorations: 'foo',
    };

    beforeEach(() => {
      EditorLiteExtension.onMouseMoveHandler(event); // generate the anchor
    });

    it.each`
      desc             | spy
      ${'onMouseMove'} | ${instance.onMouseMove}
      ${'onMouseDown'} | ${instance.onMouseDown}
    `('sets up the $desc listener', ({ spy } = {}) => {
      EditorLiteExtension.setupLineLinking(instance);
      expect(spy).toHaveBeenCalled();
    });

    it.each`
      desc                                                                                | eventTrigger      | shouldRemove
      ${'does not remove the line decorations if the event is triggered on a wrong node'} | ${null}           | ${false}
      ${'removes existing line decorations when clicking a line number'}                  | ${'.link-anchor'} | ${true}
    `('$desc', ({ eventTrigger, shouldRemove } = {}) => {
      event = generateEventMock({ el: eventTrigger ? document.querySelector(eventTrigger) : null });
      instance.onMouseDown.mockImplementation((fn) => {
        fn(event);
      });

      EditorLiteExtension.setupLineLinking(instance);
      if (shouldRemove) {
        expect(instance.deltaDecorations).toHaveBeenCalledWith(instance.lineDecorations, []);
      } else {
        expect(instance.deltaDecorations).not.toHaveBeenCalled();
      }
    });
  });

  describe('onMouseMoveHandler', () => {
    it('stops propagation for contextmenu event on the generated anchor', () => {
      EditorLiteExtension.onMouseMoveHandler(event);
      const anchor = findLine(defaultLine).querySelector('a');
      const contextMenuEvent = new Event('contextmenu');

      jest.spyOn(contextMenuEvent, 'stopPropagation');
      anchor.dispatchEvent(contextMenuEvent);

      expect(contextMenuEvent.stopPropagation).toHaveBeenCalled();
    });

    it('creates an anchor if it does not exist yet', () => {
      expect(findLine(defaultLine).querySelector('a')).toBe(null);
      EditorLiteExtension.onMouseMoveHandler(event);
      expect(findLine(defaultLine).querySelector('a')).not.toBe(null);
    });

    it('does not create a new anchor if it exists', () => {
      EditorLiteExtension.onMouseMoveHandler(event);
      expect(findLine(defaultLine).querySelector('a')).not.toBe(null);

      EditorLiteExtension.createAnchor = jest.fn();
      EditorLiteExtension.onMouseMoveHandler(event);
      expect(EditorLiteExtension.createAnchor).not.toHaveBeenCalled();
      expect(findLine(defaultLine).querySelectorAll('a')).toHaveLength(1);
    });

    it('does not create a link if the event is triggered on a wrong node', () => {
      setFixtures('<div class="wrong-class">3</div>');
      EditorLiteExtension.createAnchor = jest.fn();
      const wrongEvent = generateEventMock({ el: document.querySelector('.wrong-class') });

      EditorLiteExtension.onMouseMoveHandler(wrongEvent);
      expect(EditorLiteExtension.createAnchor).not.toHaveBeenCalled();
    });
  });
});