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

shortcuts_spec.js « shortcuts « behaviors « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5f71eb24758473b0176a74921a14c67e837c2f81 (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
import $ from 'jquery';
import { flatten } from 'lodash';
import htmlSnippetsShow from 'test_fixtures/snippets/show.html';
import { Mousetrap } from '~/lib/mousetrap';
import { setHTMLFixture, resetHTMLFixture } from 'helpers/fixtures';
import Shortcuts, { LOCAL_MOUSETRAP_DATA_KEY } from '~/behaviors/shortcuts/shortcuts';
import MarkdownPreview from '~/behaviors/preview_markdown';

describe('Shortcuts', () => {
  let shortcuts;

  beforeAll(() => {
    shortcuts = new Shortcuts();
  });

  const mockSuperSidebarSearchButton = () => {
    const button = document.createElement('button');
    button.id = 'super-sidebar-search';
    return button;
  };

  beforeEach(() => {
    setHTMLFixture(htmlSnippetsShow);
    document.body.appendChild(mockSuperSidebarSearchButton());

    new Shortcuts(); // eslint-disable-line no-new
    new MarkdownPreview(); // eslint-disable-line no-new

    jest.spyOn(HTMLElement.prototype, 'click');

    jest.spyOn(Mousetrap.prototype, 'stopCallback');
    jest.spyOn(Mousetrap.prototype, 'bind').mockImplementation();
    jest.spyOn(Mousetrap.prototype, 'unbind').mockImplementation();
  });

  afterEach(() => {
    resetHTMLFixture();
  });

  it('does not allow subclassing', () => {
    const createSubclass = () => {
      class Subclass extends Shortcuts {}

      return new Subclass();
    };

    expect(createSubclass).toThrow(/cannot be subclassed/);
  });

  describe('markdown shortcuts', () => {
    let shortcutElements;

    beforeEach(() => {
      // Get all shortcuts specified with md-shortcuts attributes in the fixture.
      // `shortcuts` will look something like this:
      // [
      //   [ 'mod+b' ],
      //   [ 'mod+i' ],
      //   [ 'mod+k' ]
      // ]
      shortcutElements = $('.edit-note .js-md')
        .map(function getShortcutsFromToolbarBtn() {
          const mdShortcuts = $(this).data('md-shortcuts');

          // jQuery.map() automatically unwraps arrays, so we
          // have to double wrap the array to counteract this
          return mdShortcuts ? [mdShortcuts] : undefined;
        })
        .get();
    });

    describe('initMarkdownEditorShortcuts', () => {
      let $textarea;
      let localMousetrapInstance;

      beforeEach(() => {
        $textarea = $('.edit-note textarea');
        Shortcuts.initMarkdownEditorShortcuts($textarea);
        localMousetrapInstance = $textarea.data(LOCAL_MOUSETRAP_DATA_KEY);
      });

      it('attaches a Mousetrap handler for every markdown shortcut specified with md-shortcuts', () => {
        const expectedCalls = shortcutElements.map((s) => [s, expect.any(Function)]);

        expect(Mousetrap.prototype.bind.mock.calls).toEqual(expectedCalls);
      });

      it('attaches a stopCallback that allows each markdown shortcut specified with md-shortcuts', () => {
        flatten(shortcutElements).forEach((s) => {
          expect(
            localMousetrapInstance.stopCallback.call(localMousetrapInstance, null, null, s),
          ).toBe(false);
        });
      });
    });

    describe('removeMarkdownEditorShortcuts', () => {
      it('does nothing if initMarkdownEditorShortcuts was not previous called', () => {
        Shortcuts.removeMarkdownEditorShortcuts($('.edit-note textarea'));

        expect(Mousetrap.prototype.unbind.mock.calls).toEqual([]);
      });

      it('removes Mousetrap handlers for every markdown shortcut specified with md-shortcuts', () => {
        Shortcuts.initMarkdownEditorShortcuts($('.edit-note textarea'));
        Shortcuts.removeMarkdownEditorShortcuts($('.edit-note textarea'));

        const expectedCalls = shortcutElements.map((s) => [s]);

        expect(Mousetrap.prototype.unbind.mock.calls).toEqual(expectedCalls);
      });
    });
  });

  describe('focusSearch', () => {
    let event;

    beforeEach(() => {
      event = new KeyboardEvent('keydown', { cancelable: true });
      Shortcuts.focusSearch(event);
    });

    it('clicks the super sidebar search button', () => {
      expect(HTMLElement.prototype.click).toHaveBeenCalled();
      const thisArg = HTMLElement.prototype.click.mock.contexts[0];
      expect(thisArg.id).toBe('super-sidebar-search');
    });

    it('cancels the default behaviour of the event', () => {
      expect(event.defaultPrevented).toBe(true);
    });
  });

  describe('adding shortcuts', () => {
    it('add calls Mousetrap.bind correctly', () => {
      const mockCommand = { defaultKeys: ['m'] };
      const mockCallback = () => {};

      shortcuts.add(mockCommand, mockCallback);

      expect(Mousetrap.prototype.bind).toHaveBeenCalledTimes(1);
      const [callArguments] = Mousetrap.prototype.bind.mock.calls;
      expect(callArguments[0]).toEqual(mockCommand.defaultKeys);
      expect(callArguments[1]).toBe(mockCallback);
    });

    it('addAll calls Mousetrap.bind correctly', () => {
      const mockCommandsAndCallbacks = [
        [{ defaultKeys: ['1'] }, () => {}],
        [{ defaultKeys: ['2'] }, () => {}],
      ];

      shortcuts.addAll(mockCommandsAndCallbacks);

      expect(Mousetrap.prototype.bind).toHaveBeenCalledTimes(mockCommandsAndCallbacks.length);
      const { calls } = Mousetrap.prototype.bind.mock;

      mockCommandsAndCallbacks.forEach(([mockCommand, mockCallback], i) => {
        expect(calls[i][0]).toEqual(mockCommand.defaultKeys);
        expect(calls[i][1]).toBe(mockCallback);
      });
    });
  });

  describe('addExtension', () => {
    it('instantiates the given extension', () => {
      const MockExtension = jest.fn();

      const returnValue = shortcuts.addExtension(MockExtension, ['foo']);

      expect(MockExtension).toHaveBeenCalledTimes(1);
      expect(MockExtension).toHaveBeenCalledWith(shortcuts, 'foo');
      expect(returnValue).toBe(MockExtension.mock.instances[0]);
    });

    it('instantiates declared dependencies', () => {
      const MockDependency = jest.fn();
      const MockExtension = jest.fn();

      MockExtension.dependencies = [MockDependency];

      const returnValue = shortcuts.addExtension(MockExtension, ['foo']);

      expect(MockDependency).toHaveBeenCalledTimes(1);
      expect(MockDependency.mock.instances).toHaveLength(1);
      expect(MockDependency).toHaveBeenCalledWith(shortcuts);

      expect(returnValue).toBe(MockExtension.mock.instances[0]);
    });

    it('does not instantiate an extension more than once', () => {
      const MockExtension = jest.fn();

      const returnValue = shortcuts.addExtension(MockExtension, ['foo']);
      const secondReturnValue = shortcuts.addExtension(MockExtension, ['bar']);

      expect(MockExtension).toHaveBeenCalledTimes(1);
      expect(MockExtension).toHaveBeenCalledWith(shortcuts, 'foo');
      expect(returnValue).toBe(MockExtension.mock.instances[0]);
      expect(secondReturnValue).toBe(MockExtension.mock.instances[0]);
    });

    it('allows extensions to redundantly depend on Shortcuts', () => {
      const MockExtension = jest.fn();
      MockExtension.dependencies = [Shortcuts];

      shortcuts.addExtension(MockExtension);

      expect(MockExtension).toHaveBeenCalledTimes(1);
      expect(MockExtension).toHaveBeenCalledWith(shortcuts);

      // Ensure it wasn't instantiated
      expect(shortcuts.extensions.has(Shortcuts)).toBe(false);
    });

    it('allows extensions to incorrectly depend on themselves', () => {
      const A = jest.fn();
      A.dependencies = [A];
      shortcuts.addExtension(A);
      expect(A).toHaveBeenCalledTimes(1);
      expect(A).toHaveBeenCalledWith(shortcuts);
    });

    it('handles extensions with circular dependencies', () => {
      const A = jest.fn();
      const B = jest.fn();
      const C = jest.fn();

      A.dependencies = [B];
      B.dependencies = [C];
      C.dependencies = [A];

      shortcuts.addExtension(A);

      expect(A).toHaveBeenCalledTimes(1);
      expect(B).toHaveBeenCalledTimes(1);
      expect(C).toHaveBeenCalledTimes(1);
    });

    it('handles complex (diamond) dependency graphs', () => {
      const X = jest.fn();
      const A = jest.fn();
      const C = jest.fn();
      const D = jest.fn();
      const E = jest.fn();

      // Form this dependency graph:
      //
      // X ───► A ───► C
      // │             ▲
      // └────► D ─────┘
      //        │
      //        └────► E
      X.dependencies = [A, D];
      A.dependencies = [C];
      D.dependencies = [C, E];

      shortcuts.addExtension(X);

      expect(X).toHaveBeenCalledTimes(1);
      expect(A).toHaveBeenCalledTimes(1);
      expect(C).toHaveBeenCalledTimes(1);
      expect(D).toHaveBeenCalledTimes(1);
      expect(E).toHaveBeenCalledTimes(1);
    });
  });
});