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.

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