create_merge_request_dropdown.js 15.9 KB
Newer Older
1
/* eslint-disable no-new */
P
Phil Hughes 已提交
2
import _ from 'underscore';
3
import axios from './lib/utils/axios_utils';
P
Phil Hughes 已提交
4
import Flash from './flash';
5 6
import DropLab from './droplab/drop_lab';
import ISetter from './droplab/plugins/input_setter';
7
import { __, sprintf } from './locale';
8 9 10 11 12 13
import {
  init as initConfidentialMergeRequest,
  isConfidentialIssue,
  canCreateConfidentialMergeRequest,
} from './confidential_merge_request';
import confidentialMergeRequestState from './confidential_merge_request/state';
14 15 16 17 18 19 20

// Todo: Remove this when fixing issue in input_setter plugin
const InputSetter = Object.assign({}, ISetter);

const CREATE_MERGE_REQUEST = 'create-mr';
const CREATE_BRANCH = 'create-branch';

21 22 23 24 25 26 27 28 29 30 31
function createEndpoint(projectPath, endpoint) {
  if (canCreateConfidentialMergeRequest()) {
    return endpoint.replace(
      projectPath,
      confidentialMergeRequestState.selectedProject.pathWithNamespace,
    );
  }

  return endpoint;
}

32 33 34
export default class CreateMergeRequestDropdown {
  constructor(wrapperEl) {
    this.wrapperEl = wrapperEl;
35 36 37
    this.availableButton = this.wrapperEl.querySelector('.available');
    this.branchInput = this.wrapperEl.querySelector('.js-branch-name');
    this.branchMessage = this.wrapperEl.querySelector('.js-branch-message');
38
    this.createMergeRequestButton = this.wrapperEl.querySelector('.js-create-merge-request');
39
    this.createTargetButton = this.wrapperEl.querySelector('.js-create-target');
40
    this.dropdownList = this.wrapperEl.querySelector('.dropdown-menu');
41 42 43
    this.dropdownToggle = this.wrapperEl.querySelector('.js-dropdown-toggle');
    this.refInput = this.wrapperEl.querySelector('.js-ref');
    this.refMessage = this.wrapperEl.querySelector('.js-ref-message');
44 45 46 47
    this.unavailableButton = this.wrapperEl.querySelector('.unavailable');
    this.unavailableButtonArrow = this.unavailableButton.querySelector('.fa');
    this.unavailableButtonText = this.unavailableButton.querySelector('.text');

48 49
    this.branchCreated = false;
    this.branchIsValid = true;
50
    this.canCreatePath = this.wrapperEl.dataset.canCreatePath;
51
    this.createBranchPath = this.wrapperEl.dataset.createBranchPath;
52 53
    this.createMrPath = this.wrapperEl.dataset.createMrPath;
    this.droplabInitialized = false;
54
    this.isCreatingBranch = false;
55
    this.isCreatingMergeRequest = false;
56
    this.isGettingRef = false;
57
    this.mergeRequestCreated = false;
58 59 60 61
    this.refDebounce = _.debounce((value, target) => this.getRef(value, target), 500);
    this.refIsValid = true;
    this.refsPath = this.wrapperEl.dataset.refsPath;
    this.suggestedRef = this.refInput.value;
62 63
    this.projectPath = this.wrapperEl.dataset.projectPath;
    this.projectId = this.wrapperEl.dataset.projectId;
64

65 66 67 68 69 70 71 72 73 74 75 76 77
    // These regexps are used to replace
    // a backend generated new branch name and its source (ref)
    // with user's inputs.
    this.regexps = {
      branch: {
        createBranchPath: new RegExp('(branch_name=)(.+?)(?=&issue)'),
        createMrPath: new RegExp('(branch_name=)(.+?)(?=&ref)'),
      },
      ref: {
        createBranchPath: new RegExp('(ref=)(.+?)$'),
        createMrPath: new RegExp('(ref=)(.+?)$'),
      },
    };
78

79
    this.init();
80 81 82 83 84 85 86 87

    if (isConfidentialIssue()) {
      this.createMergeRequestButton.setAttribute(
        'data-dropdown-trigger',
        '#create-merge-request-dropdown',
      );
      initConfidentialMergeRequest();
    }
88 89 90
  }

