summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/project_select_combo_button.js
blob: f799d9d619ac09f1c25262127bc4042fef91e651 (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
import AccessorUtilities from './lib/utils/accessor';

export default class ProjectSelectComboButton {
  constructor(select) {
    this.projectSelectInput = $(select);
    this.newItemBtn = $('.new-project-item-link');
    this.newItemBtnBaseText = this.newItemBtn.data('label');
    this.itemType = this.deriveItemTypeFromLabel();
    this.groupId = this.projectSelectInput.data('groupId');

    this.bindEvents();
    this.initLocalStorage();
  }

  bindEvents() {
    this.projectSelectInput.siblings('.new-project-item-select-button')
      .on('click', this.openDropdown);

    this.projectSelectInput.on('change', () => this.selectProject());
  }

  initLocalStorage() {
    const localStorageIsSafe = AccessorUtilities.isLocalStorageAccessSafe();

    if (localStorageIsSafe) {
      const itemTypeKebabed = this.newItemBtnBaseText.toLowerCase().split(' ').join('-');

      this.localStorageKey = ['group', this.groupId, itemTypeKebabed, 'recent-project'].join('-');
      this.setBtnTextFromLocalStorage();
    }
  }

  openDropdown() {
    $(this).siblings('.project-item-select').select2('open');
  }

  selectProject() {
    const selectedProjectData = JSON.parse(this.projectSelectInput.val());
    const projectUrl = `${selectedProjectData.url}/${this.projectSelectInput.data('relativePath')}`;
    const projectName = selectedProjectData.name;

    const projectMeta = {
      url: projectUrl,
      name: projectName,
    };

    this.setNewItemBtnAttributes(projectMeta);
    this.setProjectInLocalStorage(projectMeta);
  }

  setBtnTextFromLocalStorage() {
    const cachedProjectData = this.getProjectFromLocalStorage();

    this.setNewItemBtnAttributes(cachedProjectData);
  }

  setNewItemBtnAttributes(project) {
    if (project) {
      this.newItemBtn.attr('href', project.url);
      this.newItemBtn.text(`${this.newItemBtnBaseText} in ${project.name}`);
      this.newItemBtn.enable();
    } else {
      this.newItemBtn.text(`Select project to create ${this.itemType}`);
      this.newItemBtn.disable();
    }
  }

  deriveItemTypeFromLabel() {
    // label is either 'New issue' or 'New merge request'
    return this.newItemBtnBaseText.split(' ').slice(1).join(' ');
  }

  getProjectFromLocalStorage() {
    const projectString = localStorage.getItem(this.localStorageKey);

    return JSON.parse(projectString);
  }

  setProjectInLocalStorage(projectMeta) {
    const projectString = JSON.stringify(projectMeta);

    localStorage.setItem(this.localStorageKey, projectString);
  }
}