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

shortcuts.js « shortcuts « behaviors « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e05694c0907bddd950a7af9a45881ce4913ec36e (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
import $ from 'jquery';
import { flatten } from 'lodash';
import Vue from 'vue';
import { Mousetrap, addStopCallback } from '~/lib/mousetrap';
import { getCookie, setCookie, parseBoolean } from '~/lib/utils/common_utils';

import findAndFollowLink from '~/lib/utils/navigation_utility';
import { refreshCurrentPage, visitUrl } from '~/lib/utils/url_utility';
import {
  keysFor,
  TOGGLE_KEYBOARD_SHORTCUTS_DIALOG,
  START_SEARCH,
  FOCUS_FILTER_BAR,
  TOGGLE_PERFORMANCE_BAR,
  HIDE_APPEARING_CONTENT,
  TOGGLE_CANARY,
  TOGGLE_MARKDOWN_PREVIEW,
  GO_TO_YOUR_TODO_LIST,
  GO_TO_ACTIVITY_FEED,
  GO_TO_YOUR_ISSUES,
  GO_TO_YOUR_MERGE_REQUESTS,
  GO_TO_YOUR_PROJECTS,
  GO_TO_YOUR_GROUPS,
  GO_TO_MILESTONE_LIST,
  GO_TO_YOUR_SNIPPETS,
  GO_TO_PROJECT_FIND_FILE,
  GO_TO_YOUR_REVIEW_REQUESTS,
} from './keybindings';
import { disableShortcuts, shouldDisableShortcuts } from './shortcuts_toggle';

/**
 * The key used to save and fetch the local Mousetrap instance
 * attached to a `<textarea>` element using `jQuery.data`
 */
export const LOCAL_MOUSETRAP_DATA_KEY = 'local-mousetrap-instance';

/**
 * Gets a mapping of toolbar button => keyboard shortcuts
 * associated to the given markdown editor `<textarea>` element
 *
 * @param {HTMLTextAreaElement} $textarea The jQuery-wrapped `<textarea>`
 * element to extract keyboard shortcuts from
 *
 * @returns A Map with keys that are jQuery-wrapped toolbar buttons
 * (i.e. `$toolbarBtn`) and values that are arrays of string
 * keyboard shortcuts (e.g. `['command+k', 'ctrl+k]`).
 */
function getToolbarBtnToShortcutsMap($textarea) {
  const $allToolbarBtns = $textarea.closest('.md-area').find('.js-md');
  const map = new Map();

  $allToolbarBtns.each(function attachToolbarBtnHandler() {
    const $toolbarBtn = $(this);
    const keyboardShortcuts = $toolbarBtn.data('md-shortcuts');

    if (keyboardShortcuts?.length) {
      map.set($toolbarBtn, keyboardShortcuts);
    }
  });

  return map;
}

export default class Shortcuts {
  constructor() {
    if (process.env.NODE_ENV !== 'production' && this.constructor !== Shortcuts) {
      // eslint-disable-next-line @gitlab/require-i18n-strings
      throw new Error('Shortcuts cannot be subclassed.');
    }

    this.extensions = new Map();
    this.onToggleHelp = this.onToggleHelp.bind(this);
    this.helpModalElement = null;
    this.helpModalVueInstance = null;

    this.addAll([
      [TOGGLE_KEYBOARD_SHORTCUTS_DIALOG, this.onToggleHelp],
      [START_SEARCH, Shortcuts.focusSearch],
      [FOCUS_FILTER_BAR, this.focusFilter.bind(this)],
      [TOGGLE_PERFORMANCE_BAR, Shortcuts.onTogglePerfBar],
      [HIDE_APPEARING_CONTENT, Shortcuts.hideAppearingContent],
      [TOGGLE_CANARY, Shortcuts.onToggleCanary],

      [GO_TO_YOUR_TODO_LIST, () => findAndFollowLink('.shortcuts-todos')],
      [GO_TO_ACTIVITY_FEED, () => findAndFollowLink('.dashboard-shortcuts-activity')],
      [GO_TO_YOUR_ISSUES, () => findAndFollowLink('.dashboard-shortcuts-issues')],
      [GO_TO_YOUR_MERGE_REQUESTS, () => findAndFollowLink('.dashboard-shortcuts-merge_requests')],
      [GO_TO_YOUR_REVIEW_REQUESTS, () => findAndFollowLink('.dashboard-shortcuts-review_requests')],
      [GO_TO_YOUR_PROJECTS, () => findAndFollowLink('.dashboard-shortcuts-projects')],
      [GO_TO_YOUR_GROUPS, () => findAndFollowLink('.dashboard-shortcuts-groups')],
      [GO_TO_MILESTONE_LIST, () => findAndFollowLink('.dashboard-shortcuts-milestones')],
      [GO_TO_YOUR_SNIPPETS, () => findAndFollowLink('.dashboard-shortcuts-snippets')],

      [TOGGLE_MARKDOWN_PREVIEW, Shortcuts.toggleMarkdownPreview],
    ]);

    addStopCallback((e, element, combo) =>
      keysFor(TOGGLE_MARKDOWN_PREVIEW).includes(combo) ? false : undefined,
    );

    const findFileURL = document.body.dataset.findFile;
    if (typeof findFileURL !== 'undefined' && findFileURL !== null) {
      this.add(GO_TO_PROJECT_FIND_FILE, () => {
        visitUrl(findFileURL);
      });
    }

    $(document).on('click', '.js-shortcuts-modal-trigger', this.onToggleHelp);

    if (shouldDisableShortcuts()) {
      disableShortcuts();
    }
  }

  /**
   * Instantiate a legacy shortcut extension class.
   *
   * NOTE: The preferred approach for adding shortcuts is described in
   * https://docs.gitlab.com/ee/development/fe_guide/keyboard_shortcuts.html.
   * This method is only for existing legacy shortcut classes.
   *
   * A shortcut extension class packages up several shortcuts and behaviors for
   * a page or set of pages. They are considered legacy because they usually do
   * not follow modern best practices. For instance, they may hook into the UI
   * in brittle ways, e.g.. querySelectors.
   *
   * Extension classes can declare dependencies on other shortcut extension
   * classes by listing them in a static `dependencies` property. This is
   * essentially a reimplementation of the previous subclassing approach, but
   * with idempotency: a shortcut extension class can now only be added at most
   * one time.
   *
   * Extension classes are instantiated and given the Shortcuts singleton
   * instance as their first argument. If the class constructor needs
   * additional arguments, pass them via the second argument as an array.
   *
   * See https://gitlab.com/gitlab-org/gitlab/-/issues/392845 for more context.
   *
   * @param {Function} Extension The extension class to add/instantiate.
   * @param {Array} [args] A list of additional args to pass to the extension
   *     class constructor.
   * @param {Set} [extensionsCurrentlyLoading] For internal use only. Do not
   *     use.
   * @returns The instantiated shortcut extension class.
   */
  addExtension(Extension, args = [], extensionsCurrentlyLoading = new Set()) {
    extensionsCurrentlyLoading.add(Extension);

    let instance = this.extensions.get(Extension);
    if (!instance) {
      for (const Dep of Extension.dependencies ?? []) {
        if (extensionsCurrentlyLoading.has(Dep) || Dep === Shortcuts) {
          // We've encountered a circular dependency, so stop recursing.
          // eslint-disable-next-line no-continue
          continue;
        }

        extensionsCurrentlyLoading.add(Dep);

        this.addExtension(Dep, [], extensionsCurrentlyLoading);
      }

      instance = new Extension(this, ...args);
      this.extensions.set(Extension, instance);
    }

    extensionsCurrentlyLoading.delete(Extension);
    return instance;
  }

  /**
   * Bind the keyboard shortcut(s) defined by the given command to the given
   * callback.
   *
   * @param {Object} command A command object.
   * @param {Function} callback The callback to call when the command's key
   *     combo has been pressed.
   * @returns {void}
   */
  // eslint-disable-next-line class-methods-use-this
  add(command, callback) {
    Mousetrap.bind(keysFor(command), callback);
  }

  /**
   * Bind the keyboard shortcut(s) defined by the given commands to the given
   * callbacks.
   *
   * @param {Array<[Object, Function]>} commandsAndCallbacks An array of
   *     command/callback pairs.
   * @returns {void}
   */
  addAll(commandsAndCallbacks) {
    commandsAndCallbacks.forEach((commandAndCallback) => this.add(...commandAndCallback));
  }

  onToggleHelp(e) {
    if (e?.preventDefault) {
      e.preventDefault();
    }

    if (this.helpModalElement && this.helpModalVueInstance) {
      this.helpModalVueInstance.$destroy();
      this.helpModalElement.remove();
      this.helpModalElement = null;
      this.helpModalVueInstance = null;
    } else {
      this.helpModalElement = document.createElement('div');
      document.body.append(this.helpModalElement);

      this.helpModalVueInstance = new Vue({
        el: this.helpModalElement,
        components: {
          ShortcutsHelp: () => import('./shortcuts_help.vue'),
        },
        render: (createElement) => {
          return createElement('shortcuts-help', {
            on: {
              hidden: this.onToggleHelp,
            },
          });
        },
      });
    }
  }

  static onTogglePerfBar(e) {
    e.preventDefault();
    const performanceBarCookieName = 'perf_bar_enabled';
    if (parseBoolean(getCookie(performanceBarCookieName))) {
      setCookie(performanceBarCookieName, 'false', { path: '/' });
    } else {
      setCookie(performanceBarCookieName, 'true', { path: '/' });
    }
    refreshCurrentPage();
  }

  static onToggleCanary(e) {
    e.preventDefault();
    const canaryCookieName = 'gitlab_canary';
    const currentValue = parseBoolean(getCookie(canaryCookieName));
    setCookie(canaryCookieName, (!currentValue).toString(), { expires: 365, path: '/' });
    refreshCurrentPage();
  }

  static toggleMarkdownPreview(e) {
    $(document).triggerHandler('markdown-preview:toggle', [e]);
  }

  focusFilter(e) {
    if (!this.filterInput) {
      this.filterInput = $('input[type=search]', '.nav-controls');
    }
    this.filterInput.focus();
    e.preventDefault();
  }

  static focusSearch(e) {
    document.querySelector('#super-sidebar-search')?.click();

    if (e.preventDefault) {
      e.preventDefault();
    }
  }

  static hideAppearingContent(e) {
    const elements = document.querySelectorAll('.tooltip, .popover');

    elements.forEach((element) => {
      element.style.display = 'none';
    });

    if (e.preventDefault) {
      e.preventDefault();
    }
  }

  /**
   * Initializes markdown editor shortcuts on the provided `<textarea>` element
   *
   * @param {JQuery} $textarea The jQuery-wrapped `<textarea>` element
   * where markdown shortcuts should be enabled
   * @param {Function} handler The handler to call when a
   * keyboard shortcut is pressed inside the markdown `<textarea>`
   */
  static initMarkdownEditorShortcuts($textarea, handler) {
    const toolbarBtnToShortcutsMap = getToolbarBtnToShortcutsMap($textarea);

    const localMousetrap = new Mousetrap($textarea[0]);

    // Save a reference to the local mousetrap instance on the <textarea>
    // so that it can be retrieved when unbinding shortcut handlers
    $textarea.data(LOCAL_MOUSETRAP_DATA_KEY, localMousetrap);

    toolbarBtnToShortcutsMap.forEach((keyboardShortcuts, $toolbarBtn) => {
      localMousetrap.bind(keyboardShortcuts, (e) => {
        e.preventDefault();

        handler($toolbarBtn);
      });
    });

    // Get an array of all shortcut strings that have been added above
    const allShortcuts = flatten([...toolbarBtnToShortcutsMap.values()]);

    const originalStopCallback = Mousetrap.prototype.stopCallback;
    localMousetrap.stopCallback = function newStopCallback(e, element, combo) {
      if (allShortcuts.includes(combo)) {
        return false;
      }

      return originalStopCallback.call(this, e, element, combo);
    };
  }

  /**
   * Removes markdown editor shortcut handlers originally attached
   * with `initMarkdownEditorShortcuts`.
   *
   * Note: it is safe to call this function even if `initMarkdownEditorShortcuts`
   * has _not_ yet been called on the given `<textarea>`.
   *
   * @param {JQuery} $textarea The jQuery-wrapped `<textarea>`
   * to remove shortcut handlers from
   */
  static removeMarkdownEditorShortcuts($textarea) {
    const localMousetrap = $textarea.data(LOCAL_MOUSETRAP_DATA_KEY);

    if (localMousetrap) {
      getToolbarBtnToShortcutsMap($textarea).forEach((keyboardShortcuts) => {
        localMousetrap.unbind(keyboardShortcuts);
      });
    }
  }
}