  available() {
C
Clement Ho 已提交
91 92
    this.availableButton.classList.remove('hidden');
    this.unavailableButton.classList.add('hidden');
93 94
  }

95
  bindEvents() {
96 97 98 99 100 101 102 103
    this.createMergeRequestButton.addEventListener(
      'click',
      this.onClickCreateMergeRequestButton.bind(this),
    );
    this.createTargetButton.addEventListener(
      'click',
      this.onClickCreateMergeRequestButton.bind(this),
    );
104 105 106 107
    this.branchInput.addEventListener('keyup', this.onChangeInput.bind(this));
    this.dropdownToggle.addEventListener('click', this.onClickSetFocusOnBranchNameInput.bind(this));
    this.refInput.addEventListener('keyup', this.onChangeInput.bind(this));
    this.refInput.addEventListener('keydown', CreateMergeRequestDropdown.processTab.bind(this));
108 109 110
  }

  checkAbilityToCreateBranch() {
111 112
    this.setUnavailableButtonState();

113 114
    axios
      .get(this.canCreatePath)
115 116 117 118 119 120
      .then(({ data }) => {
        this.setUnavailableButtonState(false);

        if (data.can_create_branch) {
          this.available();
          this.enable();
121
          this.updateBranchName(data.suggested_branch_name);
122 123 124 125 126 127

          if (!this.droplabInitialized) {
            this.droplabInitialized = true;
            this.initDroplab();
            this.bindEvents();
          }
128
        } else {
129
          this.hide();
130
        }
131 132 133 134
      })
      .catch(() => {
        this.unavailable();
        this.disable();
135
        Flash(__('Failed to check related branches.'));
136
      });
137 138
  }

139
  createBranch() {
140 141
    this.isCreatingBranch = true;

142
    return axios
143 144 145
      .post(createEndpoint(this.projectPath, this.createBranchPath), {
        confidential_issue_project_id: canCreateConfidentialMergeRequest() ? this.projectId : null,
      })
146 147 148 149
      .then(({ data }) => {
        this.branchCreated = true;
        window.location.href = data.url;
      })
150
      .catch(() => Flash(__('Failed to create a branch for this issue. Please try again.')));
151
  }
152

153
  createMergeRequest() {
154 155
    this.isCreatingMergeRequest = true;

156
    return axios
157 158 159 160 161
      .post(this.createMrPath, {
        target_project_id: canCreateConfidentialMergeRequest()
          ? confidentialMergeRequestState.selectedProject.id
          : null,
      })
162 163 164 165
      .then(({ data }) => {
        this.mergeRequestCreated = true;
        window.location.href = data.url;
      })
166
      .catch(() => Flash(__('Failed to create Merge Request. Please try again.')));
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
  }

  disable() {
    this.disableCreateAction();

    this.dropdownToggle.classList.add('disabled');
    this.dropdownToggle.setAttribute('disabled', 'disabled');
  }

  disableCreateAction() {
    this.createMergeRequestButton.classList.add('disabled');
    this.createMergeRequestButton.setAttribute('disabled', 'disabled');

    this.createTargetButton.classList.add('disabled');
    this.createTargetButton.setAttribute('disabled', 'disabled');
  }

  enable() {
185
    if (isConfidentialIssue() && !canCreateConfidentialMergeRequest()) return;
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    this.createMergeRequestButton.classList.remove('disabled');
    this.createMergeRequestButton.removeAttribute('disabled');

    this.createTargetButton.classList.remove('disabled');
    this.createTargetButton.removeAttribute('disabled');

    this.dropdownToggle.classList.remove('disabled');
    this.dropdownToggle.removeAttribute('disabled');
  }

  static findByValue(objects, ref, returnFirstMatch = false) {
    if (!objects || !objects.length) return false;
    if (objects.indexOf(ref) > -1) return ref;
    if (returnFirstMatch) return objects.find(item => new RegExp(`^${ref}`).test(item));

    return false;
203 204 205 206
  }

  getDroplabConfig() {
    return {
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
      addActiveClassToDropdownButton: true,
      InputSetter: [
        {
          input: this.createMergeRequestButton,
          valueAttribute: 'data-value',
          inputAttribute: 'data-action',
        },
        {
          input: this.createMergeRequestButton,
          valueAttribute: 'data-text',
        },
        {
          input: this.createTargetButton,
          valueAttribute: 'data-value',
          inputAttribute: 'data-action',
        },
        {
          input: this.createTargetButton,
          valueAttribute: 'data-text',
        },
      ],
228
      hideOnClick: false,
229 230 231
    };
  }

232 233 234 235 236 237 238 239 240 241
  static getInputSelectedText(input) {
    const start = input.selectionStart;
    const end = input.selectionEnd;

    return input.value.substr(start, end - start);
  }

