本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3340 lines
117KB

  1. /* globals wipPrefixes, issuesTribute, emojiTribute */
  2. /* exported timeAddManual, toggleStopwatch, cancelStopwatch, initHeatmap */
  3. /* exported toggleDeadlineForm, setDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */
  4. 'use strict';
  5. function htmlEncode(text) {
  6. return jQuery('<div />').text(text).html()
  7. }
  8. let csrf;
  9. let suburl;
  10. let previewFileModes;
  11. let simpleMDEditor;
  12. let codeMirrorEditor;
  13. // Disable Dropzone auto-discover because it's manually initialized
  14. if (typeof(Dropzone) !== "undefined") {
  15. Dropzone.autoDiscover = false;
  16. }
  17. // Polyfill for IE9+ support (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
  18. if (!Array.from) {
  19. Array.from = (function () {
  20. const toStr = Object.prototype.toString;
  21. const isCallable = function (fn) {
  22. return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
  23. };
  24. const toInteger = function (value) {
  25. const number = Number(value);
  26. if (isNaN(number)) { return 0; }
  27. if (number === 0 || !isFinite(number)) { return number; }
  28. return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
  29. };
  30. const maxSafeInteger = Math.pow(2, 53) - 1;
  31. const toLength = function (value) {
  32. const len = toInteger(value);
  33. return Math.min(Math.max(len, 0), maxSafeInteger);
  34. };
  35. // The length property of the from method is 1.
  36. return function from(arrayLike/*, mapFn, thisArg */) {
  37. // 1. Let C be the this value.
  38. const C = this;
  39. // 2. Let items be ToObject(arrayLike).
  40. const items = Object(arrayLike);
  41. // 3. ReturnIfAbrupt(items).
  42. if (arrayLike == null) {
  43. throw new TypeError("Array.from requires an array-like object - not null or undefined");
  44. }
  45. // 4. If mapfn is undefined, then let mapping be false.
  46. const mapFn = arguments.length > 1 ? arguments[1] : void undefined;
  47. let T;
  48. if (typeof mapFn !== 'undefined') {
  49. // 5. else
  50. // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
  51. if (!isCallable(mapFn)) {
  52. throw new TypeError('Array.from: when provided, the second argument must be a function');
  53. }
  54. // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
  55. if (arguments.length > 2) {
  56. T = arguments[2];
  57. }
  58. }
  59. // 10. Let lenValue be Get(items, "length").
  60. // 11. Let len be ToLength(lenValue).
  61. const len = toLength(items.length);
  62. // 13. If IsConstructor(C) is true, then
  63. // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
  64. // 14. a. Else, Let A be ArrayCreate(len).
  65. const A = isCallable(C) ? Object(new C(len)) : new Array(len);
  66. // 16. Let k be 0.
  67. let k = 0;
  68. // 17. Repeat, while k < len… (also steps a - h)
  69. let kValue;
  70. while (k < len) {
  71. kValue = items[k];
  72. if (mapFn) {
  73. A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
  74. } else {
  75. A[k] = kValue;
  76. }
  77. k += 1;
  78. }
  79. // 18. Let putStatus be Put(A, "length", len, true).
  80. A.length = len;
  81. // 20. Return A.
  82. return A;
  83. };
  84. }());
  85. }
  86. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  87. if (typeof Object.assign != 'function') {
  88. // Must be writable: true, enumerable: false, configurable: true
  89. Object.defineProperty(Object, "assign", {
  90. value: function assign(target, _varArgs) { // .length of function is 2
  91. 'use strict';
  92. if (target == null) { // TypeError if undefined or null
  93. throw new TypeError('Cannot convert undefined or null to object');
  94. }
  95. const to = Object(target);
  96. for (let index = 1; index < arguments.length; index++) {
  97. const nextSource = arguments[index];
  98. if (nextSource != null) { // Skip over if undefined or null
  99. for (const nextKey in nextSource) {
  100. // Avoid bugs when hasOwnProperty is shadowed
  101. if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
  102. to[nextKey] = nextSource[nextKey];
  103. }
  104. }
  105. }
  106. }
  107. return to;
  108. },
  109. writable: true,
  110. configurable: true
  111. });
  112. }
  113. function initCommentPreviewTab($form) {
  114. const $tabMenu = $form.find('.tabular.menu');
  115. $tabMenu.find('.item').tab();
  116. $tabMenu.find('.item[data-tab="' + $tabMenu.data('preview') + '"]').click(function () {
  117. const $this = $(this);
  118. $.post($this.data('url'), {
  119. "_csrf": csrf,
  120. "mode": "gfm",
  121. "context": $this.data('context'),
  122. "text": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  123. },
  124. function (data) {
  125. const $previewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('preview') + '"]');
  126. $previewPanel.html(data);
  127. emojify.run($previewPanel[0]);
  128. $('pre code', $previewPanel[0]).each(function () {
  129. hljs.highlightBlock(this);
  130. });
  131. }
  132. );
  133. });
  134. buttonsClickOnEnter();
  135. }
  136. function initEditPreviewTab($form) {
  137. const $tabMenu = $form.find('.tabular.menu');
  138. $tabMenu.find('.item').tab();
  139. const $previewTab = $tabMenu.find('.item[data-tab="' + $tabMenu.data('preview') + '"]');
  140. if ($previewTab.length) {
  141. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  142. $previewTab.click(function () {
  143. const $this = $(this);
  144. $.post($this.data('url'), {
  145. "_csrf": csrf,
  146. "mode": "gfm",
  147. "context": $this.data('context'),
  148. "text": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  149. },
  150. function (data) {
  151. const $previewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('preview') + '"]');
  152. $previewPanel.html(data);
  153. emojify.run($previewPanel[0]);
  154. $('pre code', $previewPanel[0]).each(function () {
  155. hljs.highlightBlock(this);
  156. });
  157. }
  158. );
  159. });
  160. }
  161. }
  162. function initEditDiffTab($form) {
  163. const $tabMenu = $form.find('.tabular.menu');
  164. $tabMenu.find('.item').tab();
  165. $tabMenu.find('.item[data-tab="' + $tabMenu.data('diff') + '"]').click(function () {
  166. const $this = $(this);
  167. $.post($this.data('url'), {
  168. "_csrf": csrf,
  169. "context": $this.data('context'),
  170. "content": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  171. },
  172. function (data) {
  173. const $diffPreviewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('diff') + '"]');
  174. $diffPreviewPanel.html(data);
  175. emojify.run($diffPreviewPanel[0]);
  176. }
  177. );
  178. });
  179. }
  180. function initEditForm() {
  181. if ($('.edit.form').length == 0) {
  182. return;
  183. }
  184. initEditPreviewTab($('.edit.form'));
  185. initEditDiffTab($('.edit.form'));
  186. }
  187. function initBranchSelector() {
  188. const $selectBranch = $('.ui.select-branch')
  189. const $branchMenu = $selectBranch.find('.reference-list-menu');
  190. $branchMenu.find('.item:not(.no-select)').click(function () {
  191. const selectedValue = $(this).data('id');
  192. $($(this).data('id-selector')).val(selectedValue);
  193. $selectBranch.find('.ui .branch-name').text(selectedValue);
  194. });
  195. $selectBranch.find('.reference.column').click(function () {
  196. $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none');
  197. $selectBranch.find('.reference .text').removeClass('black');
  198. $($(this).data('target')).css('display', 'block');
  199. $(this).find('.text').addClass('black');
  200. return false;
  201. });
  202. }
  203. function updateIssuesMeta(url, action, issueIds, elementId) {
  204. return new Promise(function(resolve) {
  205. $.ajax({
  206. type: "POST",
  207. url: url,
  208. data: {
  209. "_csrf": csrf,
  210. "action": action,
  211. "issue_ids": issueIds,
  212. "id": elementId
  213. },
  214. success: resolve
  215. })
  216. })
  217. }
  218. function initRepoStatusChecker() {
  219. const migrating = $("#repo_migrating");
  220. $('#repo_migrating_failed').hide();
  221. if (migrating) {
  222. const repo_name = migrating.attr('repo');
  223. if (typeof repo_name === 'undefined') {
  224. return
  225. }
  226. $.ajax({
  227. type: "GET",
  228. url: suburl +"/"+repo_name+"/status",
  229. data: {
  230. "_csrf": csrf,
  231. },
  232. complete: function(xhr) {
  233. if (xhr.status == 200) {
  234. if (xhr.responseJSON) {
  235. if (xhr.responseJSON["status"] == 0) {
  236. location.reload();
  237. return
  238. }
  239. setTimeout(function () {
  240. initRepoStatusChecker()
  241. }, 2000);
  242. return
  243. }
  244. }
  245. $('#repo_migrating_progress').hide();
  246. $('#repo_migrating_failed').show();
  247. }
  248. })
  249. }
  250. }
  251. function initReactionSelector(parent) {
  252. let reactions = '';
  253. if (!parent) {
  254. parent = $(document);
  255. reactions = '.reactions > ';
  256. }
  257. parent.find(reactions + 'a.label').popup({'position': 'bottom left', 'metadata': {'content': 'title', 'title': 'none'}});
  258. parent.find('.select-reaction > .menu > .item, ' + reactions + 'a.label').on('click', function(e){
  259. const vm = this;
  260. e.preventDefault();
  261. if ($(this).hasClass('disabled')) return;
  262. const actionURL = $(this).hasClass('item') ?
  263. $(this).closest('.select-reaction').data('action-url') :
  264. $(this).data('action-url');
  265. const url = actionURL + '/' + ($(this).hasClass('blue') ? 'unreact' : 'react');
  266. $.ajax({
  267. type: 'POST',
  268. url: url,
  269. data: {
  270. '_csrf': csrf,
  271. 'content': $(this).data('content')
  272. }
  273. }).done(function(resp) {
  274. if (resp && (resp.html || resp.empty)) {
  275. const content = $(vm).closest('.content');
  276. let react = content.find('.segment.reactions');
  277. if (!resp.empty && react.length > 0) {
  278. react.remove();
  279. }
  280. if (!resp.empty) {
  281. react = $('<div class="ui attached segment reactions"></div>');
  282. const attachments = content.find('.segment.bottom:first');
  283. if (attachments.length > 0) {
  284. react.insertBefore(attachments);
  285. } else {
  286. react.appendTo(content);
  287. }
  288. react.html(resp.html);
  289. const hasEmoji = react.find('.has-emoji');
  290. for (let i = 0; i < hasEmoji.length; i++) {
  291. emojify.run(hasEmoji.get(i));
  292. }
  293. react.find('.dropdown').dropdown();
  294. initReactionSelector(react);
  295. }
  296. }
  297. });
  298. });
  299. }
  300. function insertAtCursor(field, value) {
  301. if (field.selectionStart || field.selectionStart === 0) {
  302. const startPos = field.selectionStart;
  303. const endPos = field.selectionEnd;
  304. field.value = field.value.substring(0, startPos)
  305. + value
  306. + field.value.substring(endPos, field.value.length);
  307. field.selectionStart = startPos + value.length;
  308. field.selectionEnd = startPos + value.length;
  309. } else {
  310. field.value += value;
  311. }
  312. }
  313. function replaceAndKeepCursor(field, oldval, newval) {
  314. if (field.selectionStart || field.selectionStart === 0) {
  315. const startPos = field.selectionStart;
  316. const endPos = field.selectionEnd;
  317. field.value = field.value.replace(oldval, newval);
  318. field.selectionStart = startPos + newval.length - oldval.length;
  319. field.selectionEnd = endPos + newval.length - oldval.length;
  320. } else {
  321. field.value = field.value.replace(oldval, newval);
  322. }
  323. }
  324. function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
  325. if (!pasteEvent.clipboardData) {
  326. return;
  327. }
  328. const items = pasteEvent.clipboardData.items;
  329. if (typeof(items) === "undefined") {
  330. return;
  331. }
  332. for (let i = 0; i < items.length; i++) {
  333. if (items[i].type.indexOf("image") === -1) continue;
  334. const blob = items[i].getAsFile();
  335. if (typeof(callback) === "function") {
  336. pasteEvent.preventDefault();
  337. pasteEvent.stopPropagation();
  338. callback(blob);
  339. }
  340. }
  341. }
  342. function uploadFile(file, callback) {
  343. const xhr = new XMLHttpRequest();
  344. xhr.onload = function() {
  345. if (xhr.status == 200) {
  346. callback(xhr.responseText);
  347. }
  348. };
  349. xhr.open("post", suburl + "/attachments", true);
  350. xhr.setRequestHeader("X-Csrf-Token", csrf);
  351. const formData = new FormData();
  352. formData.append('file', file, file.name);
  353. xhr.send(formData);
  354. }
  355. function reload() {
  356. window.location.reload();
  357. }
  358. function initImagePaste(target) {
  359. target.each(function() {
  360. const field = this;
  361. field.addEventListener('paste', function(event){
  362. retrieveImageFromClipboardAsBlob(event, function(img) {
  363. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  364. insertAtCursor(field, '![' + name + ']()');
  365. uploadFile(img, function(res) {
  366. const data = JSON.parse(res);
  367. replaceAndKeepCursor(field, '![' + name + ']()', '![' + name + '](' + suburl + '/attachments/' + data.uuid + ')');
  368. const input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  369. $('.files').append(input);
  370. });
  371. });
  372. }, false);
  373. });
  374. }
  375. function initCommentForm() {
  376. if ($('.comment.form').length == 0) {
  377. return
  378. }
  379. initBranchSelector();
  380. initCommentPreviewTab($('.comment.form'));
  381. initImagePaste($('.comment.form textarea'));
  382. // Listsubmit
  383. function initListSubmits(selector, outerSelector) {
  384. const $list = $('.ui.' + outerSelector + '.list');
  385. const $noSelect = $list.find('.no-select');
  386. const $listMenu = $('.' + selector + ' .menu');
  387. let hasLabelUpdateAction = $listMenu.data('action') == 'update';
  388. const labels = {};
  389. $('.' + selector).dropdown('setting', 'onHide', function(){
  390. hasLabelUpdateAction = $listMenu.data('action') == 'update'; // Update the var
  391. if (hasLabelUpdateAction) {
  392. const promises = [];
  393. Object.keys(labels).forEach(function(elementId) {
  394. const label = labels[elementId];
  395. const promise = updateIssuesMeta(
  396. label["update-url"],
  397. label["action"],
  398. label["issue-id"],
  399. elementId
  400. );
  401. promises.push(promise);
  402. });
  403. Promise.all(promises).then(reload);
  404. }
  405. });
  406. $listMenu.find('.item:not(.no-select)').click(function () {
  407. // we don't need the action attribute when updating assignees
  408. if (selector == 'select-assignees-modify') {
  409. // UI magic. We need to do this here, otherwise it would destroy the functionality of
  410. // adding/removing labels
  411. if ($(this).hasClass('checked')) {
  412. $(this).removeClass('checked');
  413. $(this).find('.octicon').removeClass('octicon-check');
  414. } else {
  415. $(this).addClass('checked');
  416. $(this).find('.octicon').addClass('octicon-check');
  417. }
  418. updateIssuesMeta(
  419. $listMenu.data('update-url'),
  420. "",
  421. $listMenu.data('issue-id'),
  422. $(this).data('id')
  423. );
  424. $listMenu.data('action', 'update'); // Update to reload the page when we updated items
  425. return false;
  426. }
  427. if ($(this).hasClass('checked')) {
  428. $(this).removeClass('checked');
  429. $(this).find('.octicon').removeClass('octicon-check');
  430. if (hasLabelUpdateAction) {
  431. if (!($(this).data('id') in labels)) {
  432. labels[$(this).data('id')] = {
  433. "update-url": $listMenu.data('update-url'),
  434. "action": "detach",
  435. "issue-id": $listMenu.data('issue-id'),
  436. };
  437. } else {
  438. delete labels[$(this).data('id')];
  439. }
  440. }
  441. } else {
  442. $(this).addClass('checked');
  443. $(this).find('.octicon').addClass('octicon-check');
  444. if (hasLabelUpdateAction) {
  445. if (!($(this).data('id') in labels)) {
  446. labels[$(this).data('id')] = {
  447. "update-url": $listMenu.data('update-url'),
  448. "action": "attach",
  449. "issue-id": $listMenu.data('issue-id'),
  450. };
  451. } else {
  452. delete labels[$(this).data('id')];
  453. }
  454. }
  455. }
  456. const listIds = [];
  457. $(this).parent().find('.item').each(function () {
  458. if ($(this).hasClass('checked')) {
  459. listIds.push($(this).data('id'));
  460. $($(this).data('id-selector')).removeClass('hide');
  461. } else {
  462. $($(this).data('id-selector')).addClass('hide');
  463. }
  464. });
  465. if (listIds.length == 0) {
  466. $noSelect.removeClass('hide');
  467. } else {
  468. $noSelect.addClass('hide');
  469. }
  470. $($(this).parent().data('id')).val(listIds.join(","));
  471. return false;
  472. });
  473. $listMenu.find('.no-select.item').click(function () {
  474. if (hasLabelUpdateAction || selector == 'select-assignees-modify') {
  475. updateIssuesMeta(
  476. $listMenu.data('update-url'),
  477. "clear",
  478. $listMenu.data('issue-id'),
  479. ""
  480. ).then(reload);
  481. }
  482. $(this).parent().find('.item').each(function () {
  483. $(this).removeClass('checked');
  484. $(this).find('.octicon').removeClass('octicon-check');
  485. });
  486. $list.find('.item').each(function () {
  487. $(this).addClass('hide');
  488. });
  489. $noSelect.removeClass('hide');
  490. $($(this).parent().data('id')).val('');
  491. });
  492. }
  493. // Init labels and assignees
  494. initListSubmits('select-label', 'labels');
  495. initListSubmits('select-assignees', 'assignees');
  496. initListSubmits('select-assignees-modify', 'assignees');
  497. function selectItem(select_id, input_id) {
  498. const $menu = $(select_id + ' .menu');
  499. const $list = $('.ui' + select_id + '.list');
  500. const hasUpdateAction = $menu.data('action') == 'update';
  501. $menu.find('.item:not(.no-select)').click(function () {
  502. $(this).parent().find('.item').each(function () {
  503. $(this).removeClass('selected active')
  504. });
  505. $(this).addClass('selected active');
  506. if (hasUpdateAction) {
  507. updateIssuesMeta(
  508. $menu.data('update-url'),
  509. "",
  510. $menu.data('issue-id'),
  511. $(this).data('id')
  512. ).then(reload);
  513. }
  514. switch (input_id) {
  515. case '#milestone_id':
  516. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  517. htmlEncode($(this).text()) + '</a>');
  518. break;
  519. case '#assignee_id':
  520. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  521. '<img class="ui avatar image" src=' + $(this).data('avatar') + '>' +
  522. htmlEncode($(this).text()) + '</a>');
  523. }
  524. $('.ui' + select_id + '.list .no-select').addClass('hide');
  525. $(input_id).val($(this).data('id'));
  526. });
  527. $menu.find('.no-select.item').click(function () {
  528. $(this).parent().find('.item:not(.no-select)').each(function () {
  529. $(this).removeClass('selected active')
  530. });
  531. if (hasUpdateAction) {
  532. updateIssuesMeta(
  533. $menu.data('update-url'),
  534. "",
  535. $menu.data('issue-id'),
  536. $(this).data('id')
  537. ).then(reload);
  538. }
  539. $list.find('.selected').html('');
  540. $list.find('.no-select').removeClass('hide');
  541. $(input_id).val('');
  542. });
  543. }
  544. // Milestone and assignee
  545. selectItem('.select-milestone', '#milestone_id');
  546. selectItem('.select-assignee', '#assignee_id');
  547. }
  548. function initInstall() {
  549. if ($('.install').length == 0) {
  550. return;
  551. }
  552. if ($('#db_host').val()=="") {
  553. $('#db_host').val("127.0.0.1:3306");
  554. $('#db_user').val("gitea");
  555. $('#db_name').val("gitea");
  556. }
  557. // Database type change detection.
  558. $("#db_type").change(function () {
  559. const sqliteDefault = 'data/gitea.db';
  560. const tidbDefault = 'data/gitea_tidb';
  561. const dbType = $(this).val();
  562. if (dbType === "SQLite3") {
  563. $('#sql_settings').hide();
  564. $('#pgsql_settings').hide();
  565. $('#mysql_settings').hide();
  566. $('#sqlite_settings').show();
  567. if (dbType === "SQLite3" && $('#db_path').val() == tidbDefault) {
  568. $('#db_path').val(sqliteDefault);
  569. }
  570. return;
  571. }
  572. const dbDefaults = {
  573. "MySQL": "127.0.0.1:3306",
  574. "PostgreSQL": "127.0.0.1:5432",
  575. "MSSQL": "127.0.0.1:1433"
  576. };
  577. $('#sqlite_settings').hide();
  578. $('#sql_settings').show();
  579. $('#pgsql_settings').toggle(dbType === "PostgreSQL");
  580. $('#mysql_settings').toggle(dbType === "MySQL");
  581. $.each(dbDefaults, function(_type, defaultHost) {
  582. if ($('#db_host').val() == defaultHost) {
  583. $('#db_host').val(dbDefaults[dbType]);
  584. return false;
  585. }
  586. });
  587. });
  588. // TODO: better handling of exclusive relations.
  589. $('#offline-mode input').change(function () {
  590. if ($(this).is(':checked')) {
  591. $('#disable-gravatar').checkbox('check');
  592. $('#federated-avatar-lookup').checkbox('uncheck');
  593. }
  594. });
  595. $('#disable-gravatar input').change(function () {
  596. if ($(this).is(':checked')) {
  597. $('#federated-avatar-lookup').checkbox('uncheck');
  598. } else {
  599. $('#offline-mode').checkbox('uncheck');
  600. }
  601. });
  602. $('#federated-avatar-lookup input').change(function () {
  603. if ($(this).is(':checked')) {
  604. $('#disable-gravatar').checkbox('uncheck');
  605. $('#offline-mode').checkbox('uncheck');
  606. }
  607. });
  608. $('#enable-openid-signin input').change(function () {
  609. if ($(this).is(':checked')) {
  610. if (!$('#disable-registration input').is(':checked')) {
  611. $('#enable-openid-signup').checkbox('check');
  612. }
  613. } else {
  614. $('#enable-openid-signup').checkbox('uncheck');
  615. }
  616. });
  617. $('#disable-registration input').change(function () {
  618. if ($(this).is(':checked')) {
  619. $('#enable-captcha').checkbox('uncheck');
  620. $('#enable-openid-signup').checkbox('uncheck');
  621. } else {
  622. $('#enable-openid-signup').checkbox('check');
  623. }
  624. });
  625. $('#enable-captcha input').change(function () {
  626. if ($(this).is(':checked')) {
  627. $('#disable-registration').checkbox('uncheck');
  628. }
  629. });
  630. }
  631. function initRepository() {
  632. if ($('.repository').length == 0) {
  633. return;
  634. }
  635. function initFilterSearchDropdown(selector) {
  636. const $dropdown = $(selector);
  637. $dropdown.dropdown({
  638. fullTextSearch: true,
  639. selectOnKeydown: false,
  640. onChange: function (_text, _value, $choice) {
  641. if ($choice.data('url')) {
  642. window.location.href = $choice.data('url');
  643. }
  644. },
  645. message: {noResults: $dropdown.data('no-results')}
  646. });
  647. }
  648. // File list and commits
  649. if ($('.repository.file.list').length > 0 ||
  650. ('.repository.commits').length > 0) {
  651. initFilterBranchTagDropdown('.choose.reference .dropdown');
  652. }
  653. // Wiki
  654. if ($('.repository.wiki.view').length > 0) {
  655. initFilterSearchDropdown('.choose.page .dropdown');
  656. }
  657. // Options
  658. if ($('.repository.settings.options').length > 0) {
  659. $('#repo_name').keyup(function () {
  660. const $prompt = $('#repo-name-change-prompt');
  661. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  662. $prompt.show();
  663. } else {
  664. $prompt.hide();
  665. }
  666. });
  667. // Enable or select internal/external wiki system and issue tracker.
  668. $('.enable-system').change(function () {
  669. if (this.checked) {
  670. $($(this).data('target')).removeClass('disabled');
  671. if (!$(this).data('context')) $($(this).data('context')).addClass('disabled');
  672. } else {
  673. $($(this).data('target')).addClass('disabled');
  674. if (!$(this).data('context')) $($(this).data('context')).removeClass('disabled');
  675. }
  676. });
  677. $('.enable-system-radio').change(function () {
  678. if (this.value == 'false') {
  679. $($(this).data('target')).addClass('disabled');
  680. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).removeClass('disabled');
  681. } else if (this.value == 'true') {
  682. $($(this).data('target')).removeClass('disabled');
  683. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).addClass('disabled');
  684. }
  685. });
  686. }
  687. // Labels
  688. if ($('.repository.labels').length > 0) {
  689. // Create label
  690. const $newLabelPanel = $('.new-label.segment');
  691. $('.new-label.button').click(function () {
  692. $newLabelPanel.show();
  693. });
  694. $('.new-label.segment .cancel').click(function () {
  695. $newLabelPanel.hide();
  696. });
  697. $('.color-picker').each(function () {
  698. $(this).minicolors();
  699. });
  700. $('.precolors .color').click(function () {
  701. const color_hex = $(this).data('color-hex');
  702. $('.color-picker').val(color_hex);
  703. $('.minicolors-swatch-color').css("background-color", color_hex);
  704. });
  705. $('.edit-label-button').click(function () {
  706. $('#label-modal-id').val($(this).data('id'));
  707. $('.edit-label .new-label-input').val($(this).data('title'));
  708. $('.edit-label .new-label-desc-input').val($(this).data('description'));
  709. $('.edit-label .color-picker').val($(this).data('color'));
  710. $('.minicolors-swatch-color').css("background-color", $(this).data('color'));
  711. $('.edit-label.modal').modal({
  712. onApprove: function () {
  713. $('.edit-label.form').submit();
  714. }
  715. }).modal('show');
  716. return false;
  717. });
  718. }
  719. // Milestones
  720. if ($('.repository.new.milestone').length > 0) {
  721. const $datepicker = $('.milestone.datepicker');
  722. $datepicker.datetimepicker({
  723. lang: $datepicker.data('lang'),
  724. inline: true,
  725. timepicker: false,
  726. startDate: $datepicker.data('start-date'),
  727. formatDate: 'Y-m-d',
  728. onSelectDate: function (ct) {
  729. $('#deadline').val(ct.dateFormat('Y-m-d'));
  730. }
  731. });
  732. $('#clear-date').click(function () {
  733. $('#deadline').val('');
  734. return false;
  735. });
  736. }
  737. // Issues
  738. if ($('.repository.view.issue').length > 0) {
  739. // Edit issue title
  740. const $issueTitle = $('#issue-title');
  741. const $editInput = $('#edit-title-input input');
  742. const editTitleToggle = function () {
  743. $issueTitle.toggle();
  744. $('.not-in-edit').toggle();
  745. $('#edit-title-input').toggle();
  746. $('.in-edit').toggle();
  747. $editInput.focus();
  748. return false;
  749. };
  750. $('#edit-title').click(editTitleToggle);
  751. $('#cancel-edit-title').click(editTitleToggle);
  752. $('#save-edit-title').click(editTitleToggle).click(function () {
  753. if ($editInput.val().length == 0 ||
  754. $editInput.val() == $issueTitle.text()) {
  755. $editInput.val($issueTitle.text());
  756. return false;
  757. }
  758. $.post($(this).data('update-url'), {
  759. "_csrf": csrf,
  760. "title": $editInput.val()
  761. },
  762. function (data) {
  763. $editInput.val(data.title);
  764. $issueTitle.text(data.title);
  765. reload();
  766. });
  767. return false;
  768. });
  769. // Edit issue or comment content
  770. $('.edit-content').click(function () {
  771. const $segment = $(this).parent().parent().parent().next();
  772. const $editContentZone = $segment.find('.edit-content-zone');
  773. const $renderContent = $segment.find('.render-content');
  774. const $rawContent = $segment.find('.raw-content');
  775. let $textarea;
  776. // Setup new form
  777. if ($editContentZone.html().length == 0) {
  778. $editContentZone.html($('#edit-content-form').html());
  779. $textarea = $editContentZone.find('textarea');
  780. issuesTribute.attach($textarea.get());
  781. emojiTribute.attach($textarea.get());
  782. const $dropzone = $editContentZone.find('.dropzone');
  783. $dropzone.data("saved", false);
  784. const $files = $editContentZone.find('.comment-files');
  785. if ($dropzone.length > 0) {
  786. const filenameDict = {};
  787. $dropzone.dropzone({
  788. url: $dropzone.data('upload-url'),
  789. headers: {"X-Csrf-Token": csrf},
  790. maxFiles: $dropzone.data('max-file'),
  791. maxFilesize: $dropzone.data('max-size'),
  792. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  793. addRemoveLinks: true,
  794. dictDefaultMessage: $dropzone.data('default-message'),
  795. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  796. dictFileTooBig: $dropzone.data('file-too-big'),
  797. dictRemoveFile: $dropzone.data('remove-file'),
  798. init: function () {
  799. this.on("success", function (file, data) {
  800. filenameDict[file.name] = {
  801. "uuid": data.uuid,
  802. "submitted": false
  803. }
  804. const input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  805. $files.append(input);
  806. });
  807. this.on("removedfile", function (file) {
  808. if (!(file.name in filenameDict)) {
  809. return;
  810. }
  811. $('#' + filenameDict[file.name].uuid).remove();
  812. if ($dropzone.data('remove-url') && $dropzone.data('csrf') && !filenameDict[file.name].submitted) {
  813. $.post($dropzone.data('remove-url'), {
  814. file: filenameDict[file.name].uuid,
  815. _csrf: $dropzone.data('csrf')
  816. });
  817. }
  818. });
  819. this.on("submit", function () {
  820. $.each(filenameDict, function(name){
  821. filenameDict[name].submitted = true;
  822. });
  823. });
  824. this.on("reload", function (){
  825. $.getJSON($editContentZone.data('attachment-url'), function(data){
  826. const drop = $dropzone.get(0).dropzone;
  827. drop.removeAllFiles(true);
  828. $files.empty();
  829. $.each(data, function(){
  830. const imgSrc = $dropzone.data('upload-url') + "/" + this.uuid;
  831. drop.emit("addedfile", this);
  832. drop.emit("thumbnail", this, imgSrc);
  833. drop.emit("complete", this);
  834. drop.files.push(this);
  835. filenameDict[this.name] = {
  836. "submitted": true,
  837. "uuid": this.uuid
  838. }
  839. $dropzone.find("img[src='" + imgSrc + "']").css("max-width", "100%");
  840. const input = $('<input id="' + this.uuid + '" name="files" type="hidden">').val(this.uuid);
  841. $files.append(input);
  842. });
  843. });
  844. });
  845. }
  846. });
  847. $dropzone.get(0).dropzone.emit("reload");
  848. }
  849. // Give new write/preview data-tab name to distinguish from others
  850. const $editContentForm = $editContentZone.find('.ui.comment.form');
  851. const $tabMenu = $editContentForm.find('.tabular.menu');
  852. $tabMenu.attr('data-write', $editContentZone.data('write'));
  853. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  854. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  855. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  856. $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write'));
  857. $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview'));
  858. initCommentPreviewTab($editContentForm);
  859. $editContentZone.find('.cancel.button').click(function () {
  860. $renderContent.show();
  861. $editContentZone.hide();
  862. $dropzone.get(0).dropzone.emit("reload");
  863. });
  864. $editContentZone.find('.save.button').click(function () {
  865. $renderContent.show();
  866. $editContentZone.hide();
  867. const $attachments = $files.find("[name=files]").map(function(){
  868. return $(this).val();
  869. }).get();
  870. $.post($editContentZone.data('update-url'), {
  871. "_csrf": csrf,
  872. "content": $textarea.val(),
  873. "context": $editContentZone.data('context'),
  874. "files": $attachments
  875. },
  876. function (data) {
  877. if (data.length == 0) {
  878. $renderContent.html($('#no-content').html());
  879. } else {
  880. $renderContent.html(data.content);
  881. emojify.run($renderContent[0]);
  882. $('pre code', $renderContent[0]).each(function () {
  883. hljs.highlightBlock(this);
  884. });
  885. }
  886. const $content = $segment.parent();
  887. if(!$content.find(".ui.small.images").length){
  888. if(data.attachments != ""){
  889. $content.append(
  890. '<div class="ui bottom attached segment">' +
  891. ' <div class="ui small images">' +
  892. ' </div>' +
  893. '</div>'
  894. );
  895. $content.find(".ui.small.images").html(data.attachments);
  896. }
  897. } else if (data.attachments == "") {
  898. $content.find(".ui.small.images").parent().remove();
  899. } else {
  900. $content.find(".ui.small.images").html(data.attachments);
  901. }
  902. $dropzone.get(0).dropzone.emit("submit");
  903. $dropzone.get(0).dropzone.emit("reload");
  904. });
  905. });
  906. } else {
  907. $textarea = $segment.find('textarea');
  908. }
  909. // Show write/preview tab and copy raw content as needed
  910. $editContentZone.show();
  911. $renderContent.hide();
  912. if ($textarea.val().length == 0) {
  913. $textarea.val($rawContent.text());
  914. }
  915. $textarea.focus();
  916. return false;
  917. });
  918. // Delete comment
  919. $('.delete-comment').click(function () {
  920. const $this = $(this);
  921. if (confirm($this.data('locale'))) {
  922. $.post($this.data('url'), {
  923. "_csrf": csrf
  924. }).success(function () {
  925. $('#' + $this.data('comment-id')).remove();
  926. });
  927. }
  928. return false;
  929. });
  930. // Change status
  931. const $statusButton = $('#status-button');
  932. $('#comment-form .edit_area').keyup(function () {
  933. if ($(this).val().length == 0) {
  934. $statusButton.text($statusButton.data('status'))
  935. } else {
  936. $statusButton.text($statusButton.data('status-and-comment'))
  937. }
  938. });
  939. $statusButton.click(function () {
  940. $('#status').val($statusButton.data('status-val'));
  941. $('#comment-form').submit();
  942. });
  943. // Pull Request merge button
  944. const $mergeButton = $('.merge-button > button');
  945. $mergeButton.on('click', function(e) {
  946. e.preventDefault();
  947. $('.' + $(this).data('do') + '-fields').show();
  948. $(this).parent().hide();
  949. });
  950. $('.merge-button > .dropdown').dropdown({
  951. onChange: function (_text, _value, $choice) {
  952. if ($choice.data('do')) {
  953. $mergeButton.find('.button-text').text($choice.text());
  954. $mergeButton.data('do', $choice.data('do'));
  955. }
  956. }
  957. });
  958. $('.merge-cancel').on('click', function(e) {
  959. e.preventDefault();
  960. $(this).closest('.form').hide();
  961. $mergeButton.parent().show();
  962. });
  963. initReactionSelector();
  964. }
  965. // Diff
  966. if ($('.repository.diff').length > 0) {
  967. $('.diff-counter').each(function () {
  968. const $item = $(this);
  969. const addLine = $item.find('span[data-line].add').data("line");
  970. const delLine = $item.find('span[data-line].del').data("line");
  971. const addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  972. $item.find(".bar .add").css("width", addPercent + "%");
  973. });
  974. }
  975. // Quick start and repository home
  976. $('#repo-clone-ssh').click(function () {
  977. $('.clone-url').text($(this).data('link'));
  978. $('#repo-clone-url').val($(this).data('link'));
  979. $(this).addClass('blue');
  980. $('#repo-clone-https').removeClass('blue');
  981. localStorage.setItem('repo-clone-protocol', 'ssh');
  982. });
  983. $('#repo-clone-https').click(function () {
  984. $('.clone-url').text($(this).data('link'));
  985. $('#repo-clone-url').val($(this).data('link'));
  986. $(this).addClass('blue');
  987. $('#repo-clone-ssh').removeClass('blue');
  988. localStorage.setItem('repo-clone-protocol', 'https');
  989. });
  990. $('#repo-clone-url').click(function () {
  991. $(this).select();
  992. });
  993. // Pull request
  994. const $repoComparePull = $('.repository.compare.pull');
  995. if ($repoComparePull.length > 0) {
  996. initFilterSearchDropdown('.choose.branch .dropdown');
  997. // show pull request form
  998. $repoComparePull.find('button.show-form').on('click', function(e) {
  999. e.preventDefault();
  1000. $repoComparePull.find('.pullrequest-form').show();
  1001. $(this).parent().hide();
  1002. });
  1003. }
  1004. // Branches
  1005. if ($('.repository.settings.branches').length > 0) {
  1006. initFilterSearchDropdown('.protected-branches .dropdown');
  1007. $('.enable-protection, .enable-whitelist').change(function () {
  1008. if (this.checked) {
  1009. $($(this).data('target')).removeClass('disabled');
  1010. } else {
  1011. $($(this).data('target')).addClass('disabled');
  1012. }
  1013. });
  1014. }
  1015. }
  1016. function initMigration() {
  1017. const toggleMigrations = function() {
  1018. const authUserName = $('#auth_username').val();
  1019. const cloneAddr = $('#clone_addr').val();
  1020. if (!$('#mirror').is(":checked") && (authUserName!=undefined && authUserName.length > 0)
  1021. && (cloneAddr!=undefined && (cloneAddr.startsWith("https://github.com") || cloneAddr.startsWith("http://github.com")))) {
  1022. $('#migrate_items').show();
  1023. } else {
  1024. $('#migrate_items').hide();
  1025. }
  1026. }
  1027. toggleMigrations();
  1028. $('#clone_addr').on('input', toggleMigrations)
  1029. $('#auth_username').on('input', toggleMigrations)
  1030. $('#mirror').on('change', toggleMigrations)
  1031. }
  1032. function initPullRequestReview() {
  1033. $('.show-outdated').on('click', function (e) {
  1034. e.preventDefault();
  1035. const id = $(this).data('comment');
  1036. $(this).addClass("hide");
  1037. $("#code-comments-" + id).removeClass('hide');
  1038. $("#code-preview-" + id).removeClass('hide');
  1039. $("#hide-outdated-" + id).removeClass('hide');
  1040. });
  1041. $('.hide-outdated').on('click', function (e) {
  1042. e.preventDefault();
  1043. const id = $(this).data('comment');
  1044. $(this).addClass("hide");
  1045. $("#code-comments-" + id).addClass('hide');
  1046. $("#code-preview-" + id).addClass('hide');
  1047. $("#show-outdated-" + id).removeClass('hide');
  1048. });
  1049. $('button.comment-form-reply').on('click', function (e) {
  1050. e.preventDefault();
  1051. $(this).hide();
  1052. const form = $(this).parent().find('.comment-form')
  1053. form.removeClass('hide');
  1054. assingMenuAttributes(form.find('.menu'));
  1055. });
  1056. // The following part is only for diff views
  1057. if ($('.repository.pull.diff').length == 0) {
  1058. return;
  1059. }
  1060. $('.diff-detail-box.ui.sticky').sticky();
  1061. $('.btn-review').on('click', function(e) {
  1062. e.preventDefault();
  1063. $(this).closest('.dropdown').find('.menu').toggle('visible');
  1064. }).closest('.dropdown').find('.link.close').on('click', function(e) {
  1065. e.preventDefault();
  1066. $(this).closest('.menu').toggle('visible');
  1067. });
  1068. $('.code-view .lines-code,.code-view .lines-num')
  1069. .on('mouseenter', function() {
  1070. const parent = $(this).closest('td');
  1071. $(this).closest('tr').addClass(
  1072. parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old')
  1073. ? 'focus-lines-old' : 'focus-lines-new'
  1074. );
  1075. })
  1076. .on('mouseleave', function() {
  1077. $(this).closest('tr').removeClass('focus-lines-new focus-lines-old');
  1078. });
  1079. $('.add-code-comment').on('click', function(e) {
  1080. // https://github.com/go-gitea/gitea/issues/4745
  1081. if ($(e.target).hasClass('btn-add-single')) {
  1082. return;
  1083. }
  1084. e.preventDefault();
  1085. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  1086. const side = $(this).data('side');
  1087. const idx = $(this).data('idx');
  1088. const path = $(this).data('path');
  1089. const form = $('#pull_review_add_comment').html();
  1090. const tr = $(this).closest('tr');
  1091. let ntr = tr.next();
  1092. if (!ntr.hasClass('add-comment')) {
  1093. ntr = $('<tr class="add-comment">'
  1094. + (isSplit ? '<td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-right"></td>'
  1095. : '<td class="lines-num"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left add-comment-right"></td>')
  1096. + '</tr>');
  1097. tr.after(ntr);
  1098. }
  1099. const td = ntr.find('.add-comment-' + side);
  1100. let commentCloud = td.find('.comment-code-cloud');
  1101. if (commentCloud.length === 0) {
  1102. td.html(form);
  1103. commentCloud = td.find('.comment-code-cloud');
  1104. assingMenuAttributes(commentCloud.find('.menu'));
  1105. td.find("input[name='line']").val(idx);
  1106. td.find("input[name='side']").val(side === "left" ? "previous":"proposed");
  1107. td.find("input[name='path']").val(path);
  1108. }
  1109. commentCloud.find('textarea').focus();
  1110. });
  1111. }
  1112. function assingMenuAttributes(menu) {
  1113. const id = Math.floor(Math.random() * Math.floor(1000000));
  1114. menu.attr('data-write', menu.attr('data-write') + id);
  1115. menu.attr('data-preview', menu.attr('data-preview') + id);
  1116. menu.find('.item').each(function() {
  1117. const tab = $(this).attr('data-tab') + id;
  1118. $(this).attr('data-tab', tab);
  1119. });
  1120. menu.parent().find("*[data-tab='write']").attr('data-tab', 'write' + id);
  1121. menu.parent().find("*[data-tab='preview']").attr('data-tab', 'preview' + id);
  1122. initCommentPreviewTab(menu.parent(".form"));
  1123. return id;
  1124. }
  1125. function initRepositoryCollaboration() {
  1126. // Change collaborator access mode
  1127. $('.access-mode.menu .item').click(function () {
  1128. const $menu = $(this).parent();
  1129. $.post($menu.data('url'), {
  1130. "_csrf": csrf,
  1131. "uid": $menu.data('uid'),
  1132. "mode": $(this).data('value')
  1133. })
  1134. });
  1135. }
  1136. function initTeamSettings() {
  1137. // Change team access mode
  1138. $('.organization.new.team input[name=permission]').change(function () {
  1139. const val = $('input[name=permission]:checked', '.organization.new.team').val()
  1140. if (val === 'admin') {
  1141. $('.organization.new.team .team-units').hide();
  1142. } else {
  1143. $('.organization.new.team .team-units').show();
  1144. }
  1145. });
  1146. }
  1147. function initWikiForm() {
  1148. const $editArea = $('.repository.wiki textarea#edit_area');
  1149. if ($editArea.length > 0) {
  1150. const simplemde = new SimpleMDE({
  1151. autoDownloadFontAwesome: false,
  1152. element: $editArea[0],
  1153. forceSync: true,
  1154. previewRender: function (plainText, preview) { // Async method
  1155. setTimeout(function () {
  1156. // FIXME: still send render request when return back to edit mode
  1157. $.post($editArea.data('url'), {
  1158. "_csrf": csrf,
  1159. "mode": "gfm",
  1160. "context": $editArea.data('context'),
  1161. "text": plainText
  1162. },
  1163. function (data) {
  1164. preview.innerHTML = '<div class="markdown ui segment">' + data + '</div>';
  1165. emojify.run($('.editor-preview')[0]);
  1166. }
  1167. );
  1168. }, 0);
  1169. return "Loading...";
  1170. },
  1171. renderingConfig: {
  1172. singleLineBreaks: false
  1173. },
  1174. indentWithTabs: false,
  1175. tabSize: 4,
  1176. spellChecker: false,
  1177. toolbar: ["bold", "italic", "strikethrough", "|",
  1178. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  1179. {
  1180. name: "code-inline",
  1181. action: function(e){
  1182. const cm = e.codemirror;
  1183. const selection = cm.getSelection();
  1184. cm.replaceSelection("`" + selection + "`");
  1185. if (!selection) {
  1186. const cursorPos = cm.getCursor();
  1187. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1188. }
  1189. cm.focus();
  1190. },
  1191. className: "fa fa-angle-right",
  1192. title: "Add Inline Code",
  1193. },"code", "quote", "|", {
  1194. name: "checkbox-empty",
  1195. action: function(e){
  1196. const cm = e.codemirror;
  1197. cm.replaceSelection("\n- [ ] " + cm.getSelection());
  1198. cm.focus();
  1199. },
  1200. className: "fa fa-square-o",
  1201. title: "Add Checkbox (empty)",
  1202. },
  1203. {
  1204. name: "checkbox-checked",
  1205. action: function(e){
  1206. const cm = e.codemirror;
  1207. cm.replaceSelection("\n- [x] " + cm.getSelection());
  1208. cm.focus();
  1209. },
  1210. className: "fa fa-check-square-o",
  1211. title: "Add Checkbox (checked)",
  1212. }, "|",
  1213. "unordered-list", "ordered-list", "|",
  1214. "link", "image", "table", "horizontal-rule", "|",
  1215. "clean-block", "preview", "fullscreen"]
  1216. })
  1217. $(simplemde.codemirror.getInputField()).addClass("js-quick-submit");
  1218. }
  1219. }
  1220. // For IE
  1221. String.prototype.endsWith = function (pattern) {
  1222. const d = this.length - pattern.length;
  1223. return d >= 0 && this.lastIndexOf(pattern) === d;
  1224. };
  1225. // Adding function to get the cursor position in a text field to jQuery object.
  1226. $.fn.getCursorPosition = function () {
  1227. const el = $(this).get(0);
  1228. let pos = 0;
  1229. if ('selectionStart' in el) {
  1230. pos = el.selectionStart;
  1231. } else if ('selection' in document) {
  1232. el.focus();
  1233. const Sel = document.selection.createRange();
  1234. const SelLength = document.selection.createRange().text.length;
  1235. Sel.moveStart('character', -el.value.length);
  1236. pos = Sel.text.length - SelLength;
  1237. }
  1238. return pos;
  1239. }
  1240. function setSimpleMDE($editArea) {
  1241. if (codeMirrorEditor) {
  1242. codeMirrorEditor.toTextArea();
  1243. codeMirrorEditor = null;
  1244. }
  1245. if (simpleMDEditor) {
  1246. return true;
  1247. }
  1248. simpleMDEditor = new SimpleMDE({
  1249. autoDownloadFontAwesome: false,
  1250. element: $editArea[0],
  1251. forceSync: true,
  1252. renderingConfig: {
  1253. singleLineBreaks: false
  1254. },
  1255. indentWithTabs: false,
  1256. tabSize: 4,
  1257. spellChecker: false,
  1258. previewRender: function (plainText, preview) { // Async method
  1259. setTimeout(function () {
  1260. // FIXME: still send render request when return back to edit mode
  1261. $.post($editArea.data('url'), {
  1262. "_csrf": csrf,
  1263. "mode": "gfm",
  1264. "context": $editArea.data('context'),
  1265. "text": plainText
  1266. },
  1267. function (data) {
  1268. preview.innerHTML = '<div class="markdown ui segment">' + data + '</div>';
  1269. emojify.run($('.editor-preview')[0]);
  1270. }
  1271. );
  1272. }, 0);
  1273. return "Loading...";
  1274. },
  1275. toolbar: ["bold", "italic", "strikethrough", "|",
  1276. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  1277. "code", "quote", "|",
  1278. "unordered-list", "ordered-list", "|",
  1279. "link", "image", "table", "horizontal-rule", "|",
  1280. "clean-block", "preview", "fullscreen", "side-by-side"]
  1281. });
  1282. return true;
  1283. }
  1284. function setCodeMirror($editArea) {
  1285. if (simpleMDEditor) {
  1286. simpleMDEditor.toTextArea();
  1287. simpleMDEditor = null;
  1288. }
  1289. if (codeMirrorEditor) {
  1290. return true;
  1291. }
  1292. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  1293. lineNumbers: true
  1294. });
  1295. codeMirrorEditor.on("change", function (cm, _change) {
  1296. $editArea.val(cm.getValue());
  1297. });
  1298. return true;
  1299. }
  1300. function initEditor() {
  1301. $('.js-quick-pull-choice-option').change(function () {
  1302. if ($(this).val() == 'commit-to-new-branch') {
  1303. $('.quick-pull-branch-name').show();
  1304. $('.quick-pull-branch-name input').prop('required',true);
  1305. } else {
  1306. $('.quick-pull-branch-name').hide();
  1307. $('.quick-pull-branch-name input').prop('required',false);
  1308. }
  1309. $('#commit-button').text($(this).attr('button_text'));
  1310. });
  1311. const $editFilename = $("#file-name");
  1312. $editFilename.keyup(function (e) {
  1313. const $section = $('.breadcrumb span.section');
  1314. const $divider = $('.breadcrumb div.divider');
  1315. let value;
  1316. let parts;
  1317. if (e.keyCode == 8) {
  1318. if ($(this).getCursorPosition() == 0) {
  1319. if ($section.length > 0) {
  1320. value = $section.last().find('a').text();
  1321. $(this).val(value + $(this).val());
  1322. $(this)[0].setSelectionRange(value.length, value.length);
  1323. $section.last().remove();
  1324. $divider.last().remove();
  1325. }
  1326. }
  1327. }
  1328. if (e.keyCode == 191) {
  1329. parts = $(this).val().split('/');
  1330. for (let i = 0; i < parts.length; ++i) {
  1331. value = parts[i];
  1332. if (i < parts.length - 1) {
  1333. if (value.length) {
  1334. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  1335. $('<div class="divider"> / </div>').insertBefore($(this));
  1336. }
  1337. }
  1338. else {
  1339. $(this).val(value);
  1340. }
  1341. $(this)[0].setSelectionRange(0, 0);
  1342. }
  1343. }
  1344. parts = [];
  1345. $('.breadcrumb span.section').each(function () {
  1346. const element = $(this);
  1347. if (element.find('a').length) {
  1348. parts.push(element.find('a').text());
  1349. } else {
  1350. parts.push(element.text());
  1351. }
  1352. });
  1353. if ($(this).val())
  1354. parts.push($(this).val());
  1355. $('#tree_path').val(parts.join('/'));
  1356. }).trigger('keyup');
  1357. const $editArea = $('.repository.editor textarea#edit_area');
  1358. if (!$editArea.length)
  1359. return;
  1360. const markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  1361. const lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  1362. $editFilename.on("keyup", function () {
  1363. const val = $editFilename.val();
  1364. let mode, spec, extension, extWithDot, dataUrl, apiCall;
  1365. extension = extWithDot = "";
  1366. const m = /.+\.([^.]+)$/.exec(val);
  1367. if (m) {
  1368. extension = m[1];
  1369. extWithDot = "." + extension;
  1370. }
  1371. const info = CodeMirror.findModeByExtension(extension);
  1372. const previewLink = $('a[data-tab=preview]');
  1373. if (info) {
  1374. mode = info.mode;
  1375. spec = info.mime;
  1376. apiCall = mode;
  1377. }
  1378. else {
  1379. apiCall = extension
  1380. }
  1381. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  1382. dataUrl = previewLink.data('url');
  1383. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  1384. previewLink.show();
  1385. }
  1386. else {
  1387. previewLink.hide();
  1388. }
  1389. // If this file is a Markdown extensions, we will load that editor and return
  1390. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  1391. if (setSimpleMDE($editArea)) {
  1392. return;
  1393. }
  1394. }
  1395. // Else we are going to use CodeMirror
  1396. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  1397. return;
  1398. }
  1399. if (mode) {
  1400. codeMirrorEditor.setOption("mode", spec);
  1401. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  1402. }
  1403. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  1404. codeMirrorEditor.setOption("lineWrapping", true);
  1405. }
  1406. else {
  1407. codeMirrorEditor.setOption("lineWrapping", false);
  1408. }
  1409. // get the filename without any folder
  1410. let value = $editFilename.val();
  1411. if (value.length === 0) {
  1412. return;
  1413. }
  1414. value = value.split('/');
  1415. value = value[value.length - 1];
  1416. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  1417. if (editorconfig.indent_style === 'tab') {
  1418. codeMirrorEditor.setOption("indentWithTabs", true);
  1419. codeMirrorEditor.setOption('extraKeys', {});
  1420. } else {
  1421. codeMirrorEditor.setOption("indentWithTabs", false);
  1422. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  1423. // - https://github.com/codemirror/CodeMirror/issues/988
  1424. // - https://codemirror.net/doc/manual.html#keymaps
  1425. codeMirrorEditor.setOption('extraKeys', {
  1426. Tab: function(cm) {
  1427. const spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  1428. cm.replaceSelection(spaces);
  1429. }
  1430. });
  1431. }
  1432. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  1433. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  1434. });
  1435. }).trigger('keyup');
  1436. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1437. // to enable or disable the commit button
  1438. const $commitButton = $('#commit-button');
  1439. const $editForm = $('.ui.edit.form');
  1440. const dirtyFileClass = 'dirty-file';
  1441. // Disabling the button at the start
  1442. $commitButton.prop('disabled', true);
  1443. // Registering a custom listener for the file path and the file content
  1444. $editForm.areYouSure({
  1445. silent: true,
  1446. dirtyClass: dirtyFileClass,
  1447. fieldSelector: ':input:not(.commit-form-wrapper :input)',
  1448. change: function () {
  1449. const dirty = $(this).hasClass(dirtyFileClass);
  1450. $commitButton.prop('disabled', !dirty);
  1451. }
  1452. });
  1453. $commitButton.click(function (event) {
  1454. // A modal which asks if an empty file should be committed
  1455. if ($editArea.val().length === 0) {
  1456. $('#edit-empty-content-modal').modal({
  1457. onApprove: function () {
  1458. $('.edit.form').submit();
  1459. }
  1460. }).modal('show');
  1461. event.preventDefault();
  1462. }
  1463. });
  1464. }
  1465. function initOrganization() {
  1466. if ($('.organization').length == 0) {
  1467. return;
  1468. }
  1469. // Options
  1470. if ($('.organization.settings.options').length > 0) {
  1471. $('#org_name').keyup(function () {
  1472. const $prompt = $('#org-name-change-prompt');
  1473. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  1474. $prompt.show();
  1475. } else {
  1476. $prompt.hide();
  1477. }
  1478. });
  1479. }
  1480. }
  1481. function initUserSettings() {
  1482. // Options
  1483. if ($('.user.settings.profile').length > 0) {
  1484. $('#username').keyup(function () {
  1485. const $prompt = $('#name-change-prompt');
  1486. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1487. $prompt.show();
  1488. } else {
  1489. $prompt.hide();
  1490. }
  1491. });
  1492. }
  1493. }
  1494. function initWebhook() {
  1495. if ($('.new.webhook').length == 0) {
  1496. return;
  1497. }
  1498. $('.events.checkbox input').change(function () {
  1499. if ($(this).is(':checked')) {
  1500. $('.events.fields').show();
  1501. }
  1502. });
  1503. $('.non-events.checkbox input').change(function () {
  1504. if ($(this).is(':checked')) {
  1505. $('.events.fields').hide();
  1506. }
  1507. });
  1508. const updateContentType = function () {
  1509. const visible = $('#http_method').val() === 'POST';
  1510. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1511. };
  1512. updateContentType();
  1513. $('#http_method').change(function () {
  1514. updateContentType();
  1515. });
  1516. // Test delivery
  1517. $('#test-delivery').click(function () {
  1518. const $this = $(this);
  1519. $this.addClass('loading disabled');
  1520. $.post($this.data('link'), {
  1521. "_csrf": csrf
  1522. }).done(
  1523. setTimeout(function () {
  1524. window.location.href = $this.data('redirect');
  1525. }, 5000)
  1526. )
  1527. });
  1528. }
  1529. function initAdmin() {
  1530. if ($('.admin').length == 0) {
  1531. return;
  1532. }
  1533. // New user
  1534. if ($('.admin.new.user').length > 0 ||
  1535. $('.admin.edit.user').length > 0) {
  1536. $('#login_type').change(function () {
  1537. if ($(this).val().substring(0, 1) == '0') {
  1538. $('#login_name').removeAttr('required');
  1539. $('.non-local').hide();
  1540. $('.local').show();
  1541. $('#user_name').focus();
  1542. if ($(this).data('password') == "required") {
  1543. $('#password').attr('required', 'required');
  1544. }
  1545. } else {
  1546. $('#login_name').attr('required', 'required');
  1547. $('.non-local').show();
  1548. $('.local').hide();
  1549. $('#login_name').focus();
  1550. $('#password').removeAttr('required');
  1551. }
  1552. });
  1553. }
  1554. function onSecurityProtocolChange() {
  1555. if ($('#security_protocol').val() > 0) {
  1556. $('.has-tls').show();
  1557. } else {
  1558. $('.has-tls').hide();
  1559. }
  1560. }
  1561. function onUsePagedSearchChange() {
  1562. if ($('#use_paged_search').prop('checked')) {
  1563. $('.search-page-size').show()
  1564. .find('input').attr('required', 'required');
  1565. } else {
  1566. $('.search-page-size').hide()
  1567. .find('input').removeAttr('required');
  1568. }
  1569. }
  1570. function onOAuth2Change() {
  1571. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1572. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1573. const provider = $('#oauth2_provider').val();
  1574. switch (provider) {
  1575. case 'github':
  1576. case 'gitlab':
  1577. case 'gitea':
  1578. $('.oauth2_use_custom_url').show();
  1579. break;
  1580. case 'openidConnect':
  1581. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1582. $('.open_id_connect_auto_discovery_url').show();
  1583. break;
  1584. }
  1585. onOAuth2UseCustomURLChange();
  1586. }
  1587. function onOAuth2UseCustomURLChange() {
  1588. const provider = $('#oauth2_provider').val();
  1589. $('.oauth2_use_custom_url_field').hide();
  1590. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1591. if ($('#oauth2_use_custom_url').is(':checked')) {
  1592. if (!$('#oauth2_token_url').val()) {
  1593. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  1594. }
  1595. if (!$('#oauth2_auth_url').val()) {
  1596. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  1597. }
  1598. if (!$('#oauth2_profile_url').val()) {
  1599. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  1600. }
  1601. if (!$('#oauth2_email_url').val()) {
  1602. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  1603. }
  1604. switch (provider) {
  1605. case 'github':
  1606. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1607. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1608. break;
  1609. case 'gitea':
  1610. case 'gitlab':
  1611. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1612. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1613. $('#oauth2_email_url').val('');
  1614. break;
  1615. }
  1616. }
  1617. }
  1618. // New authentication
  1619. if ($('.admin.new.authentication').length > 0) {
  1620. $('#auth_type').change(function () {
  1621. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls .search-page-size').hide();
  1622. $('.ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required]').removeAttr('required');
  1623. $('.binddnrequired').removeClass("required");
  1624. const authType = $(this).val();
  1625. switch (authType) {
  1626. case '2': // LDAP
  1627. $('.ldap').show();
  1628. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1629. $('.binddnrequired').addClass("required");
  1630. break;
  1631. case '3': // SMTP
  1632. $('.smtp').show();
  1633. $('.has-tls').show();
  1634. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1635. break;
  1636. case '4': // PAM
  1637. $('.pam').show();
  1638. $('.pam input').attr('required', 'required');
  1639. break;
  1640. case '5': // LDAP
  1641. $('.dldap').show();
  1642. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1643. break;
  1644. case '6': // OAuth2
  1645. $('.oauth2').show();
  1646. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1647. onOAuth2Change();
  1648. break;
  1649. }
  1650. if (authType == '2' || authType == '5') {
  1651. onSecurityProtocolChange()
  1652. }
  1653. if (authType == '2') {
  1654. onUsePagedSearchChange();
  1655. }
  1656. });
  1657. $('#auth_type').change();
  1658. $('#security_protocol').change(onSecurityProtocolChange);
  1659. $('#use_paged_search').change(onUsePagedSearchChange);
  1660. $('#oauth2_provider').change(onOAuth2Change);
  1661. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1662. }
  1663. // Edit authentication
  1664. if ($('.admin.edit.authentication').length > 0) {
  1665. const authType = $('#auth_type').val();
  1666. if (authType == '2' || authType == '5') {
  1667. $('#security_protocol').change(onSecurityProtocolChange);
  1668. if (authType == '2') {
  1669. $('#use_paged_search').change(onUsePagedSearchChange);
  1670. }
  1671. } else if (authType == '6') {
  1672. $('#oauth2_provider').change(onOAuth2Change);
  1673. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1674. onOAuth2Change();
  1675. }
  1676. }
  1677. // Notice
  1678. if ($('.admin.notice')) {
  1679. const $detailModal = $('#detail-modal');
  1680. // Attach view detail modals
  1681. $('.view-detail').click(function () {
  1682. $detailModal.find('.content p').text($(this).data('content'));
  1683. $detailModal.modal('show');
  1684. return false;
  1685. });
  1686. // Select actions
  1687. const $checkboxes = $('.select.table .ui.checkbox');
  1688. $('.select.action').click(function () {
  1689. switch ($(this).data('action')) {
  1690. case 'select-all':
  1691. $checkboxes.checkbox('check');
  1692. break;
  1693. case 'deselect-all':
  1694. $checkboxes.checkbox('uncheck');
  1695. break;
  1696. case 'inverse':
  1697. $checkboxes.checkbox('toggle');
  1698. break;
  1699. }
  1700. });
  1701. $('#delete-selection').click(function () {
  1702. const $this = $(this);
  1703. $this.addClass("loading disabled");
  1704. const ids = [];
  1705. $checkboxes.each(function () {
  1706. if ($(this).checkbox('is checked')) {
  1707. ids.push($(this).data('id'));
  1708. }
  1709. });
  1710. $.post($this.data('link'), {
  1711. "_csrf": csrf,
  1712. "ids": ids
  1713. }).done(function () {
  1714. window.location.href = $this.data('redirect');
  1715. });
  1716. });
  1717. }
  1718. }
  1719. function buttonsClickOnEnter() {
  1720. $('.ui.button').keypress(function (e) {
  1721. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1722. $(this).click();
  1723. });
  1724. }
  1725. function searchUsers() {
  1726. const $searchUserBox = $('#search-user-box');
  1727. $searchUserBox.search({
  1728. minCharacters: 2,
  1729. apiSettings: {
  1730. url: suburl + '/api/v1/users/search?q={query}',
  1731. onResponse: function(response) {
  1732. const items = [];
  1733. $.each(response.data, function (_i, item) {
  1734. let title = item.login;
  1735. if (item.full_name && item.full_name.length > 0) {
  1736. title += ' (' + htmlEncode(item.full_name) + ')';
  1737. }
  1738. items.push({
  1739. title: title,
  1740. image: item.avatar_url
  1741. })
  1742. });
  1743. return { results: items }
  1744. }
  1745. },
  1746. searchFields: ['login', 'full_name'],
  1747. showNoResults: false
  1748. });
  1749. }
  1750. function searchTeams() {
  1751. const $searchTeamBox = $('#search-team-box');
  1752. $searchTeamBox.search({
  1753. minCharacters: 2,
  1754. apiSettings: {
  1755. url: suburl + '/api/v1/orgs/' + $searchTeamBox.data('org') + '/teams/search?q={query}',
  1756. headers: {"X-Csrf-Token": csrf},
  1757. onResponse: function(response) {
  1758. const items = [];
  1759. $.each(response.data, function (_i, item) {
  1760. const title = item.name + ' (' + item.permission + ' access)';
  1761. items.push({
  1762. title: title,
  1763. })
  1764. });
  1765. return { results: items }
  1766. }
  1767. },
  1768. searchFields: ['name', 'description'],
  1769. showNoResults: false
  1770. });
  1771. }
  1772. function searchRepositories() {
  1773. const $searchRepoBox = $('#search-repo-box');
  1774. $searchRepoBox.search({
  1775. minCharacters: 2,
  1776. apiSettings: {
  1777. url: suburl + '/api/v1/repos/search?q={query}&uid=' + $searchRepoBox.data('uid'),
  1778. onResponse: function(response) {
  1779. const items = [];
  1780. $.each(response.data, function (_i, item) {
  1781. items.push({
  1782. title: item.full_name.split("/")[1],
  1783. description: item.full_name
  1784. })
  1785. });
  1786. return { results: items }
  1787. }
  1788. },
  1789. searchFields: ['full_name'],
  1790. showNoResults: false
  1791. });
  1792. }
  1793. function initCodeView() {
  1794. if ($('.code-view .linenums').length > 0) {
  1795. $(document).on('click', '.lines-num span', function (e) {
  1796. const $select = $(this);
  1797. const $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1798. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1799. deSelect();
  1800. });
  1801. $(window).on('hashchange', function () {
  1802. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1803. const $list = $('.code-view ol.linenums > li');
  1804. let $first;
  1805. if (m) {
  1806. $first = $list.filter('.' + m[1]);
  1807. selectRange($list, $first, $list.filter('.' + m[2]));
  1808. $("html, body").scrollTop($first.offset().top - 200);
  1809. return;
  1810. }
  1811. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1812. if (m) {
  1813. $first = $list.filter('.L' + m[2]);
  1814. selectRange($list, $first);
  1815. $("html, body").scrollTop($first.offset().top - 200);
  1816. }
  1817. }).trigger('hashchange');
  1818. }
  1819. }
  1820. function initU2FAuth() {
  1821. if($('#wait-for-key').length === 0) {
  1822. return
  1823. }
  1824. u2fApi.ensureSupport()
  1825. .then(function () {
  1826. $.getJSON(suburl + '/user/u2f/challenge').success(function(req) {
  1827. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1828. .then(u2fSigned)
  1829. .catch(function (err) {
  1830. if(err === undefined) {
  1831. u2fError(1);
  1832. return
  1833. }
  1834. u2fError(err.metaData.code);
  1835. });
  1836. });
  1837. }).catch(function () {
  1838. // Fallback in case browser do not support U2F
  1839. window.location.href = suburl + "/user/two_factor"
  1840. })
  1841. }
  1842. function u2fSigned(resp) {
  1843. $.ajax({
  1844. url: suburl + '/user/u2f/sign',
  1845. type: "POST",
  1846. headers: {"X-Csrf-Token": csrf},
  1847. data: JSON.stringify(resp),
  1848. contentType: "application/json; charset=utf-8",
  1849. }).done(function(res){
  1850. window.location.replace(res);
  1851. }).fail(function () {
  1852. u2fError(1);
  1853. });
  1854. }
  1855. function u2fRegistered(resp) {
  1856. if (checkError(resp)) {
  1857. return;
  1858. }
  1859. $.ajax({
  1860. url: suburl + '/user/settings/security/u2f/register',
  1861. type: "POST",
  1862. headers: {"X-Csrf-Token": csrf},
  1863. data: JSON.stringify(resp),
  1864. contentType: "application/json; charset=utf-8",
  1865. success: function(){
  1866. reload();
  1867. },
  1868. fail: function () {
  1869. u2fError(1);
  1870. }
  1871. });
  1872. }
  1873. function checkError(resp) {
  1874. if (!('errorCode' in resp)) {
  1875. return false;
  1876. }
  1877. if (resp.errorCode === 0) {
  1878. return false;
  1879. }
  1880. u2fError(resp.errorCode);
  1881. return true;
  1882. }
  1883. function u2fError(errorType) {
  1884. const u2fErrors = {
  1885. 'browser': $('#unsupported-browser'),
  1886. 1: $('#u2f-error-1'),
  1887. 2: $('#u2f-error-2'),
  1888. 3: $('#u2f-error-3'),
  1889. 4: $('#u2f-error-4'),
  1890. 5: $('.u2f-error-5')
  1891. };
  1892. u2fErrors[errorType].removeClass('hide');
  1893. for(const type in u2fErrors){
  1894. if(type != errorType){
  1895. u2fErrors[type].addClass('hide');
  1896. }
  1897. }
  1898. $('#u2f-error').modal('show');
  1899. }
  1900. function initU2FRegister() {
  1901. $('#register-device').modal({allowMultiple: false});
  1902. $('#u2f-error').modal({allowMultiple: false});
  1903. $('#register-security-key').on('click', function(e) {
  1904. e.preventDefault();
  1905. u2fApi.ensureSupport()
  1906. .then(u2fRegisterRequest)
  1907. .catch(function() {
  1908. u2fError('browser');
  1909. })
  1910. })
  1911. }
  1912. function u2fRegisterRequest() {
  1913. $.post(suburl + "/user/settings/security/u2f/request_register", {
  1914. "_csrf": csrf,
  1915. "name": $('#nickname').val()
  1916. }).success(function(req) {
  1917. $("#nickname").closest("div.field").removeClass("error");
  1918. $('#register-device').modal('show');
  1919. if(req.registeredKeys === null) {
  1920. req.registeredKeys = []
  1921. }
  1922. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1923. .then(u2fRegistered)
  1924. .catch(function (reason) {
  1925. if(reason === undefined) {
  1926. u2fError(1);
  1927. return
  1928. }
  1929. u2fError(reason.metaData.code);
  1930. });
  1931. }).fail(function(xhr) {
  1932. if(xhr.status === 409) {
  1933. $("#nickname").closest("div.field").addClass("error");
  1934. }
  1935. });
  1936. }
  1937. function initWipTitle() {
  1938. $(".title_wip_desc > a").click(function (e) {
  1939. e.preventDefault();
  1940. const $issueTitle = $("#issue_title");
  1941. $issueTitle.focus();
  1942. const value = $issueTitle.val().trim().toUpperCase();
  1943. for (const i in wipPrefixes) {
  1944. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1945. return;
  1946. }
  1947. }
  1948. $issueTitle.val(wipPrefixes[0] + " " + $issueTitle.val());
  1949. });
  1950. }
  1951. $(document).ready(function () {
  1952. csrf = $('meta[name=_csrf]').attr("content");
  1953. suburl = $('meta[name=_suburl]').attr("content");
  1954. // Show exact time
  1955. $('.time-since').each(function () {
  1956. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1957. });
  1958. // Semantic UI modules.
  1959. $('.dropdown:not(.custom)').dropdown();
  1960. $('.jump.dropdown').dropdown({
  1961. action: 'hide',
  1962. onShow: function () {
  1963. $('.poping.up').popup('hide');
  1964. }
  1965. });
  1966. $('.slide.up.dropdown').dropdown({
  1967. transition: 'slide up'
  1968. });
  1969. $('.upward.dropdown').dropdown({
  1970. direction: 'upward'
  1971. });
  1972. $('.ui.accordion').accordion();
  1973. $('.ui.checkbox').checkbox();
  1974. $('.ui.progress').progress({
  1975. showActivity: false
  1976. });
  1977. $('.poping.up').popup();
  1978. $('.top.menu .poping.up').popup({
  1979. onShow: function () {
  1980. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1981. return false;
  1982. }
  1983. }
  1984. });
  1985. $('.tabular.menu .item').tab();
  1986. $('.tabable.menu .item').tab();
  1987. $('.toggle.button').click(function () {
  1988. $($(this).data('target')).slideToggle(100);
  1989. });
  1990. // make table <tr> element clickable like a link
  1991. $('tr[data-href]').click(function() {
  1992. window.location = $(this).data('href');
  1993. });
  1994. // Highlight JS
  1995. if (typeof hljs != 'undefined') {
  1996. const nodes = [].slice.call(document.querySelectorAll('pre code') || []);
  1997. for (let i = 0; i < nodes.length; i++) {
  1998. hljs.highlightBlock(nodes[i]);
  1999. }
  2000. }
  2001. // Dropzone
  2002. const $dropzone = $('#dropzone');
  2003. if ($dropzone.length > 0) {
  2004. const filenameDict = {};
  2005. new Dropzone("#dropzone", {
  2006. url: $dropzone.data('upload-url'),
  2007. headers: {"X-Csrf-Token": csrf},
  2008. maxFiles: $dropzone.data('max-file'),
  2009. maxFilesize: $dropzone.data('max-size'),
  2010. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  2011. addRemoveLinks: true,
  2012. dictDefaultMessage: $dropzone.data('default-message'),
  2013. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  2014. dictFileTooBig: $dropzone.data('file-too-big'),
  2015. dictRemoveFile: $dropzone.data('remove-file'),
  2016. init: function () {
  2017. this.on("success", function (file, data) {
  2018. filenameDict[file.name] = data.uuid;
  2019. const input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  2020. $('.files').append(input);
  2021. });
  2022. this.on("removedfile", function (file) {
  2023. if (file.name in filenameDict) {
  2024. $('#' + filenameDict[file.name]).remove();
  2025. }
  2026. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  2027. $.post($dropzone.data('remove-url'), {
  2028. file: filenameDict[file.name],
  2029. _csrf: $dropzone.data('csrf')
  2030. });
  2031. }
  2032. })
  2033. },
  2034. });
  2035. }
  2036. // Emojify
  2037. emojify.setConfig({
  2038. img_dir: suburl + '/vendor/plugins/emojify/images',
  2039. ignore_emoticons: true
  2040. });
  2041. const hasEmoji = document.getElementsByClassName('has-emoji');
  2042. for (let i = 0; i < hasEmoji.length; i++) {
  2043. emojify.run(hasEmoji[i]);
  2044. for (let j = 0; j < hasEmoji[i].childNodes.length; j++) {
  2045. if (hasEmoji[i].childNodes[j].nodeName === "A") {
  2046. emojify.run(hasEmoji[i].childNodes[j])
  2047. }
  2048. }
  2049. }
  2050. // Clipboard JS
  2051. const clipboard = new Clipboard('.clipboard');
  2052. clipboard.on('success', function (e) {
  2053. e.clearSelection();
  2054. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  2055. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  2056. $('#' + e.trigger.getAttribute('id')).popup('show');
  2057. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  2058. });
  2059. clipboard.on('error', function (e) {
  2060. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  2061. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  2062. $('#' + e.trigger.getAttribute('id')).popup('show');
  2063. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  2064. });
  2065. // Helpers.
  2066. $('.delete-button').click(showDeletePopup);
  2067. $('.delete-branch-button').click(showDeletePopup);
  2068. $('.undo-button').click(function() {
  2069. const $this = $(this);
  2070. $.post($this.data('url'), {
  2071. "_csrf": csrf,
  2072. "id": $this.data("id")
  2073. }).done(function(data) {
  2074. window.location.href = data.redirect;
  2075. });
  2076. });
  2077. $('.show-panel.button').click(function () {
  2078. $($(this).data('panel')).show();
  2079. });
  2080. $('.show-modal.button').click(function () {
  2081. $($(this).data('modal')).modal('show');
  2082. });
  2083. $('.delete-post.button').click(function () {
  2084. const $this = $(this);
  2085. $.post($this.data('request-url'), {
  2086. "_csrf": csrf
  2087. }).done(function () {
  2088. window.location.href = $this.data('done-url');
  2089. });
  2090. });
  2091. // Set anchor.
  2092. $('.markdown').each(function () {
  2093. const headers = {};
  2094. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  2095. let node = $(this);
  2096. const val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  2097. let name = val;
  2098. if (headers[val] > 0) {
  2099. name = val + '-' + headers[val];
  2100. }
  2101. if (headers[val] == undefined) {
  2102. headers[val] = 1;
  2103. } else {
  2104. headers[val] += 1;
  2105. }
  2106. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  2107. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  2108. });
  2109. });
  2110. $('.issue-checkbox').click(function() {
  2111. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2112. if (numChecked > 0) {
  2113. $('#issue-filters').addClass("hide");
  2114. $('#issue-actions').removeClass("hide");
  2115. } else {
  2116. $('#issue-filters').removeClass("hide");
  2117. $('#issue-actions').addClass("hide");
  2118. }
  2119. });
  2120. $('.issue-action').click(function () {
  2121. let action = this.dataset.action;
  2122. let elementId = this.dataset.elementId;
  2123. const issueIDs = $('.issue-checkbox').children('input:checked').map(function() {
  2124. return this.dataset.issueId;
  2125. }).get().join();
  2126. const url = this.dataset.url;
  2127. if (elementId === '0' && url.substr(-9) === '/assignee'){
  2128. elementId = '';
  2129. action = 'clear';
  2130. }
  2131. updateIssuesMeta(url, action, issueIDs, elementId).then(function() {
  2132. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2133. if (action === "close" || action === "open" ){
  2134. //uncheck all checkboxes
  2135. $('.issue-checkbox input[type="checkbox"]').each(function(_,e){ e.checked = false; });
  2136. }
  2137. reload();
  2138. });
  2139. });
  2140. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2141. // trigger ckecked event, if checkboxes are checked on load
  2142. $('.issue-checkbox input[type="checkbox"]:checked').first().each(function(_,e) {
  2143. e.checked = false;
  2144. $(e).click();
  2145. });
  2146. buttonsClickOnEnter();
  2147. searchUsers();
  2148. searchTeams();
  2149. searchRepositories();
  2150. initCommentForm();
  2151. initInstall();
  2152. initRepository();
  2153. initMigration();
  2154. initWikiForm();
  2155. initEditForm();
  2156. initEditor();
  2157. initOrganization();
  2158. initWebhook();
  2159. initAdmin();
  2160. initCodeView();
  2161. initVueApp();
  2162. initTeamSettings();
  2163. initCtrlEnterSubmit();
  2164. initNavbarContentToggle();
  2165. initTopicbar();
  2166. initU2FAuth();
  2167. initU2FRegister();
  2168. initIssueList();
  2169. initWipTitle();
  2170. initPullRequestReview();
  2171. initRepoStatusChecker();
  2172. // Repo clone url.
  2173. if ($('#repo-clone-url').length > 0) {
  2174. switch (localStorage.getItem('repo-clone-protocol')) {
  2175. case 'ssh':
  2176. if ($('#repo-clone-ssh').click().length === 0) {
  2177. $('#repo-clone-https').click();
  2178. }
  2179. break;
  2180. default:
  2181. $('#repo-clone-https').click();
  2182. break;
  2183. }
  2184. }
  2185. const routes = {
  2186. 'div.user.settings': initUserSettings,
  2187. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2188. };
  2189. let selector;
  2190. for (selector in routes) {
  2191. if ($(selector).length > 0) {
  2192. routes[selector]();
  2193. break;
  2194. }
  2195. }
  2196. const $cloneAddr = $('#clone_addr');
  2197. $cloneAddr.change(function() {
  2198. const $repoName = $('#repo_name');
  2199. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank
  2200. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2201. }
  2202. });
  2203. });
  2204. function changeHash(hash) {
  2205. if (history.pushState) {
  2206. history.pushState(null, null, hash);
  2207. }
  2208. else {
  2209. location.hash = hash;
  2210. }
  2211. }
  2212. function deSelect() {
  2213. if (window.getSelection) {
  2214. window.getSelection().removeAllRanges();
  2215. } else {
  2216. document.selection.empty();
  2217. }
  2218. }
  2219. function selectRange($list, $select, $from) {
  2220. $list.removeClass('active');
  2221. if ($from) {
  2222. let a = parseInt($select.attr('rel').substr(1));
  2223. let b = parseInt($from.attr('rel').substr(1));
  2224. let c;
  2225. if (a != b) {
  2226. if (a > b) {
  2227. c = a;
  2228. a = b;
  2229. b = c;
  2230. }
  2231. const classes = [];
  2232. for (let i = a; i <= b; i++) {
  2233. classes.push('.L' + i);
  2234. }
  2235. $list.filter(classes.join(',')).addClass('active');
  2236. changeHash('#L' + a + '-' + 'L' + b);
  2237. return
  2238. }
  2239. }
  2240. $select.addClass('active');
  2241. changeHash('#' + $select.attr('rel'));
  2242. }
  2243. $(function () {
  2244. // Warn users that try to leave a page after entering data into a form.
  2245. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2246. if ($('.user.signin').length === 0) {
  2247. $('form:not(.ignore-dirty)').areYouSure();
  2248. }
  2249. // Parse SSH Key
  2250. $("#ssh-key-content").on('change paste keyup',function(){
  2251. const arrays = $(this).val().split(" ");
  2252. const $title = $("#ssh-key-title")
  2253. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  2254. $title.val(arrays[2]);
  2255. }
  2256. });
  2257. });
  2258. function showDeletePopup() {
  2259. const $this = $(this);
  2260. let filter = "";
  2261. if ($this.attr("id")) {
  2262. filter += "#" + $this.attr("id")
  2263. }
  2264. const dialog = $('.delete.modal' + filter);
  2265. dialog.find('.name').text($this.data('name'));
  2266. dialog.modal({
  2267. closable: false,
  2268. onApprove: function() {
  2269. if ($this.data('type') == "form") {
  2270. $($this.data('form')).submit();
  2271. return;
  2272. }
  2273. $.post($this.data('url'), {
  2274. "_csrf": csrf,
  2275. "id": $this.data("id")
  2276. }).done(function(data) {
  2277. window.location.href = data.redirect;
  2278. });
  2279. }
  2280. }).modal('show');
  2281. return false;
  2282. }
  2283. function initVueComponents(){
  2284. const vueDelimeters = ['${', '}'];
  2285. Vue.component('repo-search', {
  2286. delimiters: vueDelimeters,
  2287. props: {
  2288. searchLimit: {
  2289. type: Number,
  2290. default: 10
  2291. },
  2292. suburl: {
  2293. type: String,
  2294. required: true
  2295. },
  2296. uid: {
  2297. type: Number,
  2298. required: true
  2299. },
  2300. organizations: {
  2301. type: Array,
  2302. default: []
  2303. },
  2304. isOrganization: {
  2305. type: Boolean,
  2306. default: true
  2307. },
  2308. canCreateOrganization: {
  2309. type: Boolean,
  2310. default: false
  2311. },
  2312. organizationsTotalCount: {
  2313. type: Number,
  2314. default: 0
  2315. },
  2316. moreReposLink: {
  2317. type: String,
  2318. default: ''
  2319. }
  2320. },
  2321. data: function() {
  2322. return {
  2323. tab: 'repos',
  2324. repos: [],
  2325. reposTotalCount: 0,
  2326. reposFilter: 'all',
  2327. searchQuery: '',
  2328. isLoading: false,
  2329. repoTypes: {
  2330. 'all': {
  2331. count: 0,
  2332. searchMode: '',
  2333. },
  2334. 'forks': {
  2335. count: 0,
  2336. searchMode: 'fork',
  2337. },
  2338. 'mirrors': {
  2339. count: 0,
  2340. searchMode: 'mirror',
  2341. },
  2342. 'sources': {
  2343. count: 0,
  2344. searchMode: 'source',
  2345. },
  2346. 'collaborative': {
  2347. count: 0,
  2348. searchMode: 'collaborative',
  2349. },
  2350. }
  2351. }
  2352. },
  2353. computed: {
  2354. showMoreReposLink: function() {
  2355. return this.repos.length > 0 && this.repos.length < this.repoTypes[this.reposFilter].count;
  2356. },
  2357. searchURL: function() {
  2358. return this.suburl + '/api/v1/repos/search?sort=updated&order=desc&uid=' + this.uid + '&q=' + this.searchQuery
  2359. + '&limit=' + this.searchLimit + '&mode=' + this.repoTypes[this.reposFilter].searchMode
  2360. + (this.reposFilter !== 'all' ? '&exclusive=1' : '');
  2361. },
  2362. repoTypeCount: function() {
  2363. return this.repoTypes[this.reposFilter].count;
  2364. }
  2365. },
  2366. mounted: function() {
  2367. this.searchRepos(this.reposFilter);
  2368. const self = this;
  2369. Vue.nextTick(function() {
  2370. self.$refs.search.focus();
  2371. });
  2372. },
  2373. methods: {
  2374. changeTab: function(t) {
  2375. this.tab = t;
  2376. },
  2377. changeReposFilter: function(filter) {
  2378. this.reposFilter = filter;
  2379. this.repos = [];
  2380. this.repoTypes[filter].count = 0;
  2381. this.searchRepos(filter);
  2382. },
  2383. showRepo: function(repo, filter) {
  2384. switch (filter) {
  2385. case 'sources':
  2386. return repo.owner.id == this.uid && !repo.mirror && !repo.fork;
  2387. case 'forks':
  2388. return repo.owner.id == this.uid && !repo.mirror && repo.fork;
  2389. case 'mirrors':
  2390. return repo.mirror;
  2391. case 'collaborative':
  2392. return repo.owner.id != this.uid && !repo.mirror;
  2393. default:
  2394. return true;
  2395. }
  2396. },
  2397. searchRepos: function(reposFilter) {
  2398. const self = this;
  2399. this.isLoading = true;
  2400. const searchedMode = this.repoTypes[reposFilter].searchMode;
  2401. const searchedURL = this.searchURL;
  2402. const searchedQuery = this.searchQuery;
  2403. $.getJSON(searchedURL, function(result, _textStatus, request) {
  2404. if (searchedURL == self.searchURL) {
  2405. self.repos = result.data;
  2406. const count = request.getResponseHeader('X-Total-Count');
  2407. if (searchedQuery === '' && searchedMode === '') {
  2408. self.reposTotalCount = count;
  2409. }
  2410. self.repoTypes[reposFilter].count = count;
  2411. }
  2412. }).always(function() {
  2413. if (searchedURL == self.searchURL) {
  2414. self.isLoading = false;
  2415. }
  2416. });
  2417. },
  2418. repoClass: function(repo) {
  2419. if (repo.fork) {
  2420. return 'octicon octicon-repo-forked';
  2421. } else if (repo.mirror) {
  2422. return 'octicon octicon-repo-clone';
  2423. } else if (repo.private) {
  2424. return 'octicon octicon-lock';
  2425. } else {
  2426. return 'octicon octicon-repo';
  2427. }
  2428. }
  2429. }
  2430. })
  2431. }
  2432. function initCtrlEnterSubmit() {
  2433. $(".js-quick-submit").keydown(function(e) {
  2434. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
  2435. $(this).closest("form").submit();
  2436. }
  2437. });
  2438. }
  2439. function initVueApp() {
  2440. const el = document.getElementById('app');
  2441. if (!el) {
  2442. return;
  2443. }
  2444. initVueComponents();
  2445. new Vue({
  2446. delimiters: ['${', '}'],
  2447. el: el,
  2448. data: {
  2449. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  2450. suburl: document.querySelector('meta[name=_suburl]').content,
  2451. uid: document.querySelector('meta[name=_context_uid]').content,
  2452. },
  2453. });
  2454. }
  2455. function timeAddManual() {
  2456. $('.mini.modal')
  2457. .modal({
  2458. duration: 200,
  2459. onApprove: function() {
  2460. $('#add_time_manual_form').submit();
  2461. }
  2462. }).modal('show')
  2463. ;
  2464. }
  2465. function toggleStopwatch() {
  2466. $("#toggle_stopwatch_form").submit();
  2467. }
  2468. function cancelStopwatch() {
  2469. $("#cancel_stopwatch_form").submit();
  2470. }
  2471. function initHeatmap(appElementId, heatmapUser, locale) {
  2472. const el = document.getElementById(appElementId);
  2473. if (!el) {
  2474. return;
  2475. }
  2476. locale = locale || {};
  2477. locale.contributions = locale.contributions || 'contributions';
  2478. locale.no_contributions = locale.no_contributions || 'No contributions';
  2479. const vueDelimeters = ['${', '}'];
  2480. Vue.component('activity-heatmap', {
  2481. delimiters: vueDelimeters,
  2482. props: {
  2483. user: {
  2484. type: String,
  2485. required: true
  2486. },
  2487. suburl: {
  2488. type: String,
  2489. required: true
  2490. },
  2491. locale: {
  2492. type: Object,
  2493. required: true
  2494. }
  2495. },
  2496. data: function () {
  2497. return {
  2498. isLoading: true,
  2499. colorRange: [],
  2500. endDate: null,
  2501. values: [],
  2502. totalContributions: 0,
  2503. };
  2504. },
  2505. mounted: function() {
  2506. this.colorRange = [
  2507. this.getColor(0),
  2508. this.getColor(1),
  2509. this.getColor(2),
  2510. this.getColor(3),
  2511. this.getColor(4),
  2512. this.getColor(5)
  2513. ];
  2514. this.endDate = new Date();
  2515. this.loadHeatmap(this.user);
  2516. },
  2517. methods: {
  2518. loadHeatmap: function(userName) {
  2519. const self = this;
  2520. $.get(this.suburl + '/api/v1/users/' + userName + '/heatmap', function(chartRawData) {
  2521. const chartData = [];
  2522. for (let i = 0; i < chartRawData.length; i++) {
  2523. self.totalContributions += chartRawData[i].contributions;
  2524. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2525. }
  2526. self.values = chartData;
  2527. self.isLoading = false;
  2528. });
  2529. },
  2530. getColor: function(idx) {
  2531. const el = document.createElement('div');
  2532. el.className = 'heatmap-color-' + idx;
  2533. document.body.appendChild(el);
  2534. const color = getComputedStyle(el).backgroundColor;
  2535. document.body.removeChild(el);
  2536. return color;
  2537. }
  2538. },
  2539. template: '<div><div v-show="isLoading"><slot name="loading"></slot></div><h4 class="total-contributions" v-if="!isLoading"><span v-html="totalContributions"></span> total contributions in the last 12 months</h4><calendar-heatmap v-show="!isLoading" :locale="locale" :no-data-text="locale.no_contributions" :tooltip-unit="locale.contributions" :end-date="endDate" :values="values" :range-color="colorRange" />'
  2540. });
  2541. new Vue({
  2542. delimiters: vueDelimeters,
  2543. el: el,
  2544. data: {
  2545. suburl: document.querySelector('meta[name=_suburl]').content,
  2546. heatmapUser: heatmapUser,
  2547. locale: locale
  2548. },
  2549. });
  2550. }
  2551. function initFilterBranchTagDropdown(selector) {
  2552. $(selector).each(function() {
  2553. const $dropdown = $(this);
  2554. const $data = $dropdown.find('.data');
  2555. const data = {
  2556. items: [],
  2557. mode: $data.data('mode'),
  2558. searchTerm: '',
  2559. noResults: '',
  2560. canCreateBranch: false,
  2561. menuVisible: false,
  2562. active: 0
  2563. };
  2564. $data.find('.item').each(function() {
  2565. data.items.push({
  2566. name: $(this).text(),
  2567. url: $(this).data('url'),
  2568. branch: $(this).hasClass('branch'),
  2569. tag: $(this).hasClass('tag'),
  2570. selected: $(this).hasClass('selected')
  2571. });
  2572. });
  2573. $data.remove();
  2574. new Vue({
  2575. delimiters: ['${', '}'],
  2576. el: this,
  2577. data: data,
  2578. beforeMount: function () {
  2579. const vm = this;
  2580. this.noResults = vm.$el.getAttribute('data-no-results');
  2581. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2582. document.body.addEventListener('click', function(event) {
  2583. if (vm.$el.contains(event.target)) {
  2584. return;
  2585. }
  2586. if (vm.menuVisible) {
  2587. Vue.set(vm, 'menuVisible', false);
  2588. }
  2589. });
  2590. },
  2591. watch: {
  2592. menuVisible: function(visible) {
  2593. if (visible) {
  2594. this.focusSearchField();
  2595. }
  2596. }
  2597. },
  2598. computed: {
  2599. filteredItems: function() {
  2600. const vm = this;
  2601. const items = vm.items.filter(function (item) {
  2602. return ((vm.mode === 'branches' && item.branch)
  2603. || (vm.mode === 'tags' && item.tag))
  2604. && (!vm.searchTerm
  2605. || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2606. });
  2607. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2608. return items;
  2609. },
  2610. showNoResults: function() {
  2611. return this.filteredItems.length === 0
  2612. && !this.showCreateNewBranch;
  2613. },
  2614. showCreateNewBranch: function() {
  2615. const vm = this;
  2616. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2617. return false;
  2618. }
  2619. return vm.items.filter(function (item) {
  2620. return item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  2621. }).length === 0;
  2622. }
  2623. },
  2624. methods: {
  2625. selectItem: function(item) {
  2626. const prev = this.getSelected();
  2627. if (prev !== null) {
  2628. prev.selected = false;
  2629. }
  2630. item.selected = true;
  2631. window.location.href = item.url;
  2632. },
  2633. createNewBranch: function() {
  2634. if (!this.showCreateNewBranch) {
  2635. return;
  2636. }
  2637. this.$refs.newBranchForm.submit();
  2638. },
  2639. focusSearchField: function() {
  2640. const vm = this;
  2641. Vue.nextTick(function() {
  2642. vm.$refs.searchField.focus();
  2643. });
  2644. },
  2645. getSelected: function() {
  2646. for (let i = 0, j = this.items.length; i < j; ++i) {
  2647. if (this.items[i].selected)
  2648. return this.items[i];
  2649. }
  2650. return null;
  2651. },
  2652. getSelectedIndexInFiltered: function() {
  2653. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  2654. if (this.filteredItems[i].selected)
  2655. return i;
  2656. }
  2657. return -1;
  2658. },
  2659. scrollToActive: function() {
  2660. let el = this.$refs['listItem' + this.active];
  2661. if (!el || el.length === 0) {
  2662. return;
  2663. }
  2664. if (Array.isArray(el)) {
  2665. el = el[0];
  2666. }
  2667. const cont = this.$refs.scrollContainer;
  2668. if (el.offsetTop < cont.scrollTop) {
  2669. cont.scrollTop = el.offsetTop;
  2670. }
  2671. else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2672. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2673. }
  2674. },
  2675. keydown: function(event) {
  2676. const vm = this;
  2677. if (event.keyCode === 40) {
  2678. // arrow down
  2679. event.preventDefault();
  2680. if (vm.active === -1) {
  2681. vm.active = vm.getSelectedIndexInFiltered();
  2682. }
  2683. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2684. return;
  2685. }
  2686. vm.active++;
  2687. vm.scrollToActive();
  2688. }
  2689. if (event.keyCode === 38) {
  2690. // arrow up
  2691. event.preventDefault();
  2692. if (vm.active === -1) {
  2693. vm.active = vm.getSelectedIndexInFiltered();
  2694. }
  2695. if (vm.active <= 0) {
  2696. return;
  2697. }
  2698. vm.active--;
  2699. vm.scrollToActive();
  2700. }
  2701. if (event.keyCode == 13) {
  2702. // enter
  2703. event.preventDefault();
  2704. if (vm.active >= vm.filteredItems.length) {
  2705. vm.createNewBranch();
  2706. } else if (vm.active >= 0) {
  2707. vm.selectItem(vm.filteredItems[vm.active]);
  2708. }
  2709. }
  2710. if (event.keyCode == 27) {
  2711. // escape
  2712. event.preventDefault();
  2713. vm.menuVisible = false;
  2714. }
  2715. }
  2716. }
  2717. });
  2718. });
  2719. }
  2720. $(".commit-button").click(function() {
  2721. $(this).parent().find('.commit-body').toggle();
  2722. });
  2723. function initNavbarContentToggle() {
  2724. const content = $('#navbar');
  2725. const toggle = $('#navbar-expand-toggle');
  2726. let isExpanded = false;
  2727. toggle.click(function() {
  2728. isExpanded = !isExpanded;
  2729. if (isExpanded) {
  2730. content.addClass('shown');
  2731. toggle.addClass('active');
  2732. }
  2733. else {
  2734. content.removeClass('shown');
  2735. toggle.removeClass('active');
  2736. }
  2737. });
  2738. }
  2739. function initTopicbar() {
  2740. const mgrBtn = $("#manage_topic");
  2741. const editDiv = $("#topic_edit");
  2742. const viewDiv = $("#repo-topics");
  2743. const saveBtn = $("#save_topic");
  2744. const topicDropdown = $('#topic_edit .dropdown');
  2745. const topicForm = $('#topic_edit.ui.form');
  2746. const topicPrompts = getPrompts();
  2747. mgrBtn.click(function() {
  2748. viewDiv.hide();
  2749. editDiv.css('display', ''); // show Semantic UI Grid
  2750. });
  2751. function getPrompts() {
  2752. const hidePrompt = $("div.hide#validate_prompt"),
  2753. prompts = {
  2754. countPrompt: hidePrompt.children('#count_prompt').text(),
  2755. formatPrompt: hidePrompt.children('#format_prompt').text()
  2756. };
  2757. hidePrompt.remove();
  2758. return prompts;
  2759. }
  2760. saveBtn.click(function() {
  2761. const topics = $("input[name=topics]").val();
  2762. $.post(saveBtn.data('link'), {
  2763. "_csrf": csrf,
  2764. "topics": topics
  2765. }, function(_data, _textStatus, xhr){
  2766. if (xhr.responseJSON.status === 'ok') {
  2767. viewDiv.children(".topic").remove();
  2768. if (topics.length) {
  2769. const topicArray = topics.split(",");
  2770. const last = viewDiv.children("a").last();
  2771. for (let i=0; i < topicArray.length; i++) {
  2772. $('<div class="ui small label topic" style="cursor:pointer;">'+topicArray[i]+'</div>').insertBefore(last)
  2773. }
  2774. }
  2775. editDiv.css('display', 'none');
  2776. viewDiv.show();
  2777. }
  2778. }).fail(function(xhr){
  2779. if (xhr.status === 422) {
  2780. if (xhr.responseJSON.invalidTopics.length > 0) {
  2781. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2782. const invalidTopics = xhr.responseJSON.invalidTopics,
  2783. topicLables = topicDropdown.children('a.ui.label');
  2784. topics.split(',').forEach(function(value, index) {
  2785. for (let i=0; i < invalidTopics.length; i++) {
  2786. if (invalidTopics[i] === value) {
  2787. topicLables.eq(index).removeClass("green").addClass("red");
  2788. }
  2789. }
  2790. });
  2791. } else {
  2792. topicPrompts.countPrompt = xhr.responseJSON.message;
  2793. }
  2794. }
  2795. }).always(function() {
  2796. topicForm.form('validate form');
  2797. });
  2798. });
  2799. topicDropdown.dropdown({
  2800. allowAdditions: true,
  2801. forceSelection: false,
  2802. fields: { name: "description", value: "data-value" },
  2803. saveRemoteData: false,
  2804. label: {
  2805. transition : 'horizontal flip',
  2806. duration : 200,
  2807. variation : false,
  2808. blue : true,
  2809. basic: true,
  2810. },
  2811. className: {
  2812. label: 'ui small label'
  2813. },
  2814. apiSettings: {
  2815. url: suburl + '/api/v1/topics/search?q={query}',
  2816. throttle: 500,
  2817. cache: false,
  2818. onResponse: function(res) {
  2819. const formattedResponse = {
  2820. success: false,
  2821. results: [],
  2822. };
  2823. const stripTags = function (text) {
  2824. return text.replace(/<[^>]*>?/gm, "");
  2825. };
  2826. const query = stripTags(this.urlData.query.trim());
  2827. let found_query = false;
  2828. const current_topics = [];
  2829. topicDropdown.find('div.label.visible.topic,a.label.visible').each(function(_,e){ current_topics.push(e.dataset.value); });
  2830. if (res.topics) {
  2831. let found = false;
  2832. for (let i=0;i < res.topics.length;i++) {
  2833. // skip currently added tags
  2834. if (current_topics.indexOf(res.topics[i].topic_name) != -1){
  2835. continue;
  2836. }
  2837. if (res.topics[i].topic_name.toLowerCase() === query.toLowerCase()){
  2838. found_query = true;
  2839. }
  2840. formattedResponse.results.push({"description": res.topics[i].topic_name, "data-value": res.topics[i].topic_name});
  2841. found = true;
  2842. }
  2843. formattedResponse.success = found;
  2844. }
  2845. if (query.length > 0 && !found_query){
  2846. formattedResponse.success = true;
  2847. formattedResponse.results.unshift({"description": query, "data-value": query});
  2848. } else if (query.length > 0 && found_query) {
  2849. formattedResponse.results.sort(function(a, b){
  2850. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  2851. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  2852. if (a.description > b.description) return -1;
  2853. if (a.description < b.description) return 1;
  2854. return 0;
  2855. });
  2856. }
  2857. return formattedResponse;
  2858. },
  2859. },
  2860. onLabelCreate: function(value) {
  2861. value = value.toLowerCase().trim();
  2862. this.attr("data-value", value).contents().first().replaceWith(value);
  2863. return $(this);
  2864. },
  2865. onAdd: function(addedValue, _addedText, $addedChoice) {
  2866. addedValue = addedValue.toLowerCase().trim();
  2867. $($addedChoice).attr('data-value', addedValue);
  2868. $($addedChoice).attr('data-text', addedValue);
  2869. }
  2870. });
  2871. $.fn.form.settings.rules.validateTopic = function(_values, regExp) {
  2872. const topics = topicDropdown.children('a.ui.label'),
  2873. status = topics.length === 0 || topics.last().attr("data-value").match(regExp);
  2874. if (!status) {
  2875. topics.last().removeClass("green").addClass("red");
  2876. }
  2877. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2878. };
  2879. topicForm.form({
  2880. on: 'change',
  2881. inline : true,
  2882. fields: {
  2883. topics: {
  2884. identifier: 'topics',
  2885. rules: [
  2886. {
  2887. type: 'validateTopic',
  2888. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2889. prompt: topicPrompts.formatPrompt
  2890. },
  2891. {
  2892. type: 'maxCount[25]',
  2893. prompt: topicPrompts.countPrompt
  2894. }
  2895. ]
  2896. },
  2897. }
  2898. });
  2899. }
  2900. function toggleDeadlineForm() {
  2901. $('#deadlineForm').fadeToggle(150);
  2902. }
  2903. function setDeadline() {
  2904. const deadline = $('#deadlineDate').val();
  2905. updateDeadline(deadline);
  2906. }
  2907. function updateDeadline(deadlineString) {
  2908. $('#deadline-err-invalid-date').hide();
  2909. $('#deadline-loader').addClass('loading');
  2910. let realDeadline = null;
  2911. if (deadlineString !== '') {
  2912. const newDate = Date.parse(deadlineString)
  2913. if (isNaN(newDate)) {
  2914. $('#deadline-loader').removeClass('loading');
  2915. $('#deadline-err-invalid-date').show();
  2916. return false;
  2917. }
  2918. realDeadline = new Date(newDate);
  2919. }
  2920. $.ajax($('#update-issue-deadline-form').attr('action') + '/deadline', {
  2921. data: JSON.stringify({
  2922. 'due_date': realDeadline,
  2923. }),
  2924. headers: {
  2925. 'X-Csrf-Token': csrf,
  2926. 'X-Remote': true,
  2927. },
  2928. contentType: 'application/json',
  2929. type: 'POST',
  2930. success: function () {
  2931. reload();
  2932. },
  2933. error: function () {
  2934. $('#deadline-loader').removeClass('loading');
  2935. $('#deadline-err-invalid-date').show();
  2936. }
  2937. });
  2938. }
  2939. function deleteDependencyModal(id, type) {
  2940. $('.remove-dependency')
  2941. .modal({
  2942. closable: false,
  2943. duration: 200,
  2944. onApprove: function () {
  2945. $('#removeDependencyID').val(id);
  2946. $('#dependencyType').val(type);
  2947. $('#removeDependencyForm').submit();
  2948. }
  2949. }).modal('show')
  2950. ;
  2951. }
  2952. function initIssueList() {
  2953. const repolink = $('#repolink').val();
  2954. $('#new-dependency-drop-list')
  2955. .dropdown({
  2956. apiSettings: {
  2957. url: suburl + '/api/v1/repos/' + repolink + '/issues?q={query}',
  2958. onResponse: function(response) {
  2959. const filteredResponse = {'success': true, 'results': []};
  2960. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  2961. // Parse the response from the api to work with our dropdown
  2962. $.each(response, function(_i, issue) {
  2963. // Don't list current issue in the dependency list.
  2964. if(issue.id === currIssueId) {
  2965. return;
  2966. }
  2967. filteredResponse.results.push({
  2968. 'name' : '#' + issue.number + '&nbsp;' + htmlEncode(issue.title),
  2969. 'value' : issue.id
  2970. });
  2971. });
  2972. return filteredResponse;
  2973. },
  2974. cache: false,
  2975. },
  2976. fullTextSearch: true
  2977. });
  2978. $(".menu a.label-filter-item").each(function() {
  2979. $(this).click(function(e) {
  2980. if (e.altKey) {
  2981. e.preventDefault();
  2982. const href = $(this).attr("href");
  2983. const id = $(this).data("label-id");
  2984. const regStr = "labels=(-?[0-9]+%2c)*(" + id + ")(%2c-?[0-9]+)*&";
  2985. const newStr = "labels=$1-$2$3&";
  2986. window.location = href.replace(new RegExp(regStr), newStr);
  2987. }
  2988. });
  2989. });
  2990. $(".menu .ui.dropdown.label-filter").keydown(function(e) {
  2991. if (e.altKey && e.keyCode == 13) {
  2992. const selectedItems = $(".menu .ui.dropdown.label-filter .menu .item.selected");
  2993. if (selectedItems.length > 0) {
  2994. const item = $(selectedItems[0]);
  2995. const href = item.attr("href");
  2996. const id = item.data("label-id");
  2997. const regStr = "labels=(-?[0-9]+%2c)*(" + id + ")(%2c-?[0-9]+)*&";
  2998. const newStr = "labels=$1-$2$3&";
  2999. window.location = href.replace(new RegExp(regStr), newStr);
  3000. }
  3001. }
  3002. });
  3003. }
  3004. function cancelCodeComment(btn) {
  3005. const form = $(btn).closest("form");
  3006. if(form.length > 0 && form.hasClass('comment-form')) {
  3007. form.addClass('hide');
  3008. form.parent().find('button.comment-form-reply').show();
  3009. } else {
  3010. form.closest('.comment-code-cloud').remove()
  3011. }
  3012. }
  3013. function onOAuthLoginClick() {
  3014. const oauthLoader = $('#oauth2-login-loader');
  3015. const oauthNav = $('#oauth2-login-navigator');
  3016. oauthNav.hide();
  3017. oauthLoader.removeClass('disabled');
  3018. setTimeout(function(){
  3019. // recover previous content to let user try again
  3020. // usually redirection will be performed before this action
  3021. oauthLoader.addClass('disabled');
  3022. oauthNav.show();
  3023. },5000);
  3024. }
上海开阖软件有限公司 沪ICP备12045867号-1