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

project_new.js « projects « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f1b7e3df7d6d63390d8b74e1d1c14a28c0631187 (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
import $ from 'jquery';
import { debounce } from 'lodash';
import DEFAULT_PROJECT_TEMPLATES from 'ee_else_ce/projects/default_project_templates';
import { confirmAction } from '~/lib/utils/confirm_via_gl_modal/confirm_via_gl_modal';
import { DEFAULT_DEBOUNCE_AND_THROTTLE_MS } from '../lib/utils/constants';
import axios from '../lib/utils/axios_utils';
import {
  convertToTitleCase,
  humanize,
  slugify,
  convertUnicodeToAscii,
} from '../lib/utils/text_utility';

let hasUserDefinedProjectPath = false;
let hasUserDefinedProjectName = false;
const invalidInputClass = 'gl-field-error-outline';

const cancelSource = axios.CancelToken.source();
const endpoint = `${gon.relative_url_root}/import/url/validate`;
let importCredentialsValidationPromise = null;
const validateImportCredentials = (url, user, password) => {
  cancelSource.cancel();
  importCredentialsValidationPromise = axios
    .post(endpoint, { url, user, password }, { cancelToken: cancelSource.cancel() })
    .then(({ data }) => data)
    .catch((thrown) =>
      axios.isCancel(thrown)
        ? {
            cancelled: true,
          }
        : {
            // intentionally reporting success in case of validation error
            // we do not want to block users from trying import in case of validation exception
            success: true,
          },
    );
  return importCredentialsValidationPromise;
};

const onProjectNameChange = ($projectNameInput, $projectPathInput) => {
  const slug = slugify(convertUnicodeToAscii($projectNameInput.val()));
  $projectPathInput.val(slug);
};

const onProjectPathChange = ($projectNameInput, $projectPathInput, hasExistingProjectName) => {
  const slug = $projectPathInput.val();

  if (!hasExistingProjectName) {
    $projectNameInput.val(convertToTitleCase(humanize(slug, '[-_]')));
  }
};

const setProjectNamePathHandlers = ($projectNameInput, $projectPathInput) => {
  const specialRepo = document.querySelector('.js-user-readme-repo');

  // eslint-disable-next-line @gitlab/no-global-event-off
  $projectNameInput.off('keyup change').on('keyup change', () => {
    onProjectNameChange($projectNameInput, $projectPathInput);
    hasUserDefinedProjectName = $projectNameInput.val().trim().length > 0;
    hasUserDefinedProjectPath = $projectPathInput.val().trim().length > 0;
  });

  // eslint-disable-next-line @gitlab/no-global-event-off
  $projectPathInput.off('keyup change').on('keyup change', () => {
    onProjectPathChange($projectNameInput, $projectPathInput, hasUserDefinedProjectName);
    hasUserDefinedProjectPath = $projectPathInput.val().trim().length > 0;

    specialRepo.classList.toggle(
      'gl-display-none',
      $projectPathInput.val() !== $projectPathInput.data('username'),
    );
  });
};

const deriveProjectPathFromUrl = ($projectImportUrl) => {
  const $currentProjectName = $projectImportUrl
    .parents('.toggle-import-form')
    .find('#project_name');
  const $currentProjectPath = $projectImportUrl
    .parents('.toggle-import-form')
    .find('#project_path');

  if (hasUserDefinedProjectPath || $currentProjectPath.length === 0) {
    return;
  }

  let importUrl = $projectImportUrl.val().trim();
  if (importUrl.length === 0) {
    return;
  }

  /*
    \/?: remove trailing slash
    (\.git\/?)?: remove trailing .git (with optional trailing slash)
    (\?.*)?: remove query string
    (#.*)?: remove fragment identifier
  */
  importUrl = importUrl.replace(/\/?(\.git\/?)?(\?.*)?(#.*)?$/, '');

  // extract everything after the last slash
  const pathMatch = /\/([^/]+)$/.exec(importUrl);
  if (pathMatch) {
    $currentProjectPath.val(pathMatch[1]);
    onProjectPathChange($currentProjectName, $currentProjectPath, false);
  }
};

const bindHowToImport = () => {
  const importLinks = document.querySelectorAll('.js-how-to-import-link');

  importLinks.forEach((link) => {
    const { modalTitle: title, modalMessage: modalHtmlMessage } = link.dataset;

    link.addEventListener('click', (e) => {
      e.preventDefault();
      confirmAction('', {
        modalHtmlMessage,
        title,
        hideCancel: true,
      });
    });
  });
};

const bindEvents = () => {
  const $newProjectForm = $('#new_project');
  const $projectImportUrl = $('#project_import_url');
  const $projectImportUrlUser = $('#project_import_url_user');
  const $projectImportUrlPassword = $('#project_import_url_password');
  const $projectImportUrlError = $('.js-import-url-error');
  const $projectImportForm = $('form.js-project-import');
  const $projectPath = $('.tab-pane.active #project_path');
  const $useTemplateBtn = $('.template-button > input');
  const $projectFieldsForm = $('.project-fields-form');
  const $selectedTemplateText = $('.selected-template');
  const $changeTemplateBtn = $('.change-template');
  const $selectedIcon = $('.selected-icon');
  const $projectTemplateButtons = $('.project-templates-buttons');
  const $projectName = $('.tab-pane.active #project_name');

  if ($newProjectForm.length !== 1 && $projectImportForm.length !== 1) {
    return;
  }

  bindHowToImport();

  $('.btn_import_gitlab_project').on('click contextmenu', () => {
    const importHref = $('a.btn_import_gitlab_project').attr('data-href');
    $('.btn_import_gitlab_project').attr(
      'href',
      `${importHref}?namespace_id=${$(
        '#project_namespace_id',
      ).val()}&name=${$projectName.val()}&path=${$projectPath.val()}`,
    );
  });

  function chooseTemplate() {
    $projectTemplateButtons.addClass('hidden');
    $projectFieldsForm.addClass('selected');
    $selectedIcon.empty();
    const value = $(this).val();

    const selectedTemplate = DEFAULT_PROJECT_TEMPLATES[value];
    $selectedTemplateText.text(selectedTemplate.text);
    $(selectedTemplate.icon).clone().addClass('d-block').appendTo($selectedIcon);

    const $activeTabProjectName = $('.tab-pane.active #project_name');
    const $activeTabProjectPath = $('.tab-pane.active #project_path');
    $activeTabProjectName.focus();
    setProjectNamePathHandlers($activeTabProjectName, $activeTabProjectPath);
  }

  $useTemplateBtn.on('change', chooseTemplate);

  $changeTemplateBtn.on('click', () => {
    $projectTemplateButtons.removeClass('hidden');
    $projectFieldsForm.removeClass('selected');
    $useTemplateBtn.prop('checked', false);
  });

  $newProjectForm.on('submit', () => {
    $projectPath.val($projectPath.val().trim());
  });

  const updateUrlPathWarningVisibility = async () => {
    const { success: isUrlValid, cancelled } = await validateImportCredentials(
      $projectImportUrl.val(),
      $projectImportUrlUser.val(),
      $projectImportUrlPassword.val(),
    );
    if (cancelled) {
      return;
    }

    $projectImportUrl.toggleClass(invalidInputClass, !isUrlValid);
    $projectImportUrlError.toggleClass('hide', isUrlValid);
  };
  const debouncedUpdateUrlPathWarningVisibility = debounce(
    updateUrlPathWarningVisibility,
    DEFAULT_DEBOUNCE_AND_THROTTLE_MS,
  );

  let isProjectImportUrlDirty = false;
  $projectImportUrl.on('blur', () => {
    isProjectImportUrlDirty = true;
    debouncedUpdateUrlPathWarningVisibility();
  });
  $projectImportUrl.on('keyup', () => {
    deriveProjectPathFromUrl($projectImportUrl);
  });

  [$projectImportUrl, $projectImportUrlUser, $projectImportUrlPassword].forEach(($f) => {
    $f.on('input', () => {
      if (isProjectImportUrlDirty) {
        debouncedUpdateUrlPathWarningVisibility();
      }
    });
  });

  $projectImportForm.on('submit', async (e) => {
    e.preventDefault();

    if (importCredentialsValidationPromise === null) {
      // we didn't validate credentials yet
      debouncedUpdateUrlPathWarningVisibility.cancel();
      updateUrlPathWarningVisibility();
    }

    const submitBtn = $projectImportForm.find('input[type="submit"]');

    submitBtn.disable();
    await importCredentialsValidationPromise;
    submitBtn.enable();

    const $invalidFields = $projectImportForm.find(`.${invalidInputClass}`);
    if ($invalidFields.length > 0) {
      $invalidFields[0].focus();
    } else {
      // calling .submit() on HTMLFormElement does not trigger 'submit' event
      // We are using this behavior to bypass this handler and avoid infinite loop
      $projectImportForm[0].submit();
    }
  });

  $('.js-import-git-toggle-button').on('click', () => {
    const $projectMirror = $('#project_mirror');

    $projectMirror.attr('disabled', !$projectMirror.attr('disabled'));
    setProjectNamePathHandlers(
      $('.tab-pane.active #project_name'),
      $('.tab-pane.active #project_path'),
    );
  });

  setProjectNamePathHandlers($projectName, $projectPath);
};

export default {
  bindEvents,
  deriveProjectPathFromUrl,
  onProjectNameChange,
  onProjectPathChange,
};

export { bindHowToImport };