  getRef(ref, target = 'all') {
    if (!ref) return false;

242
    return axios
243
      .get(`${createEndpoint(this.projectPath, this.refsPath)}${encodeURIComponent(ref)}`)
244 245 246 247 248 249 250 251
      .then(({ data }) => {
        const branches = data[Object.keys(data)[0]];
        const tags = data[Object.keys(data)[1]];
        let result;

        if (target === 'branch') {
          result = CreateMergeRequestDropdown.findByValue(branches, ref);
        } else {
252 253
          result =
            CreateMergeRequestDropdown.findByValue(branches, ref, true) ||
254 255 256
            CreateMergeRequestDropdown.findByValue(tags, ref, true);
          this.suggestedRef = result;
        }
257

258
        this.isGettingRef = false;
259

260 261 262 263 264
        return this.updateInputState(target, ref, result);
      })
      .catch(() => {
        this.unavailable();
        this.disable();
265
        new Flash(__('Failed to get ref.'));
266

267 268 269 270
        this.isGettingRef = false;

        return false;
      });
271 272 273 274 275 276 277 278 279 280
  }

  getTargetData(target) {
    return {
      input: this[`${target}Input`],
      message: this[`${target}Message`],
    };
  }

  hide() {
C
Clement Ho 已提交
281
    this.wrapperEl.classList.add('hidden');
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
  }

  init() {
    this.checkAbilityToCreateBranch();
  }

  initDroplab() {
    this.droplab = new DropLab();

    this.droplab.init(
      this.dropdownToggle,
      this.dropdownList,
      [InputSetter],
      this.getDroplabConfig(),
    );
  }

  inputsAreValid() {
    return this.branchIsValid && this.refIsValid;
301 302 303
  }

  isBusy() {
304 305
    return (
      this.isCreatingMergeRequest ||
306 307
      this.mergeRequestCreated ||
      this.isCreatingBranch ||
308
      this.branchCreated ||
309 310
      this.isGettingRef
    );
311 312
  }

313
  onChangeInput(event) {
314
    this.disable();
315 316 317
    let target;
    let value;

318
    if (event.target === this.branchInput) {
319
      target = 'branch';
320
      ({ value } = this.branchInput);
321
    } else if (event.target === this.refInput) {
322
      target = 'ref';
323 324
      value =
        event.target.value.slice(0, event.target.selectionStart) +
325
        event.target.value.slice(event.target.selectionEnd);
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
    } else {
      return false;
    }

    if (this.isGettingRef) return false;

    // `ENTER` key submits the data.
    if (event.keyCode === 13 && this.inputsAreValid()) {
      event.preventDefault();
      return this.createMergeRequestButton.click();
    }

    // If the input is empty, use the original value generated by the backend.
    if (!value) {
      this.createBranchPath = this.wrapperEl.dataset.createBranchPath;
      this.createMrPath = this.wrapperEl.dataset.createMrPath;

      if (target === 'branch') {
        this.branchIsValid = true;
      } else {
        this.refIsValid = true;
      }

      this.enable();
      this.showAvailableMessage(target);
      return true;
    }

    this.showCheckingMessage(target);
    this.refDebounce(value, target);

    return true;
  }

  onClickCreateMergeRequestButton(event) {
361
    let xhr = null;
362
    event.preventDefault();
363

364 365 366 367 368 369
    if (isConfidentialIssue() && !event.target.classList.contains('js-create-target')) {
      this.droplab.hooks.forEach(hook => hook.list.toggle());

      return;
    }

370 371 372 373
    if (this.isBusy()) {
      return;
    }

374
    if (event.target.dataset.action === CREATE_MERGE_REQUEST) {
375
      xhr = this.createMergeRequest();
376
    } else if (event.target.dataset.action === CREATE_BRANCH) {
377 378 379
      xhr = this.createBranch();
    }

380
    xhr.catch(() => {
381 382 383
      this.isCreatingMergeRequest = false;
      this.isCreatingBranch = false;

384 385
      this.enable();
    });
386 387 388 389

    this.disable();
  }

390 391
  onClickSetFocusOnBranchNameInput() {
    this.branchInput.focus();
392 393
  }

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
  // `TAB` autocompletes the source.
  static processTab(event) {
    if (event.keyCode !== 9 || this.isGettingRef) return;

    const selectedText = CreateMergeRequestDropdown.getInputSelectedText(this.refInput);

    // if nothing selected, we don't need to autocomplete anything. Do the default TAB action.
    // If a user manually selected text, don't autocomplete anything. Do the default TAB action.
    if (!selectedText || this.refInput.dataset.value === this.suggestedRef) return;

    event.preventDefault();
    window.getSelection().removeAllRanges();
  }

