gogs.js 57 KB

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