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.

index.js 58KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  1. 'use strict';
  2. var csrf;
  3. var suburl;
  4. function initCommentPreviewTab($form) {
  5. var $tabMenu = $form.find('.tabular.menu');
  6. $tabMenu.find('.item').tab();
  7. $tabMenu.find('.item[data-tab="' + $tabMenu.data('preview') + '"]').click(function () {
  8. var $this = $(this);
  9. $.post($this.data('url'), {
  10. "_csrf": csrf,
  11. "mode": "gfm",
  12. "context": $this.data('context'),
  13. "text": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  14. },
  15. function (data) {
  16. var $previewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('preview') + '"]');
  17. $previewPanel.html(data);
  18. emojify.run($previewPanel[0]);
  19. $('pre code', $previewPanel[0]).each(function (i, block) {
  20. hljs.highlightBlock(block);
  21. });
  22. }
  23. );
  24. });
  25. buttonsClickOnEnter();
  26. }
  27. var previewFileModes;
  28. function initEditPreviewTab($form) {
  29. var $tabMenu = $form.find('.tabular.menu');
  30. $tabMenu.find('.item').tab();
  31. var $previewTab = $tabMenu.find('.item[data-tab="' + $tabMenu.data('preview') + '"]');
  32. if ($previewTab.length) {
  33. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  34. $previewTab.click(function () {
  35. var $this = $(this);
  36. $.post($this.data('url'), {
  37. "_csrf": csrf,
  38. "mode": "gfm",
  39. "context": $this.data('context'),
  40. "text": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  41. },
  42. function (data) {
  43. var $previewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('preview') + '"]');
  44. $previewPanel.html(data);
  45. emojify.run($previewPanel[0]);
  46. $('pre code', $previewPanel[0]).each(function (i, block) {
  47. hljs.highlightBlock(block);
  48. });
  49. }
  50. );
  51. });
  52. }
  53. }
  54. function initEditDiffTab($form) {
  55. var $tabMenu = $form.find('.tabular.menu');
  56. $tabMenu.find('.item').tab();
  57. $tabMenu.find('.item[data-tab="' + $tabMenu.data('diff') + '"]').click(function () {
  58. var $this = $(this);
  59. $.post($this.data('url'), {
  60. "_csrf": csrf,
  61. "context": $this.data('context'),
  62. "content": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  63. },
  64. function (data) {
  65. var $diffPreviewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('diff') + '"]');
  66. $diffPreviewPanel.html(data);
  67. emojify.run($diffPreviewPanel[0]);
  68. }
  69. );
  70. });
  71. }
  72. function initEditForm() {
  73. if ($('.edit.form').length == 0) {
  74. return;
  75. }
  76. initEditPreviewTab($('.edit.form'));
  77. initEditDiffTab($('.edit.form'));
  78. }
  79. function updateIssuesMeta(url, action, issueIds, elementId, afterSuccess) {
  80. $.ajax({
  81. type: "POST",
  82. url: url,
  83. data: {
  84. "_csrf": csrf,
  85. "action": action,
  86. "issue_ids": issueIds,
  87. "id": elementId
  88. },
  89. success: afterSuccess
  90. })
  91. }
  92. function initCommentForm() {
  93. if ($('.comment.form').length == 0) {
  94. return
  95. }
  96. initCommentPreviewTab($('.comment.form'));
  97. // Labels
  98. var $list = $('.ui.labels.list');
  99. var $noSelect = $list.find('.no-select');
  100. var $labelMenu = $('.select-label .menu');
  101. var hasLabelUpdateAction = $labelMenu.data('action') == 'update';
  102. $('.select-label').dropdown('setting', 'onHide', function(){
  103. if (hasLabelUpdateAction) {
  104. location.reload();
  105. }
  106. });
  107. $labelMenu.find('.item:not(.no-select)').click(function () {
  108. if ($(this).hasClass('checked')) {
  109. $(this).removeClass('checked');
  110. $(this).find('.octicon').removeClass('octicon-check');
  111. if (hasLabelUpdateAction) {
  112. updateIssuesMeta(
  113. $labelMenu.data('update-url'),
  114. "detach",
  115. $labelMenu.data('issue-id'),
  116. $(this).data('id')
  117. );
  118. }
  119. } else {
  120. $(this).addClass('checked');
  121. $(this).find('.octicon').addClass('octicon-check');
  122. if (hasLabelUpdateAction) {
  123. updateIssuesMeta(
  124. $labelMenu.data('update-url'),
  125. "attach",
  126. $labelMenu.data('issue-id'),
  127. $(this).data('id')
  128. );
  129. }
  130. }
  131. var labelIds = [];
  132. $(this).parent().find('.item').each(function () {
  133. if ($(this).hasClass('checked')) {
  134. labelIds.push($(this).data('id'));
  135. $($(this).data('id-selector')).removeClass('hide');
  136. } else {
  137. $($(this).data('id-selector')).addClass('hide');
  138. }
  139. });
  140. if (labelIds.length == 0) {
  141. $noSelect.removeClass('hide');
  142. } else {
  143. $noSelect.addClass('hide');
  144. }
  145. $($(this).parent().data('id')).val(labelIds.join(","));
  146. return false;
  147. });
  148. $labelMenu.find('.no-select.item').click(function () {
  149. if (hasLabelUpdateAction) {
  150. updateIssuesMeta(
  151. $labelMenu.data('update-url'),
  152. "clear",
  153. $labelMenu.data('issue-id'),
  154. ""
  155. );
  156. }
  157. $(this).parent().find('.item').each(function () {
  158. $(this).removeClass('checked');
  159. $(this).find('.octicon').removeClass('octicon-check');
  160. });
  161. $list.find('.item').each(function () {
  162. $(this).addClass('hide');
  163. });
  164. $noSelect.removeClass('hide');
  165. $($(this).parent().data('id')).val('');
  166. });
  167. function selectItem(select_id, input_id) {
  168. var $menu = $(select_id + ' .menu');
  169. var $list = $('.ui' + select_id + '.list');
  170. var hasUpdateAction = $menu.data('action') == 'update';
  171. $menu.find('.item:not(.no-select)').click(function () {
  172. $(this).parent().find('.item').each(function () {
  173. $(this).removeClass('selected active')
  174. });
  175. $(this).addClass('selected active');
  176. if (hasUpdateAction) {
  177. updateIssuesMeta(
  178. $menu.data('update-url'),
  179. "",
  180. $menu.data('issue-id'),
  181. $(this).data('id'),
  182. function() { location.reload(); }
  183. );
  184. }
  185. switch (input_id) {
  186. case '#milestone_id':
  187. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  188. $(this).text() + '</a>');
  189. break;
  190. case '#assignee_id':
  191. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  192. '<img class="ui avatar image" src=' + $(this).data('avatar') + '>' +
  193. $(this).text() + '</a>');
  194. }
  195. $('.ui' + select_id + '.list .no-select').addClass('hide');
  196. $(input_id).val($(this).data('id'));
  197. });
  198. $menu.find('.no-select.item').click(function () {
  199. $(this).parent().find('.item:not(.no-select)').each(function () {
  200. $(this).removeClass('selected active')
  201. });
  202. if (hasUpdateAction) {
  203. updateIssuesMeta(
  204. $menu.data('update-url'),
  205. "",
  206. $menu.data('issue-id'),
  207. $(this).data('id'),
  208. function() { location.reload(); }
  209. );
  210. }
  211. $list.find('.selected').html('');
  212. $list.find('.no-select').removeClass('hide');
  213. $(input_id).val('');
  214. });
  215. }
  216. // Milestone and assignee
  217. selectItem('.select-milestone', '#milestone_id');
  218. selectItem('.select-assignee', '#assignee_id');
  219. }
  220. function initInstall() {
  221. if ($('.install').length == 0) {
  222. return;
  223. }
  224. if ($('#db_host').val()=="") {
  225. $('#db_host').val("127.0.0.1:3306");
  226. $('#db_user').val("gitea");
  227. $('#db_name').val("gitea");
  228. }
  229. // Database type change detection.
  230. $("#db_type").change(function () {
  231. var sqliteDefault = 'data/gitea.db';
  232. var tidbDefault = 'data/gitea_tidb';
  233. var dbType = $(this).val();
  234. if (dbType === "SQLite3" || dbType === "TiDB") {
  235. $('#sql_settings').hide();
  236. $('#pgsql_settings').hide();
  237. $('#sqlite_settings').show();
  238. if (dbType === "SQLite3" && $('#db_path').val() == tidbDefault) {
  239. $('#db_path').val(sqliteDefault);
  240. } else if (dbType === "TiDB" && $('#db_path').val() == sqliteDefault) {
  241. $('#db_path').val(tidbDefault);
  242. }
  243. return;
  244. }
  245. var dbDefaults = {
  246. "MySQL": "127.0.0.1:3306",
  247. "PostgreSQL": "127.0.0.1:5432",
  248. "MSSQL": "127.0.0.1:1433"
  249. };
  250. $('#sqlite_settings').hide();
  251. $('#sql_settings').show();
  252. $('#pgsql_settings').toggle(dbType === "PostgreSQL");
  253. $.each(dbDefaults, function(type, defaultHost) {
  254. if ($('#db_host').val() == defaultHost) {
  255. $('#db_host').val(dbDefaults[dbType]);
  256. return false;
  257. }
  258. });
  259. });
  260. // TODO: better handling of exclusive relations.
  261. $('#offline-mode input').change(function () {
  262. if ($(this).is(':checked')) {
  263. $('#disable-gravatar').checkbox('check');
  264. $('#federated-avatar-lookup').checkbox('uncheck');
  265. }
  266. });
  267. $('#disable-gravatar input').change(function () {
  268. if ($(this).is(':checked')) {
  269. $('#federated-avatar-lookup').checkbox('uncheck');
  270. } else {
  271. $('#offline-mode').checkbox('uncheck');
  272. }
  273. });
  274. $('#federated-avatar-lookup input').change(function () {
  275. if ($(this).is(':checked')) {
  276. $('#disable-gravatar').checkbox('uncheck');
  277. $('#offline-mode').checkbox('uncheck');
  278. }
  279. });
  280. $('#disable-registration input').change(function () {
  281. if ($(this).is(':checked')) {
  282. $('#enable-captcha').checkbox('uncheck');
  283. }
  284. });
  285. $('#enable-captcha input').change(function () {
  286. if ($(this).is(':checked')) {
  287. $('#disable-registration').checkbox('uncheck');
  288. }
  289. });
  290. }
  291. function initRepository() {
  292. if ($('.repository').length == 0) {
  293. return;
  294. }
  295. function initFilterSearchDropdown(selector) {
  296. var $dropdown = $(selector);
  297. $dropdown.dropdown({
  298. fullTextSearch: true,
  299. onChange: function (text, value, $choice) {
  300. window.location.href = $choice.data('url');
  301. console.log($choice.data('url'))
  302. },
  303. message: {noResults: $dropdown.data('no-results')}
  304. });
  305. }
  306. // File list and commits
  307. if ($('.repository.file.list').length > 0 ||
  308. ('.repository.commits').length > 0) {
  309. initFilterSearchDropdown('.choose.reference .dropdown');
  310. $('.reference.column').click(function () {
  311. $('.choose.reference .scrolling.menu').css('display', 'none');
  312. $('.choose.reference .text').removeClass('black');
  313. $($(this).data('target')).css('display', 'block');
  314. $(this).find('.text').addClass('black');
  315. return false;
  316. });
  317. }
  318. // Wiki
  319. if ($('.repository.wiki.view').length > 0) {
  320. initFilterSearchDropdown('.choose.page .dropdown');
  321. }
  322. // Options
  323. if ($('.repository.settings.options').length > 0) {
  324. $('#repo_name').keyup(function () {
  325. var $prompt = $('#repo-name-change-prompt');
  326. if ($(this).val().toString().toLowerCase() != $(this).data('repo-name').toString().toLowerCase()) {
  327. $prompt.show();
  328. } else {
  329. $prompt.hide();
  330. }
  331. });
  332. // Enable or select internal/external wiki system and issue tracker.
  333. $('.enable-system').change(function () {
  334. if (this.checked) {
  335. $($(this).data('target')).removeClass('disabled');
  336. } else {
  337. $($(this).data('target')).addClass('disabled');
  338. }
  339. });
  340. $('.enable-system-radio').change(function () {
  341. if (this.value == 'false') {
  342. $($(this).data('target')).addClass('disabled');
  343. } else if (this.value == 'true') {
  344. $($(this).data('target')).removeClass('disabled');
  345. }
  346. });
  347. }
  348. // Labels
  349. if ($('.repository.labels').length > 0) {
  350. // Create label
  351. var $newLabelPanel = $('.new-label.segment');
  352. $('.new-label.button').click(function () {
  353. $newLabelPanel.show();
  354. });
  355. $('.new-label.segment .cancel').click(function () {
  356. $newLabelPanel.hide();
  357. });
  358. $('.color-picker').each(function () {
  359. $(this).minicolors();
  360. });
  361. $('.precolors .color').click(function () {
  362. var color_hex = $(this).data('color-hex');
  363. $('.color-picker').val(color_hex);
  364. $('.minicolors-swatch-color').css("background-color", color_hex);
  365. });
  366. $('.edit-label-button').click(function () {
  367. $('#label-modal-id').val($(this).data('id'));
  368. $('.edit-label .new-label-input').val($(this).data('title'));
  369. $('.edit-label .color-picker').val($(this).data('color'));
  370. $('.minicolors-swatch-color').css("background-color", $(this).data('color'));
  371. $('.edit-label.modal').modal({
  372. onApprove: function () {
  373. $('.edit-label.form').submit();
  374. }
  375. }).modal('show');
  376. return false;
  377. });
  378. }
  379. // Milestones
  380. if ($('.repository.milestones').length > 0) {
  381. }
  382. if ($('.repository.new.milestone').length > 0) {
  383. var $datepicker = $('.milestone.datepicker');
  384. $datepicker.datetimepicker({
  385. lang: $datepicker.data('lang'),
  386. inline: true,
  387. timepicker: false,
  388. startDate: $datepicker.data('start-date'),
  389. formatDate: 'Y-m-d',
  390. onSelectDate: function (ct) {
  391. $('#deadline').val(ct.dateFormat('Y-m-d'));
  392. }
  393. });
  394. $('#clear-date').click(function () {
  395. $('#deadline').val('');
  396. return false;
  397. });
  398. }
  399. // Issues
  400. if ($('.repository.view.issue').length > 0) {
  401. // Edit issue title
  402. var $issueTitle = $('#issue-title');
  403. var $editInput = $('#edit-title-input input');
  404. var editTitleToggle = function () {
  405. $issueTitle.toggle();
  406. $('.not-in-edit').toggle();
  407. $('#edit-title-input').toggle();
  408. $('.in-edit').toggle();
  409. $editInput.focus();
  410. return false;
  411. };
  412. $('#edit-title').click(editTitleToggle);
  413. $('#cancel-edit-title').click(editTitleToggle);
  414. $('#save-edit-title').click(editTitleToggle).click(function () {
  415. if ($editInput.val().length == 0 ||
  416. $editInput.val() == $issueTitle.text()) {
  417. $editInput.val($issueTitle.text());
  418. return false;
  419. }
  420. $.post($(this).data('update-url'), {
  421. "_csrf": csrf,
  422. "title": $editInput.val()
  423. },
  424. function (data) {
  425. $editInput.val(data.title);
  426. $issueTitle.text(data.title);
  427. location.reload();
  428. });
  429. return false;
  430. });
  431. // Edit issue or comment content
  432. $('.edit-content').click(function () {
  433. var $segment = $(this).parent().parent().parent().next();
  434. var $editContentZone = $segment.find('.edit-content-zone');
  435. var $renderContent = $segment.find('.render-content');
  436. var $rawContent = $segment.find('.raw-content');
  437. var $textarea;
  438. // Setup new form
  439. if ($editContentZone.html().length == 0) {
  440. $editContentZone.html($('#edit-content-form').html());
  441. $textarea = $segment.find('textarea');
  442. // Give new write/preview data-tab name to distinguish from others
  443. var $editContentForm = $editContentZone.find('.ui.comment.form');
  444. var $tabMenu = $editContentForm.find('.tabular.menu');
  445. $tabMenu.attr('data-write', $editContentZone.data('write'));
  446. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  447. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  448. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  449. $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write'));
  450. $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview'));
  451. initCommentPreviewTab($editContentForm);
  452. $editContentZone.find('.cancel.button').click(function () {
  453. $renderContent.show();
  454. $editContentZone.hide();
  455. });
  456. $editContentZone.find('.save.button').click(function () {
  457. $renderContent.show();
  458. $editContentZone.hide();
  459. $.post($editContentZone.data('update-url'), {
  460. "_csrf": csrf,
  461. "content": $textarea.val(),
  462. "context": $editContentZone.data('context')
  463. },
  464. function (data) {
  465. if (data.length == 0) {
  466. $renderContent.html($('#no-content').html());
  467. } else {
  468. $renderContent.html(data.content);
  469. emojify.run($renderContent[0]);
  470. $('pre code', $renderContent[0]).each(function (i, block) {
  471. hljs.highlightBlock(block);
  472. });
  473. }
  474. });
  475. });
  476. } else {
  477. $textarea = $segment.find('textarea');
  478. }
  479. // Show write/preview tab and copy raw content as needed
  480. $editContentZone.show();
  481. $renderContent.hide();
  482. if ($textarea.val().length == 0) {
  483. $textarea.val($rawContent.text());
  484. }
  485. $textarea.focus();
  486. return false;
  487. });
  488. // Delete comment
  489. $('.delete-comment').click(function () {
  490. var $this = $(this);
  491. if (confirm($this.data('locale'))) {
  492. $.post($this.data('url'), {
  493. "_csrf": csrf
  494. }).success(function () {
  495. $('#' + $this.data('comment-id')).remove();
  496. });
  497. }
  498. return false;
  499. });
  500. // Change status
  501. var $statusButton = $('#status-button');
  502. $('#comment-form .edit_area').keyup(function () {
  503. if ($(this).val().length == 0) {
  504. $statusButton.text($statusButton.data('status'))
  505. } else {
  506. $statusButton.text($statusButton.data('status-and-comment'))
  507. }
  508. });
  509. $statusButton.click(function () {
  510. $('#status').val($statusButton.data('status-val'));
  511. $('#comment-form').submit();
  512. });
  513. }
  514. // Diff
  515. if ($('.repository.diff').length > 0) {
  516. var $counter = $('.diff-counter');
  517. if ($counter.length >= 1) {
  518. $counter.each(function (i, item) {
  519. var $item = $(item);
  520. var addLine = $item.find('span[data-line].add').data("line");
  521. var delLine = $item.find('span[data-line].del').data("line");
  522. var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  523. $item.find(".bar .add").css("width", addPercent + "%");
  524. });
  525. }
  526. }
  527. // Quick start and repository home
  528. $('#repo-clone-ssh').click(function () {
  529. $('.clone-url').text($(this).data('link'));
  530. $('#repo-clone-url').val($(this).data('link'));
  531. $(this).addClass('blue');
  532. $('#repo-clone-https').removeClass('blue');
  533. localStorage.setItem('repo-clone-protocol', 'ssh');
  534. });
  535. $('#repo-clone-https').click(function () {
  536. $('.clone-url').text($(this).data('link'));
  537. $('#repo-clone-url').val($(this).data('link'));
  538. $(this).addClass('blue');
  539. $('#repo-clone-ssh').removeClass('blue');
  540. localStorage.setItem('repo-clone-protocol', 'https');
  541. });
  542. $('#repo-clone-url').click(function () {
  543. $(this).select();
  544. });
  545. // Pull request
  546. if ($('.repository.compare.pull').length > 0) {
  547. initFilterSearchDropdown('.choose.branch .dropdown');
  548. }
  549. }
  550. function initProtectedBranch() {
  551. $('#protectedBranch').change(function () {
  552. var $this = $(this);
  553. $.post($this.data('url'), {
  554. "_csrf": csrf,
  555. "canPush": true,
  556. "branchName": $this.val(),
  557. },
  558. function (data) {
  559. if (data.redirect) {
  560. window.location.href = data.redirect;
  561. } else {
  562. location.reload();
  563. }
  564. }
  565. );
  566. });
  567. $('.rm').click(function () {
  568. var $this = $(this);
  569. $.post($this.data('url'), {
  570. "_csrf": csrf,
  571. "canPush": false,
  572. "branchName": $this.data('val'),
  573. },
  574. function (data) {
  575. if (data.redirect) {
  576. window.location.href = data.redirect;
  577. } else {
  578. location.reload();
  579. }
  580. }
  581. );
  582. });
  583. }
  584. function initRepositoryCollaboration() {
  585. console.log('initRepositoryCollaboration');
  586. // Change collaborator access mode
  587. $('.access-mode.menu .item').click(function () {
  588. var $menu = $(this).parent();
  589. $.post($menu.data('url'), {
  590. "_csrf": csrf,
  591. "uid": $menu.data('uid'),
  592. "mode": $(this).data('value')
  593. })
  594. });
  595. }
  596. function initTeamSettings() {
  597. // Change team access mode
  598. $('.organization.new.team input[name=permission]').change(function () {
  599. var val = $('input[name=permission]:checked', '.organization.new.team').val()
  600. if (val === 'admin') {
  601. $('.organization.new.team .team-units').hide();
  602. } else {
  603. $('.organization.new.team .team-units').show();
  604. }
  605. });
  606. }
  607. function initWikiForm() {
  608. var $editArea = $('.repository.wiki textarea#edit_area');
  609. if ($editArea.length > 0) {
  610. new SimpleMDE({
  611. autoDownloadFontAwesome: false,
  612. element: $editArea[0],
  613. forceSync: true,
  614. previewRender: function (plainText, preview) { // Async method
  615. setTimeout(function () {
  616. // FIXME: still send render request when return back to edit mode
  617. $.post($editArea.data('url'), {
  618. "_csrf": csrf,
  619. "mode": "gfm",
  620. "context": $editArea.data('context'),
  621. "text": plainText
  622. },
  623. function (data) {
  624. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  625. emojify.run($('.editor-preview')[0]);
  626. $('.editor-preview').autolink();
  627. }
  628. );
  629. }, 0);
  630. return "Loading...";
  631. },
  632. renderingConfig: {
  633. singleLineBreaks: false
  634. },
  635. indentWithTabs: false,
  636. tabSize: 4,
  637. spellChecker: false,
  638. toolbar: ["bold", "italic", "strikethrough", "|",
  639. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  640. "code", "quote", "|",
  641. "unordered-list", "ordered-list", "|",
  642. "link", "image", "table", "horizontal-rule", "|",
  643. "clean-block", "preview", "fullscreen"]
  644. })
  645. }
  646. }
  647. var simpleMDEditor;
  648. var codeMirrorEditor;
  649. // For IE
  650. String.prototype.endsWith = function (pattern) {
  651. var d = this.length - pattern.length;
  652. return d >= 0 && this.lastIndexOf(pattern) === d;
  653. };
  654. // Adding function to get the cursor position in a text field to jQuery object.
  655. (function ($, undefined) {
  656. $.fn.getCursorPosition = function () {
  657. var el = $(this).get(0);
  658. var pos = 0;
  659. if ('selectionStart' in el) {
  660. pos = el.selectionStart;
  661. } else if ('selection' in document) {
  662. el.focus();
  663. var Sel = document.selection.createRange();
  664. var SelLength = document.selection.createRange().text.length;
  665. Sel.moveStart('character', -el.value.length);
  666. pos = Sel.text.length - SelLength;
  667. }
  668. return pos;
  669. }
  670. })(jQuery);
  671. function setSimpleMDE($editArea) {
  672. if (codeMirrorEditor) {
  673. codeMirrorEditor.toTextArea();
  674. codeMirrorEditor = null;
  675. }
  676. if (simpleMDEditor) {
  677. return true;
  678. }
  679. simpleMDEditor = new SimpleMDE({
  680. autoDownloadFontAwesome: false,
  681. element: $editArea[0],
  682. forceSync: true,
  683. renderingConfig: {
  684. singleLineBreaks: false
  685. },
  686. indentWithTabs: false,
  687. tabSize: 4,
  688. spellChecker: false,
  689. previewRender: function (plainText, preview) { // Async method
  690. setTimeout(function () {
  691. // FIXME: still send render request when return back to edit mode
  692. $.post($editArea.data('url'), {
  693. "_csrf": csrf,
  694. "mode": "gfm",
  695. "context": $editArea.data('context'),
  696. "text": plainText
  697. },
  698. function (data) {
  699. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  700. emojify.run($('.editor-preview')[0]);
  701. }
  702. );
  703. }, 0);
  704. return "Loading...";
  705. },
  706. toolbar: ["bold", "italic", "strikethrough", "|",
  707. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  708. "code", "quote", "|",
  709. "unordered-list", "ordered-list", "|",
  710. "link", "image", "table", "horizontal-rule", "|",
  711. "clean-block", "preview", "fullscreen", "side-by-side"]
  712. });
  713. return true;
  714. }
  715. function setCodeMirror($editArea) {
  716. if (simpleMDEditor) {
  717. simpleMDEditor.toTextArea();
  718. simpleMDEditor = null;
  719. }
  720. if (codeMirrorEditor) {
  721. return true;
  722. }
  723. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  724. lineNumbers: true
  725. });
  726. codeMirrorEditor.on("change", function (cm, change) {
  727. $editArea.val(cm.getValue());
  728. });
  729. return true;
  730. }
  731. function initEditor() {
  732. $('.js-quick-pull-choice-option').change(function () {
  733. if ($(this).val() == 'commit-to-new-branch') {
  734. $('.quick-pull-branch-name').show();
  735. $('.quick-pull-branch-name input').prop('required',true);
  736. } else {
  737. $('.quick-pull-branch-name').hide();
  738. $('.quick-pull-branch-name input').prop('required',false);
  739. }
  740. });
  741. var $editFilename = $("#file-name");
  742. $editFilename.keyup(function (e) {
  743. var $section = $('.breadcrumb span.section');
  744. var $divider = $('.breadcrumb div.divider');
  745. if (e.keyCode == 8) {
  746. if ($(this).getCursorPosition() == 0) {
  747. if ($section.length > 0) {
  748. var value = $section.last().find('a').text();
  749. $(this).val(value + $(this).val());
  750. $(this)[0].setSelectionRange(value.length, value.length);
  751. $section.last().remove();
  752. $divider.last().remove();
  753. }
  754. }
  755. }
  756. if (e.keyCode == 191) {
  757. var parts = $(this).val().split('/');
  758. for (var i = 0; i < parts.length; ++i) {
  759. var value = parts[i];
  760. if (i < parts.length - 1) {
  761. if (value.length) {
  762. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  763. $('<div class="divider"> / </div>').insertBefore($(this));
  764. }
  765. }
  766. else {
  767. $(this).val(value);
  768. }
  769. $(this)[0].setSelectionRange(0, 0);
  770. }
  771. }
  772. var parts = [];
  773. $('.breadcrumb span.section').each(function (i, element) {
  774. element = $(element);
  775. if (element.find('a').length) {
  776. parts.push(element.find('a').text());
  777. } else {
  778. parts.push(element.text());
  779. }
  780. });
  781. if ($(this).val())
  782. parts.push($(this).val());
  783. $('#tree_path').val(parts.join('/'));
  784. }).trigger('keyup');
  785. var $editArea = $('.repository.editor textarea#edit_area');
  786. if (!$editArea.length)
  787. return;
  788. var markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  789. var lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  790. $editFilename.on("keyup", function (e) {
  791. var val = $editFilename.val(), m, mode, spec, extension, extWithDot, previewLink, dataUrl, apiCall;
  792. extension = extWithDot = "";
  793. if (m = /.+\.([^.]+)$/.exec(val)) {
  794. extension = m[1];
  795. extWithDot = "." + extension;
  796. }
  797. var info = CodeMirror.findModeByExtension(extension);
  798. previewLink = $('a[data-tab=preview]');
  799. if (info) {
  800. mode = info.mode;
  801. spec = info.mime;
  802. apiCall = mode;
  803. }
  804. else {
  805. apiCall = extension
  806. }
  807. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  808. dataUrl = previewLink.data('url');
  809. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  810. previewLink.show();
  811. }
  812. else {
  813. previewLink.hide();
  814. }
  815. // If this file is a Markdown extensions, we will load that editor and return
  816. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  817. if (setSimpleMDE($editArea)) {
  818. return;
  819. }
  820. }
  821. // Else we are going to use CodeMirror
  822. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  823. return;
  824. }
  825. if (mode) {
  826. codeMirrorEditor.setOption("mode", spec);
  827. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  828. }
  829. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  830. codeMirrorEditor.setOption("lineWrapping", true);
  831. }
  832. else {
  833. codeMirrorEditor.setOption("lineWrapping", false);
  834. }
  835. // get the filename without any folder
  836. var value = $editFilename.val();
  837. if (value.length === 0) {
  838. return;
  839. }
  840. value = value.split('/');
  841. value = value[value.length - 1];
  842. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  843. if (editorconfig.indent_style === 'tab') {
  844. codeMirrorEditor.setOption("indentWithTabs", true);
  845. codeMirrorEditor.setOption('extraKeys', {});
  846. } else {
  847. codeMirrorEditor.setOption("indentWithTabs", false);
  848. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  849. // - https://github.com/codemirror/CodeMirror/issues/988
  850. // - https://codemirror.net/doc/manual.html#keymaps
  851. codeMirrorEditor.setOption('extraKeys', {
  852. Tab: function(cm) {
  853. var spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  854. cm.replaceSelection(spaces);
  855. }
  856. });
  857. }
  858. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  859. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  860. });
  861. }).trigger('keyup');
  862. }
  863. function initOrganization() {
  864. if ($('.organization').length == 0) {
  865. return;
  866. }
  867. // Options
  868. if ($('.organization.settings.options').length > 0) {
  869. $('#org_name').keyup(function () {
  870. var $prompt = $('#org-name-change-prompt');
  871. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  872. $prompt.show();
  873. } else {
  874. $prompt.hide();
  875. }
  876. });
  877. }
  878. }
  879. function initUserSettings() {
  880. console.log('initUserSettings');
  881. // Options
  882. if ($('.user.settings.profile').length > 0) {
  883. $('#username').keyup(function () {
  884. var $prompt = $('#name-change-prompt');
  885. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  886. $prompt.show();
  887. } else {
  888. $prompt.hide();
  889. }
  890. });
  891. }
  892. }
  893. function initWebhook() {
  894. if ($('.new.webhook').length == 0) {
  895. return;
  896. }
  897. $('.events.checkbox input').change(function () {
  898. if ($(this).is(':checked')) {
  899. $('.events.fields').show();
  900. }
  901. });
  902. $('.non-events.checkbox input').change(function () {
  903. if ($(this).is(':checked')) {
  904. $('.events.fields').hide();
  905. }
  906. });
  907. // Test delivery
  908. $('#test-delivery').click(function () {
  909. var $this = $(this);
  910. $this.addClass('loading disabled');
  911. $.post($this.data('link'), {
  912. "_csrf": csrf
  913. }).done(
  914. setTimeout(function () {
  915. window.location.href = $this.data('redirect');
  916. }, 5000)
  917. )
  918. });
  919. }
  920. function initAdmin() {
  921. if ($('.admin').length == 0) {
  922. return;
  923. }
  924. // New user
  925. if ($('.admin.new.user').length > 0 ||
  926. $('.admin.edit.user').length > 0) {
  927. $('#login_type').change(function () {
  928. if ($(this).val().substring(0, 1) == '0') {
  929. $('#login_name').removeAttr('required');
  930. $('.non-local').hide();
  931. $('.local').show();
  932. $('#user_name').focus();
  933. if ($(this).data('password') == "required") {
  934. $('#password').attr('required', 'required');
  935. }
  936. } else {
  937. $('#login_name').attr('required', 'required');
  938. $('.non-local').show();
  939. $('.local').hide();
  940. $('#login_name').focus();
  941. $('#password').removeAttr('required');
  942. }
  943. });
  944. }
  945. function onSecurityProtocolChange() {
  946. if ($('#security_protocol').val() > 0) {
  947. $('.has-tls').show();
  948. } else {
  949. $('.has-tls').hide();
  950. }
  951. }
  952. function onOAuth2Change() {
  953. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  954. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  955. var provider = $('#oauth2_provider').val();
  956. switch (provider) {
  957. case 'github':
  958. case 'gitlab':
  959. $('.oauth2_use_custom_url').show();
  960. break;
  961. case 'openidConnect':
  962. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  963. $('.open_id_connect_auto_discovery_url').show();
  964. break;
  965. }
  966. onOAuth2UseCustomURLChange();
  967. }
  968. function onOAuth2UseCustomURLChange() {
  969. var provider = $('#oauth2_provider').val();
  970. $('.oauth2_use_custom_url_field').hide();
  971. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  972. if ($('#oauth2_use_custom_url').is(':checked')) {
  973. if (!$('#oauth2_token_url').val()) {
  974. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  975. }
  976. if (!$('#oauth2_auth_url').val()) {
  977. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  978. }
  979. if (!$('#oauth2_profile_url').val()) {
  980. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  981. }
  982. if (!$('#oauth2_email_url').val()) {
  983. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  984. }
  985. switch (provider) {
  986. case 'github':
  987. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  988. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  989. break;
  990. case 'gitlab':
  991. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  992. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  993. $('#oauth2_email_url').val('');
  994. break;
  995. }
  996. }
  997. }
  998. // New authentication
  999. if ($('.admin.new.authentication').length > 0) {
  1000. $('#auth_type').change(function () {
  1001. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls').hide();
  1002. $('.ldap input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required] .has-tls input[required]').removeAttr('required');
  1003. var authType = $(this).val();
  1004. switch (authType) {
  1005. case '2': // LDAP
  1006. $('.ldap').show();
  1007. $('.ldap div.required:not(.dldap) input').attr('required', 'required');
  1008. break;
  1009. case '3': // SMTP
  1010. $('.smtp').show();
  1011. $('.has-tls').show();
  1012. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1013. break;
  1014. case '4': // PAM
  1015. $('.pam').show();
  1016. $('.pam input').attr('required', 'required');
  1017. break;
  1018. case '5': // LDAP
  1019. $('.dldap').show();
  1020. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1021. break;
  1022. case '6': // OAuth2
  1023. $('.oauth2').show();
  1024. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1025. onOAuth2Change();
  1026. break;
  1027. }
  1028. if (authType == '2' || authType == '5') {
  1029. onSecurityProtocolChange()
  1030. }
  1031. });
  1032. $('#auth_type').change();
  1033. $('#security_protocol').change(onSecurityProtocolChange);
  1034. $('#oauth2_provider').change(onOAuth2Change);
  1035. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1036. }
  1037. // Edit authentication
  1038. if ($('.admin.edit.authentication').length > 0) {
  1039. var authType = $('#auth_type').val();
  1040. if (authType == '2' || authType == '5') {
  1041. $('#security_protocol').change(onSecurityProtocolChange);
  1042. } else if (authType == '6') {
  1043. $('#oauth2_provider').change(onOAuth2Change);
  1044. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1045. onOAuth2Change();
  1046. }
  1047. }
  1048. // Notice
  1049. if ($('.admin.notice')) {
  1050. var $detailModal = $('#detail-modal');
  1051. // Attach view detail modals
  1052. $('.view-detail').click(function () {
  1053. $detailModal.find('.content p').text($(this).data('content'));
  1054. $detailModal.modal('show');
  1055. return false;
  1056. });
  1057. // Select actions
  1058. var $checkboxes = $('.select.table .ui.checkbox');
  1059. $('.select.action').click(function () {
  1060. switch ($(this).data('action')) {
  1061. case 'select-all':
  1062. $checkboxes.checkbox('check');
  1063. break;
  1064. case 'deselect-all':
  1065. $checkboxes.checkbox('uncheck');
  1066. break;
  1067. case 'inverse':
  1068. $checkboxes.checkbox('toggle');
  1069. break;
  1070. }
  1071. });
  1072. $('#delete-selection').click(function () {
  1073. var $this = $(this);
  1074. $this.addClass("loading disabled");
  1075. var ids = [];
  1076. $checkboxes.each(function () {
  1077. if ($(this).checkbox('is checked')) {
  1078. ids.push($(this).data('id'));
  1079. }
  1080. });
  1081. $.post($this.data('link'), {
  1082. "_csrf": csrf,
  1083. "ids": ids
  1084. }).done(function () {
  1085. window.location.href = $this.data('redirect');
  1086. });
  1087. });
  1088. }
  1089. }
  1090. function buttonsClickOnEnter() {
  1091. $('.ui.button').keypress(function (e) {
  1092. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1093. $(this).click();
  1094. });
  1095. }
  1096. function hideWhenLostFocus(body, parent) {
  1097. $(document).click(function (e) {
  1098. var target = e.target;
  1099. if (!$(target).is(body) && !$(target).parents().is(parent)) {
  1100. $(body).hide();
  1101. }
  1102. });
  1103. }
  1104. function searchUsers() {
  1105. if (!$('#search-user-box .results').length) {
  1106. return;
  1107. }
  1108. var $searchUserBox = $('#search-user-box');
  1109. var $results = $searchUserBox.find('.results');
  1110. $searchUserBox.keyup(function () {
  1111. var $this = $(this);
  1112. var keyword = $this.find('input').val();
  1113. if (keyword.length < 2) {
  1114. $results.hide();
  1115. return;
  1116. }
  1117. $.ajax({
  1118. url: suburl + '/api/v1/users/search?q=' + keyword,
  1119. dataType: "json",
  1120. success: function (response) {
  1121. var notEmpty = function (str) {
  1122. return str && str.length > 0;
  1123. };
  1124. $results.html('');
  1125. if (response.ok && response.data.length) {
  1126. var html = '';
  1127. $.each(response.data, function (i, item) {
  1128. html += '<div class="item"><img class="ui avatar image" src="' + item.avatar_url + '"><span class="username">' + item.login + '</span>';
  1129. if (notEmpty(item.full_name)) {
  1130. html += ' (' + item.full_name + ')';
  1131. }
  1132. html += '</div>';
  1133. });
  1134. $results.html(html);
  1135. $this.find('.results .item').click(function () {
  1136. $this.find('input').val($(this).find('.username').text());
  1137. $results.hide();
  1138. });
  1139. $results.show();
  1140. } else {
  1141. $results.hide();
  1142. }
  1143. }
  1144. });
  1145. });
  1146. $searchUserBox.find('input').focus(function () {
  1147. $searchUserBox.keyup();
  1148. });
  1149. hideWhenLostFocus('#search-user-box .results', '#search-user-box');
  1150. }
  1151. // FIXME: merge common parts in two functions
  1152. function searchRepositories() {
  1153. if (!$('#search-repo-box .results').length) {
  1154. return;
  1155. }
  1156. var $searchRepoBox = $('#search-repo-box');
  1157. var $results = $searchRepoBox.find('.results');
  1158. $searchRepoBox.keyup(function () {
  1159. var $this = $(this);
  1160. var keyword = $this.find('input').val();
  1161. if (keyword.length < 2) {
  1162. $results.hide();
  1163. return;
  1164. }
  1165. $.ajax({
  1166. url: suburl + '/api/v1/repos/search?q=' + keyword + "&uid=" + $searchRepoBox.data('uid'),
  1167. dataType: "json",
  1168. success: function (response) {
  1169. var notEmpty = function (str) {
  1170. return str && str.length > 0;
  1171. };
  1172. $results.html('');
  1173. if (response.ok && response.data.length) {
  1174. var html = '';
  1175. $.each(response.data, function (i, item) {
  1176. html += '<div class="item"><i class="icon octicon octicon-repo"></i> <span class="fullname">' + item.full_name + '</span></div>';
  1177. });
  1178. $results.html(html);
  1179. $this.find('.results .item').click(function () {
  1180. $this.find('input').val($(this).find('.fullname').text().split("/")[1]);
  1181. $results.hide();
  1182. });
  1183. $results.show();
  1184. } else {
  1185. $results.hide();
  1186. }
  1187. }
  1188. });
  1189. });
  1190. $searchRepoBox.find('input').focus(function () {
  1191. $searchRepoBox.keyup();
  1192. });
  1193. hideWhenLostFocus('#search-repo-box .results', '#search-repo-box');
  1194. }
  1195. function initCodeView() {
  1196. if ($('.code-view .linenums').length > 0) {
  1197. $(document).on('click', '.lines-num span', function (e) {
  1198. var $select = $(this);
  1199. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1200. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1201. deSelect();
  1202. });
  1203. $(window).on('hashchange', function (e) {
  1204. var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
  1205. var $list = $('.code-view ol.linenums > li');
  1206. var $first;
  1207. if (m) {
  1208. $first = $list.filter('.' + m[1]);
  1209. selectRange($list, $first, $list.filter('.' + m[2]));
  1210. $("html, body").scrollTop($first.offset().top - 200);
  1211. return;
  1212. }
  1213. m = window.location.hash.match(/^#(L\d+)$/);
  1214. if (m) {
  1215. $first = $list.filter('.' + m[1]);
  1216. selectRange($list, $first);
  1217. $("html, body").scrollTop($first.offset().top - 200);
  1218. }
  1219. }).trigger('hashchange');
  1220. }
  1221. }
  1222. $(document).ready(function () {
  1223. csrf = $('meta[name=_csrf]').attr("content");
  1224. suburl = $('meta[name=_suburl]').attr("content");
  1225. // Show exact time
  1226. $('.time-since').each(function () {
  1227. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1228. });
  1229. // Semantic UI modules.
  1230. $('.dropdown').dropdown();
  1231. $('.jump.dropdown').dropdown({
  1232. action: 'hide',
  1233. onShow: function () {
  1234. $('.poping.up').popup('hide');
  1235. }
  1236. });
  1237. $('.slide.up.dropdown').dropdown({
  1238. transition: 'slide up'
  1239. });
  1240. $('.upward.dropdown').dropdown({
  1241. direction: 'upward'
  1242. });
  1243. $('.ui.accordion').accordion();
  1244. $('.ui.checkbox').checkbox();
  1245. $('.ui.progress').progress({
  1246. showActivity: false
  1247. });
  1248. $('.poping.up').popup();
  1249. $('.top.menu .poping.up').popup({
  1250. onShow: function () {
  1251. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1252. return false;
  1253. }
  1254. }
  1255. });
  1256. $('.tabular.menu .item').tab();
  1257. $('.tabable.menu .item').tab();
  1258. $('.toggle.button').click(function () {
  1259. $($(this).data('target')).slideToggle(100);
  1260. });
  1261. // make table <tr> element clickable like a link
  1262. $('tr[data-href]').click(function(event) {
  1263. window.location = $(this).data('href');
  1264. });
  1265. // Highlight JS
  1266. if (typeof hljs != 'undefined') {
  1267. hljs.initHighlightingOnLoad();
  1268. }
  1269. // Dropzone
  1270. var $dropzone = $('#dropzone');
  1271. if ($dropzone.length > 0) {
  1272. // Disable auto discover for all elements:
  1273. Dropzone.autoDiscover = false;
  1274. var filenameDict = {};
  1275. $dropzone.dropzone({
  1276. url: $dropzone.data('upload-url'),
  1277. headers: {"X-Csrf-Token": csrf},
  1278. maxFiles: $dropzone.data('max-file'),
  1279. maxFilesize: $dropzone.data('max-size'),
  1280. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1281. addRemoveLinks: true,
  1282. dictDefaultMessage: $dropzone.data('default-message'),
  1283. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1284. dictFileTooBig: $dropzone.data('file-too-big'),
  1285. dictRemoveFile: $dropzone.data('remove-file'),
  1286. init: function () {
  1287. this.on("success", function (file, data) {
  1288. filenameDict[file.name] = data.uuid;
  1289. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  1290. $('.files').append(input);
  1291. });
  1292. this.on("removedfile", function (file) {
  1293. if (file.name in filenameDict) {
  1294. $('#' + filenameDict[file.name]).remove();
  1295. }
  1296. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1297. $.post($dropzone.data('remove-url'), {
  1298. file: filenameDict[file.name],
  1299. _csrf: $dropzone.data('csrf')
  1300. });
  1301. }
  1302. })
  1303. }
  1304. });
  1305. }
  1306. // Emojify
  1307. emojify.setConfig({
  1308. img_dir: suburl + '/img/emoji',
  1309. ignore_emoticons: true
  1310. });
  1311. var hasEmoji = document.getElementsByClassName('has-emoji');
  1312. for (var i = 0; i < hasEmoji.length; i++) {
  1313. emojify.run(hasEmoji[i]);
  1314. }
  1315. // Clipboard JS
  1316. var clipboard = new Clipboard('.clipboard');
  1317. clipboard.on('success', function (e) {
  1318. e.clearSelection();
  1319. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1320. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  1321. $('#' + e.trigger.getAttribute('id')).popup('show');
  1322. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1323. });
  1324. clipboard.on('error', function (e) {
  1325. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1326. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  1327. $('#' + e.trigger.getAttribute('id')).popup('show');
  1328. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1329. });
  1330. // Helpers.
  1331. $('.delete-button').click(function () {
  1332. var $this = $(this);
  1333. var filter = "";
  1334. if ($this.attr("id")) {
  1335. filter += "#"+$this.attr("id")
  1336. }
  1337. $('.delete.modal'+filter).modal({
  1338. closable: false,
  1339. onApprove: function () {
  1340. if ($this.data('type') == "form") {
  1341. $($this.data('form')).submit();
  1342. return;
  1343. }
  1344. $.post($this.data('url'), {
  1345. "_csrf": csrf,
  1346. "id": $this.data("id")
  1347. }).done(function (data) {
  1348. window.location.href = data.redirect;
  1349. });
  1350. }
  1351. }).modal('show');
  1352. return false;
  1353. });
  1354. $('.show-panel.button').click(function () {
  1355. $($(this).data('panel')).show();
  1356. });
  1357. $('.show-modal.button').click(function () {
  1358. $($(this).data('modal')).modal('show');
  1359. });
  1360. $('.delete-post.button').click(function () {
  1361. var $this = $(this);
  1362. $.post($this.data('request-url'), {
  1363. "_csrf": csrf
  1364. }).done(function () {
  1365. window.location.href = $this.data('done-url');
  1366. });
  1367. });
  1368. // Set anchor.
  1369. $('.markdown').each(function () {
  1370. var headers = {};
  1371. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  1372. var node = $(this);
  1373. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  1374. var name = val;
  1375. if (headers[val] > 0) {
  1376. name = val + '-' + headers[val];
  1377. }
  1378. if (headers[val] == undefined) {
  1379. headers[val] = 1;
  1380. } else {
  1381. headers[val] += 1;
  1382. }
  1383. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  1384. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  1385. });
  1386. });
  1387. $('.markdown').autolink();
  1388. $('.issue-checkbox').click(function() {
  1389. var numChecked = $('.issue-checkbox').children('input:checked').length;
  1390. if (numChecked > 0) {
  1391. $('.issue-filters').hide();
  1392. $('.issue-actions').show();
  1393. } else {
  1394. $('.issue-filters').show();
  1395. $('.issue-actions').hide();
  1396. }
  1397. });
  1398. $('.issue-action').click(function () {
  1399. var action = this.dataset.action
  1400. var elementId = this.dataset.elementId
  1401. var issueIDs = $('.issue-checkbox').children('input:checked').map(function() {
  1402. return this.dataset.issueId;
  1403. }).get().join();
  1404. var url = this.dataset.url
  1405. updateIssuesMeta(url, action, issueIDs, elementId, function() {
  1406. location.reload();
  1407. });
  1408. });
  1409. buttonsClickOnEnter();
  1410. searchUsers();
  1411. searchRepositories();
  1412. initCommentForm();
  1413. initInstall();
  1414. initRepository();
  1415. initWikiForm();
  1416. initEditForm();
  1417. initEditor();
  1418. initOrganization();
  1419. initProtectedBranch();
  1420. initWebhook();
  1421. initAdmin();
  1422. initCodeView();
  1423. initDashboardSearch();
  1424. initTeamSettings();
  1425. // Repo clone url.
  1426. if ($('#repo-clone-url').length > 0) {
  1427. switch (localStorage.getItem('repo-clone-protocol')) {
  1428. case 'ssh':
  1429. if ($('#repo-clone-ssh').click().length === 0) {
  1430. $('#repo-clone-https').click();
  1431. }
  1432. break;
  1433. default:
  1434. $('#repo-clone-https').click();
  1435. break;
  1436. }
  1437. }
  1438. var routes = {
  1439. 'div.user.settings': initUserSettings,
  1440. 'div.repository.settings.collaboration': initRepositoryCollaboration
  1441. };
  1442. var selector;
  1443. for (selector in routes) {
  1444. if ($(selector).length > 0) {
  1445. routes[selector]();
  1446. break;
  1447. }
  1448. }
  1449. });
  1450. function changeHash(hash) {
  1451. if (history.pushState) {
  1452. history.pushState(null, null, hash);
  1453. }
  1454. else {
  1455. location.hash = hash;
  1456. }
  1457. }
  1458. function deSelect() {
  1459. if (window.getSelection) {
  1460. window.getSelection().removeAllRanges();
  1461. } else {
  1462. document.selection.empty();
  1463. }
  1464. }
  1465. function selectRange($list, $select, $from) {
  1466. $list.removeClass('active');
  1467. if ($from) {
  1468. var a = parseInt($select.attr('rel').substr(1));
  1469. var b = parseInt($from.attr('rel').substr(1));
  1470. var c;
  1471. if (a != b) {
  1472. if (a > b) {
  1473. c = a;
  1474. a = b;
  1475. b = c;
  1476. }
  1477. var classes = [];
  1478. for (var i = a; i <= b; i++) {
  1479. classes.push('.L' + i);
  1480. }
  1481. $list.filter(classes.join(',')).addClass('active');
  1482. changeHash('#L' + a + '-' + 'L' + b);
  1483. return
  1484. }
  1485. }
  1486. $select.addClass('active');
  1487. changeHash('#' + $select.attr('rel'));
  1488. }
  1489. $(function () {
  1490. if ($('.user.signin').length > 0) return;
  1491. $('form').areYouSure();
  1492. // Parse SSH Key
  1493. $("#ssh-key-content").on('change paste keyup',function(){
  1494. var arrays = $(this).val().split(" ");
  1495. var $title = $("#ssh-key-title")
  1496. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  1497. $title.val(arrays[2]);
  1498. }
  1499. });
  1500. });
  1501. function initDashboardSearch() {
  1502. var el = document.getElementById('dashboard-repo-search');
  1503. if (!el) {
  1504. return;
  1505. }
  1506. new Vue({
  1507. delimiters: ['${', '}'],
  1508. el: el,
  1509. data: {
  1510. tab: 'repos',
  1511. repos: [],
  1512. searchQuery: '',
  1513. suburl: document.querySelector('meta[name=_suburl]').content,
  1514. uid: document.querySelector('meta[name=_context_uid]').content
  1515. },
  1516. mounted: function() {
  1517. this.searchRepos();
  1518. Vue.nextTick(function() {
  1519. document.querySelector('#search_repo').focus();
  1520. });
  1521. },
  1522. methods: {
  1523. changeTab: function(t) {
  1524. this.tab = t;
  1525. },
  1526. searchKeyUp: function() {
  1527. this.searchRepos();
  1528. },
  1529. searchRepos: function() {
  1530. var self = this;
  1531. $.getJSON(this.searchURL(), function(result) {
  1532. self.repos = result.data;
  1533. });
  1534. },
  1535. searchURL: function() {
  1536. return this.suburl + '/api/v1/repos/search?uid=' + this.uid + '&q=' + this.searchQuery;
  1537. },
  1538. repoClass: function(repo) {
  1539. if (repo.fork) {
  1540. return 'octicon octicon-repo-forked';
  1541. } else if (repo.mirror) {
  1542. return 'octicon octicon-repo-clone';
  1543. } else if (repo.private) {
  1544. return 'octicon octicon-lock';
  1545. } else {
  1546. return 'octicon octicon-repo';
  1547. }
  1548. }
  1549. }
  1550. });
  1551. }