  removeMessage(target) {
    const { input, message } = this.getTargetData(target);
    const inputClasses = ['gl-field-error-outline', 'gl-field-success-outline'];
411
    const messageClasses = ['text-muted', 'text-danger', 'text-success'];
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

    inputClasses.forEach(cssClass => input.classList.remove(cssClass));
    messageClasses.forEach(cssClass => message.classList.remove(cssClass));
    message.style.display = 'none';
  }

  setUnavailableButtonState(isLoading = true) {
    if (isLoading) {
      this.unavailableButtonArrow.classList.add('fa-spin');
      this.unavailableButtonArrow.classList.add('fa-spinner');
      this.unavailableButtonArrow.classList.remove('fa-exclamation-triangle');
      this.unavailableButtonText.textContent = __('Checking branch availability...');
    } else {
      this.unavailableButtonArrow.classList.remove('fa-spin');
      this.unavailableButtonArrow.classList.remove('fa-spinner');
      this.unavailableButtonArrow.classList.add('fa-exclamation-triangle');
      this.unavailableButtonText.textContent = __('New branch unavailable');
    }
  }

  showAvailableMessage(target) {
    const { input, message } = this.getTargetData(target);
    const text = target === 'branch' ? __('Branch name') : __('Source');

    this.removeMessage(target);
    input.classList.add('gl-field-success-outline');
438
    message.classList.add('text-success');
439 440 441 442 443 444 445 446 447
    message.textContent = sprintf(__('%{text} is available'), { text });
    message.style.display = 'inline-block';
  }

  showCheckingMessage(target) {
    const { message } = this.getTargetData(target);
    const text = target === 'branch' ? __('branch name') : __('source');

    this.removeMessage(target);
448
    message.classList.add('text-muted');
449 450 451 452 453 454
    message.textContent = sprintf(__('Checking %{text} availability…'), { text });
    message.style.display = 'inline-block';
  }

  showNotAvailableMessage(target) {
    const { input, message } = this.getTargetData(target);
455 456
    const text =
      target === 'branch' ? __('Branch is already taken') : __('Source is not available');
457 458 459

    this.removeMessage(target);
    input.classList.add('gl-field-error-outline');
460
    message.classList.add('text-danger');
461 462 463 464 465
    message.textContent = text;
    message.style.display = 'inline-block';
  }

  unavailable() {
C
Clement Ho 已提交
466 467
    this.availableButton.classList.add('hidden');
    this.unavailableButton.classList.remove('hidden');
468 469
  }

470 471 472 473 474
  updateBranchName(suggestedBranchName) {
    this.branchInput.value = suggestedBranchName;
    this.updateCreatePaths('branch', suggestedBranchName);
  }

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  updateInputState(target, ref, result) {
    // target - 'branch' or 'ref' - which the input field we are searching a ref for.
    // ref - string - what a user typed.
    // result - string - what has been found on backend.

    // If a found branch equals exact the same text a user typed,
    // that means a new branch cannot be created as it already exists.
    if (ref === result) {
      if (target === 'branch') {
        this.branchIsValid = false;
        this.showNotAvailableMessage('branch');
      } else {
        this.refIsValid = true;
        this.refInput.dataset.value = ref;
        this.showAvailableMessage('ref');
490
        this.updateCreatePaths(target, ref);
491 492 493 494
      }
    } else if (target === 'branch') {
      this.branchIsValid = true;
      this.showAvailableMessage('branch');
495
      this.updateCreatePaths(target, ref);
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    } else {
      this.refIsValid = false;
      this.refInput.dataset.value = ref;
      this.disableCreateAction();
      this.showNotAvailableMessage('ref');

      // Show ref hint.
      if (result) {
        this.refInput.value = result;
        this.refInput.setSelectionRange(ref.length, result.length);
      }
    }

    if (this.inputsAreValid()) {
      this.enable();
    } else {
      this.disableCreateAction();
    }
514
  }
515 516 517 518

  // target - 'branch' or 'ref'
  // ref - string - the new value to use as branch or ref
  updateCreatePaths(target, ref) {
519
    const pathReplacement = `$1${encodeURIComponent(ref)}`;
520

521 522 523 524 525 526 527 528
    this.createBranchPath = this.createBranchPath.replace(
      this.regexps[target].createBranchPath,
      pathReplacement,
    );
    this.createMrPath = this.createMrPath.replace(
      this.regexps[target].createMrPath,
      pathReplacement,
    );
529
  }
530
}