gogs.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533
  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. function initWikiForm() {
  469. var $editArea = $('.repository.wiki textarea#edit_area');
  470. if ($editArea.length > 0) {
  471. new SimpleMDE({
  472. autoDownloadFontAwesome: false,
  473. element: $editArea[0],
  474. forceSync: true,
  475. previewRender: function (plainText, preview) { // Async method
  476. setTimeout(function () {
  477. // FIXME: still send render request when return back to edit mode
  478. $.post($editArea.data('url'), {
  479. "_csrf": csrf,
  480. "mode": "gfm",
  481. "context": $editArea.data('context'),
  482. "text": plainText
  483. },
  484. function (data) {
  485. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  486. emojify.run($('.editor-preview')[0]);
  487. }
  488. );
  489. }, 0);
  490. return "Loading...";
  491. },
  492. renderingConfig: {
  493. singleLineBreaks: false
  494. },
  495. indentWithTabs: false,
  496. tabSize: 4,
  497. spellChecker: false,
  498. toolbar: ["bold", "italic", "strikethrough", "|",
  499. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  500. "code", "quote", "|",
  501. "unordered-list", "ordered-list", "|",
  502. "link", "image", "table", "horizontal-rule", "|",
  503. "clean-block", "preview", "fullscreen"]
  504. })
  505. }
  506. }
  507. var simpleMDEditor;
  508. var codeMirrorEditor;
  509. // For IE
  510. String.prototype.endsWith = function (pattern) {
  511. var d = this.length - pattern.length;
  512. return d >= 0 && this.lastIndexOf(pattern) === d;
  513. };
  514. // Adding function to get the cursor position in a text field to jQuery object.
  515. (function ($, undefined) {
  516. $.fn.getCursorPosition = function () {
  517. var el = $(this).get(0);
  518. var pos = 0;
  519. if ('selectionStart' in el) {
  520. pos = el.selectionStart;
  521. } else if ('selection' in document) {
  522. el.focus();
  523. var Sel = document.selection.createRange();
  524. var SelLength = document.selection.createRange().text.length;
  525. Sel.moveStart('character', -el.value.length);
  526. pos = Sel.text.length - SelLength;
  527. }
  528. return pos;
  529. }
  530. })(jQuery);
  531. function setSimpleMDE($editArea) {
  532. if (codeMirrorEditor) {
  533. codeMirrorEditor.toTextArea();
  534. codeMirrorEditor = null;
  535. }
  536. if (simpleMDEditor) {
  537. return true;
  538. }
  539. simpleMDEditor = new SimpleMDE({
  540. autoDownloadFontAwesome: false,
  541. element: $editArea[0],
  542. forceSync: true,
  543. renderingConfig: {
  544. singleLineBreaks: false
  545. },
  546. indentWithTabs: false,
  547. tabSize: 4,
  548. spellChecker: false,
  549. previewRender: function (plainText, preview) { // Async method
  550. setTimeout(function () {
  551. // FIXME: still send render request when return back to edit mode
  552. $.post($editArea.data('url'), {
  553. "_csrf": csrf,
  554. "mode": "gfm",
  555. "context": $editArea.data('context'),
  556. "text": plainText
  557. },
  558. function (data) {
  559. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  560. emojify.run($('.editor-preview')[0]);
  561. }
  562. );
  563. }, 0);
  564. return "Loading...";
  565. },
  566. toolbar: ["bold", "italic", "strikethrough", "|",
  567. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  568. "code", "quote", "|",
  569. "unordered-list", "ordered-list", "|",
  570. "link", "image", "table", "horizontal-rule", "|",
  571. "clean-block"]
  572. });
  573. return true;
  574. }
  575. function setCodeMirror($editArea) {
  576. if (simpleMDEditor) {
  577. simpleMDEditor.toTextArea();
  578. simpleMDEditor = null;
  579. }
  580. if (codeMirrorEditor) {
  581. return true;
  582. }
  583. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  584. lineNumbers: true
  585. });
  586. codeMirrorEditor.on("change", function (cm, change) {
  587. $editArea.val(cm.getValue());
  588. });
  589. codeMirrorEditor.on("keyup", function (cm, change) {
  590. if (typeof (jsonEditor)!== 'undefined') {
  591. try {
  592. jsonEditor.set(JSON.parse(cm.getValue()));
  593. document.getElementById("parseerr").innerHTML = "Valid JSON";
  594. document.getElementById("parseerr").className="ui positive message"
  595. }
  596. catch(err) {
  597. document.getElementById("parseerr").innerHTML = err.message;
  598. document.getElementById("parseerr").className="ui negative message"
  599. }
  600. }
  601. if (typeof (yamleditor)!== 'undefined') {
  602. try {
  603. yamleditor.set(YAML.parse(cm.getValue()));
  604. document.getElementById("parseerr").innerHTML = "Valid YAML";
  605. document.getElementById("parseerr").className="ui positive message"
  606. }
  607. catch(err) {
  608. document.getElementById("parseerr").innerHTML = err.message;
  609. document.getElementById("parseerr").className="ui negative message"
  610. }
  611. }
  612. });
  613. return true;
  614. }
  615. function initEditor() {
  616. $('.js-quick-pull-choice-option').change(function () {
  617. if ($(this).val() == 'commit-to-new-branch') {
  618. $('.quick-pull-branch-name').show();
  619. $('.quick-pull-branch-name input').prop('required',true);
  620. } else {
  621. $('.quick-pull-branch-name').hide();
  622. $('.quick-pull-branch-name input').prop('required',false);
  623. }
  624. });
  625. var $editFilename = $("#file-name");
  626. $editFilename.keyup(function (e) {
  627. var $section = $('.breadcrumb span.section');
  628. var $divider = $('.breadcrumb div.divider');
  629. if (e.keyCode == 8) {
  630. if ($(this).getCursorPosition() == 0) {
  631. if ($section.length > 0) {
  632. var value = $section.last().find('a').text();
  633. $(this).val(value + $(this).val());
  634. $(this)[0].setSelectionRange(value.length, value.length);
  635. $section.last().remove();
  636. $divider.last().remove();
  637. }
  638. }
  639. }
  640. if (e.keyCode == 191) {
  641. var parts = $(this).val().split('/');
  642. for (var i = 0; i < parts.length; ++i) {
  643. var value = parts[i];
  644. if (i < parts.length - 1) {
  645. if (value.length) {
  646. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  647. $('<div class="divider"> / </div>').insertBefore($(this));
  648. }
  649. }
  650. else {
  651. $(this).val(value);
  652. }
  653. $(this)[0].setSelectionRange(0, 0);
  654. }
  655. }
  656. var parts = [];
  657. $('.breadcrumb span.section').each(function (i, element) {
  658. element = $(element);
  659. if (element.find('a').length) {
  660. parts.push(element.find('a').text());
  661. } else {
  662. parts.push(element.text());
  663. }
  664. });
  665. if ($(this).val()) {
  666. parts.push($(this).val());
  667. }
  668. var tree_path = parts.join('/');
  669. $('#tree_path').val(tree_path);
  670. $('#preview-tab').data('context', $('#preview-tab').data('root-context') + tree_path.substring(0, tree_path.lastIndexOf("/")+1));
  671. }).trigger('keyup');
  672. var $editArea = $('.repository.editor textarea#edit_area');
  673. if (!$editArea.length)
  674. return;
  675. var markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  676. var lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  677. $editFilename.on("keyup", function (e) {
  678. var val = $editFilename.val(), m, mode, spec, extension, extWithDot, previewLink, dataUrl, apiCall;
  679. extension = extWithDot = "";
  680. if (m = /.+\.([^.]+)$/.exec(val)) {
  681. extension = m[1];
  682. extWithDot = "." + extension;
  683. }
  684. var info = CodeMirror.findModeByExtension(extension);
  685. previewLink = $('a[data-tab=preview]');
  686. if (info) {
  687. mode = info.mode;
  688. spec = info.mime;
  689. apiCall = mode;
  690. }
  691. else {
  692. apiCall = extension
  693. }
  694. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  695. dataUrl = previewLink.data('url');
  696. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  697. previewLink.show();
  698. }
  699. else {
  700. previewLink.hide();
  701. }
  702. // If this file is a Markdown extensions, we will load that editor and return
  703. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  704. if (setSimpleMDE($editArea)) {
  705. return;
  706. }
  707. }
  708. // Else we are going to use CodeMirror
  709. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  710. return;
  711. }
  712. if (mode) {
  713. codeMirrorEditor.setOption("mode", spec);
  714. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  715. }
  716. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  717. codeMirrorEditor.setOption("lineWrapping", true);
  718. }
  719. else {
  720. codeMirrorEditor.setOption("lineWrapping", false);
  721. }
  722. // get the filename without any folder
  723. var value = $editFilename.val();
  724. if (value.length === 0) {
  725. return;
  726. }
  727. value = value.split('/');
  728. value = value[value.length - 1];
  729. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  730. if (editorconfig.indent_style === 'tab') {
  731. codeMirrorEditor.setOption("indentWithTabs", true);
  732. codeMirrorEditor.setOption('extraKeys', {});
  733. } else {
  734. codeMirrorEditor.setOption("indentWithTabs", false);
  735. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  736. // - https://github.com/codemirror/CodeMirror/issues/988
  737. // - https://codemirror.net/doc/manual.html#keymaps
  738. codeMirrorEditor.setOption('extraKeys', {
  739. Tab: function(cm) {
  740. var spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  741. cm.replaceSelection(spaces);
  742. }
  743. });
  744. }
  745. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  746. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  747. });
  748. }).trigger('keyup');
  749. }
  750. function initOrganization() {
  751. if ($('.organization').length == 0) {
  752. return;
  753. }
  754. // Options
  755. if ($('.organization.settings.options').length > 0) {
  756. $('#org_name').keyup(function () {
  757. var $prompt = $('#org-name-change-prompt');
  758. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  759. $prompt.show();
  760. } else {
  761. $prompt.hide();
  762. }
  763. });
  764. }
  765. }
  766. function initAdmin() {
  767. if ($('.admin').length == 0) {
  768. return;
  769. }
  770. // New user
  771. if ($('.admin.new.user').length > 0 ||
  772. $('.admin.edit.user').length > 0) {
  773. $('#login_type').change(function () {
  774. if ($(this).val().substring(0, 1) == '0') {
  775. $('#login_name').removeAttr('required');
  776. $('.non-local').hide();
  777. $('.local').show();
  778. $('#user_name').focus();
  779. if ($(this).data('password') == "required") {
  780. $('#password').attr('required', 'required');
  781. }
  782. } else {
  783. $('#login_name').attr('required', 'required');
  784. $('.non-local').show();
  785. $('.local').hide();
  786. $('#login_name').focus();
  787. $('#password').removeAttr('required');
  788. }
  789. });
  790. }
  791. function onSecurityProtocolChange() {
  792. if ($('#security_protocol').val() > 0) {
  793. $('.has-tls').show();
  794. } else {
  795. $('.has-tls').hide();
  796. }
  797. }
  798. // New authentication
  799. if ($('.admin.new.authentication').length > 0) {
  800. $('#auth_type').change(function () {
  801. $('.ldap').hide();
  802. $('.dldap').hide();
  803. $('.smtp').hide();
  804. $('.pam').hide();
  805. $('.has-tls').hide();
  806. var authType = $(this).val();
  807. switch (authType) {
  808. case '2': // LDAP
  809. $('.ldap').show();
  810. break;
  811. case '3': // SMTP
  812. $('.smtp').show();
  813. $('.has-tls').show();
  814. break;
  815. case '4': // PAM
  816. $('.pam').show();
  817. break;
  818. case '5': // LDAP
  819. $('.dldap').show();
  820. break;
  821. }
  822. if (authType == '2' || authType == '5') {
  823. onSecurityProtocolChange()
  824. }
  825. });
  826. $('#security_protocol').change(onSecurityProtocolChange)
  827. }
  828. // Edit authentication
  829. if ($('.admin.edit.authentication').length > 0) {
  830. var authType = $('#auth_type').val();
  831. if (authType == '2' || authType == '5') {
  832. $('#security_protocol').change(onSecurityProtocolChange);
  833. }
  834. }
  835. // Notice
  836. if ($('.admin.notice')) {
  837. var $detailModal = $('#detail-modal');
  838. // Attach view detail modals
  839. $('.view-detail').click(function () {
  840. $detailModal.find('.content p').text($(this).data('content'));
  841. $detailModal.modal('show');
  842. return false;
  843. });
  844. // Select actions
  845. var $checkboxes = $('.select.table .ui.checkbox');
  846. $('.select.action').click(function () {
  847. switch ($(this).data('action')) {
  848. case 'select-all':
  849. $checkboxes.checkbox('check');
  850. break;
  851. case 'deselect-all':
  852. $checkboxes.checkbox('uncheck');
  853. break;
  854. case 'inverse':
  855. $checkboxes.checkbox('toggle');
  856. break;
  857. }
  858. });
  859. $('#delete-selection').click(function () {
  860. var $this = $(this);
  861. $this.addClass("loading disabled");
  862. var ids = [];
  863. $checkboxes.each(function () {
  864. if ($(this).checkbox('is checked')) {
  865. ids.push($(this).data('id'));
  866. }
  867. });
  868. $.post($this.data('link'), {
  869. "_csrf": csrf,
  870. "ids": ids
  871. }).done(function () {
  872. window.location.href = $this.data('redirect');
  873. });
  874. });
  875. }
  876. }
  877. function buttonsClickOnEnter() {
  878. $('.ui.button').keypress(function (e) {
  879. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  880. $(this).click();
  881. });
  882. }
  883. function hideWhenLostFocus(body, parent) {
  884. $(document).click(function (e) {
  885. var target = e.target;
  886. if (!$(target).is(body) && !$(target).parents().is(parent)) {
  887. $(body).hide();
  888. }
  889. });
  890. }
  891. function searchUsers() {
  892. if (!$('#search-user-box .results').length) {
  893. return;
  894. }
  895. var $searchUserBox = $('#search-user-box');
  896. var $results = $searchUserBox.find('.results');
  897. $searchUserBox.keyup(function () {
  898. var $this = $(this);
  899. var keyword = $this.find('input').val();
  900. if (keyword.length < 2) {
  901. $results.hide();
  902. return;
  903. }
  904. $.ajax({
  905. url: suburl + '/api/v1/users/search?q=' + keyword,
  906. dataType: "json",
  907. success: function (response) {
  908. var notEmpty = function (str) {
  909. return str && str.length > 0;
  910. };
  911. $results.html('');
  912. if (response.ok && response.data.length) {
  913. var html = '';
  914. $.each(response.data, function (i, item) {
  915. html += '<div class="item"><img class="ui avatar image" src="' + item.avatar_url + '"><span class="username">' + item.username + '</span>';
  916. if (notEmpty(item.full_name)) {
  917. html += ' (' + item.full_name + ')';
  918. }
  919. html += '</div>';
  920. });
  921. $results.html(html);
  922. $this.find('.results .item').click(function () {
  923. $this.find('input').val($(this).find('.username').text());
  924. $results.hide();
  925. });
  926. $results.show();
  927. } else {
  928. $results.hide();
  929. }
  930. }
  931. });
  932. });
  933. $searchUserBox.find('input').focus(function () {
  934. $searchUserBox.keyup();
  935. });
  936. hideWhenLostFocus('#search-user-box .results', '#search-user-box');
  937. }
  938. // FIXME: merge common parts in two functions
  939. function searchRepositories() {
  940. if (!$('#search-repo-box .results').length) {
  941. return;
  942. }
  943. var $searchRepoBox = $('#search-repo-box');
  944. var $results = $searchRepoBox.find('.results');
  945. $searchRepoBox.keyup(function () {
  946. var $this = $(this);
  947. var keyword = $this.find('input').val();
  948. if (keyword.length < 2) {
  949. $results.hide();
  950. return;
  951. }
  952. $.ajax({
  953. url: suburl + '/api/v1/repos/search?q=' + keyword + "&uid=" + $searchRepoBox.data('uid'),
  954. dataType: "json",
  955. success: function (response) {
  956. var notEmpty = function (str) {
  957. return str && str.length > 0;
  958. };
  959. $results.html('');
  960. if (response.ok && response.data.length) {
  961. var html = '';
  962. $.each(response.data, function (i, item) {
  963. html += '<div class="item"><i class="octicon octicon-repo"></i> <span class="fullname">' + item.full_name + '</span></div>';
  964. });
  965. $results.html(html);
  966. $this.find('.results .item').click(function () {
  967. $this.find('input').val($(this).find('.fullname').text().split("/")[1]);
  968. $results.hide();
  969. });
  970. $results.show();
  971. } else {
  972. $results.hide();
  973. }
  974. }
  975. });
  976. });
  977. $searchRepoBox.find('input').focus(function () {
  978. $searchRepoBox.keyup();
  979. });
  980. hideWhenLostFocus('#search-repo-box .results', '#search-repo-box');
  981. }
  982. function initCodeView() {
  983. if ($('.code-view .linenums').length > 0) {
  984. $(document).on('click', '.lines-num span', function (e) {
  985. var $select = $(this);
  986. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  987. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  988. deSelect();
  989. });
  990. $(window).on('hashchange', function (e) {
  991. var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
  992. var $list = $('.code-view ol.linenums > li');
  993. var $first;
  994. if (m) {
  995. $first = $list.filter('.' + m[1]);
  996. selectRange($list, $first, $list.filter('.' + m[2]));
  997. $("html, body").scrollTop($first.offset().top - 200);
  998. return;
  999. }
  1000. m = window.location.hash.match(/^#(L\d+)$/);
  1001. if (m) {
  1002. $first = $list.filter('.' + m[1]);
  1003. selectRange($list, $first);
  1004. $("html, body").scrollTop($first.offset().top - 200);
  1005. }
  1006. }).trigger('hashchange');
  1007. }
  1008. }
  1009. function initCookieWarn() {
  1010. // Automatically shows on init if cookie isnt set
  1011. if (Cookies.get('cookieok') === undefined) {
  1012. $('.cookie.nag')
  1013. .nag({
  1014. key: 'accepts-cookies',
  1015. value: true
  1016. })
  1017. ;
  1018. $('.nag.close').click(function () {
  1019. Cookies.set('cookieok', true, { expires: 365 })
  1020. })
  1021. }
  1022. }
  1023. function initSuggest() {
  1024. $('.ui.ginsearch')
  1025. .search({
  1026. apiSettings: {
  1027. url: '/api/v1/repos/suggest/{query}'
  1028. },
  1029. fields: {
  1030. results: 'Items',
  1031. title: 'Title'
  1032. },
  1033. minCharacters: 3,
  1034. showNoResults: false
  1035. })
  1036. ;
  1037. }
  1038. function initUserSettings() {
  1039. console.log('initUserSettings');
  1040. // Options
  1041. if ($('.user.settings.profile').length > 0) {
  1042. $('#username').keyup(function () {
  1043. var $prompt = $('#name-change-prompt');
  1044. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1045. $prompt.show();
  1046. } else {
  1047. $prompt.hide();
  1048. }
  1049. });
  1050. }
  1051. }
  1052. function initRepositoryCollaboration() {
  1053. console.log('initRepositoryCollaboration');
  1054. // Change collaborator access mode
  1055. $('.access-mode.menu .item').click(function () {
  1056. var $menu = $(this).parent();
  1057. $.post($menu.data('url'), {
  1058. "_csrf": csrf,
  1059. "uid": $menu.data('uid'),
  1060. "mode": $(this).data('value')
  1061. })
  1062. });
  1063. }
  1064. function initWebhookSettings() {
  1065. $('.events.checkbox input').change(function () {
  1066. if ($(this).is(':checked')) {
  1067. $('.events.fields').show();
  1068. }
  1069. });
  1070. $('.non-events.checkbox input').change(function () {
  1071. if ($(this).is(':checked')) {
  1072. $('.events.fields').hide();
  1073. }
  1074. });
  1075. // Highlight payload on first click
  1076. $('.hook.history.list .toggle.button').click(function () {
  1077. $($(this).data('target') + ' .nohighlight').each(function () {
  1078. var $this = $(this);
  1079. $this.removeClass('nohighlight');
  1080. setTimeout(function(){ hljs.highlightBlock($this[0]) }, 500);
  1081. })
  1082. })
  1083. // Trigger delivery
  1084. $('.delivery.button, .redelivery.button').click(function () {
  1085. var $this = $(this);
  1086. $this.addClass('loading disabled');
  1087. $.post($this.data('link'), {
  1088. "_csrf": csrf
  1089. }).done(
  1090. setTimeout(function () {
  1091. window.location.href = $this.data('redirect');
  1092. }, 5000)
  1093. );
  1094. });
  1095. }
  1096. $(document).ready(function () {
  1097. csrf = $('meta[name=_csrf]').attr("content");
  1098. suburl = $('meta[name=_suburl]').attr("content");
  1099. // Set cursor to the end of autofocus input string
  1100. $('input[autofocus]').each(function () {
  1101. $(this).val($(this).val());
  1102. })
  1103. // Show exact time
  1104. $('.time-since').each(function () {
  1105. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1106. });
  1107. // Semantic UI modules.
  1108. $('.ui.dropdown').dropdown({
  1109. forceSelection: false
  1110. });
  1111. $('.jump.dropdown').dropdown({
  1112. action: 'select',
  1113. onShow: function () {
  1114. $('.poping.up').popup('hide');
  1115. }
  1116. });
  1117. $('.slide.up.dropdown').dropdown({
  1118. transition: 'slide up'
  1119. });
  1120. $('.upward.dropdown').dropdown({
  1121. direction: 'upward'
  1122. });
  1123. $('.ui.accordion').accordion();
  1124. $('.ui.checkbox').checkbox();
  1125. $('.ui.progress').progress({
  1126. showActivity: false
  1127. });
  1128. $('.poping.up').popup();
  1129. $('.top.menu .poping.up').popup({
  1130. onShow: function () {
  1131. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1132. return false;
  1133. }
  1134. }
  1135. });
  1136. $('.tabular.menu .item').tab();
  1137. $('.tabable.menu .item').tab();
  1138. $('.toggle.button').click(function () {
  1139. $($(this).data('target')).slideToggle(100);
  1140. });
  1141. // Highlight JS
  1142. if (typeof hljs != 'undefined') {
  1143. if (typeof(Worker) !== "undefined") {
  1144. addEventListener('load', function () {
  1145. var code = document.querySelector('code');
  1146. var worker = new Worker('/plugins/highlighter.js');
  1147. worker.onmessage = function (event) {
  1148. code.innerHTML = event.data;
  1149. }
  1150. worker.postMessage(code.textContent);
  1151. })
  1152. } else {
  1153. hljs.initHighlightingOnLoad()
  1154. }
  1155. }
  1156. // Dropzone
  1157. var $dropzone = $('#dropzone');
  1158. if ($dropzone.length > 0) {
  1159. // Disable auto discover for all elements:
  1160. Dropzone.autoDiscover = false;
  1161. var filenameDict = {};
  1162. $dropzone.dropzone({
  1163. url: $dropzone.data('upload-url'),
  1164. headers: {"X-Csrf-Token": csrf},
  1165. maxFiles: $dropzone.data('max-file'),
  1166. maxFilesize: $dropzone.data('max-size'),
  1167. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1168. addRemoveLinks: true,
  1169. dictDefaultMessage: $dropzone.data('default-message'),
  1170. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1171. dictFileTooBig: $dropzone.data('file-too-big'),
  1172. dictRemoveFile: $dropzone.data('remove-file'),
  1173. init: function () {
  1174. this.on("success", function (file, data) {
  1175. filenameDict[file.name] = data.uuid;
  1176. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  1177. $('.files').append(input);
  1178. });
  1179. this.on("removedfile", function (file) {
  1180. if (file.name in filenameDict) {
  1181. $('#' + filenameDict[file.name]).remove();
  1182. }
  1183. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1184. $.post($dropzone.data('remove-url'), {
  1185. file: filenameDict[file.name],
  1186. _csrf: $dropzone.data('csrf')
  1187. });
  1188. }
  1189. })
  1190. }
  1191. });
  1192. }
  1193. // Emojify
  1194. emojify.setConfig({
  1195. img_dir: suburl + '/img/emoji',
  1196. ignore_emoticons: true
  1197. });
  1198. var hasEmoji = document.getElementsByClassName('has-emoji');
  1199. for (var i = 0; i < hasEmoji.length; i++) {
  1200. emojify.run(hasEmoji[i]);
  1201. }
  1202. // Clipboard JS
  1203. var clipboard = new Clipboard('.clipboard');
  1204. clipboard.on('success', function (e) {
  1205. e.clearSelection();
  1206. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1207. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  1208. $('#' + e.trigger.getAttribute('id')).popup('show');
  1209. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1210. });
  1211. clipboard.on('error', function (e) {
  1212. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1213. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  1214. $('#' + e.trigger.getAttribute('id')).popup('show');
  1215. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1216. });
  1217. // AJAX load buttons
  1218. $('.ajax-load-button').click(function () {
  1219. var $this = $(this);
  1220. $this.addClass('disabled');
  1221. $.ajax({
  1222. url: $this.data('url'),
  1223. headers: {
  1224. 'X-AJAX': "true"
  1225. }
  1226. }).success(function (data, status, request) {
  1227. $(data).insertBefore($this);
  1228. // Update new URL or remove self if no more feeds
  1229. var url = request.getResponseHeader('X-AJAX-URL');
  1230. if (url) {
  1231. $this.data('url', url);
  1232. $this.removeClass('disabled');
  1233. } else {
  1234. $this.remove();
  1235. }
  1236. });
  1237. });
  1238. // Helpers
  1239. $('.delete-button').click(function () {
  1240. var $this = $(this);
  1241. $('.delete.modal').modal({
  1242. closable: false,
  1243. onApprove: function () {
  1244. if ($this.data('type') == "form") {
  1245. $($this.data('form')).submit();
  1246. return;
  1247. }
  1248. $.post($this.data('url'), {
  1249. "_csrf": csrf,
  1250. "id": $this.data("id")
  1251. }).success(function (data) {
  1252. window.location.href = data.redirect;
  1253. });
  1254. }
  1255. }).modal('show');
  1256. return false;
  1257. });
  1258. $('.show-panel.button').click(function () {
  1259. $($(this).data('panel')).show();
  1260. });
  1261. $('.show-modal.button').click(function () {
  1262. $($(this).data('modal')).modal('show');
  1263. });
  1264. $('.delete-post.button').click(function () {
  1265. var $this = $(this);
  1266. $.post($this.data('request-url'), {
  1267. "_csrf": csrf
  1268. }).done(function () {
  1269. window.location.href = $this.data('done-url');
  1270. });
  1271. });
  1272. // Check or select on option to enable/disable target region
  1273. $('.enable-system').change(function () {
  1274. if (this.checked) {
  1275. $($(this).data('target')).removeClass('disabled');
  1276. } else {
  1277. $($(this).data('target')).addClass('disabled');
  1278. }
  1279. });
  1280. $('.enable-system-radio').change(function () {
  1281. $($(this).data('enable')).removeClass('disabled');
  1282. $($(this).data('disable')).addClass('disabled');
  1283. });
  1284. // Set anchor.
  1285. $('.markdown').each(function () {
  1286. var headers = {};
  1287. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  1288. var node = $(this);
  1289. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  1290. var name = val;
  1291. if (headers[val] > 0) {
  1292. name = val + '-' + headers[val];
  1293. }
  1294. if (headers[val] == undefined) {
  1295. headers[val] = 1;
  1296. } else {
  1297. headers[val] += 1;
  1298. }
  1299. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  1300. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  1301. });
  1302. });
  1303. buttonsClickOnEnter();
  1304. searchUsers();
  1305. searchRepositories();
  1306. initCommentForm();
  1307. initRepository();
  1308. initWikiForm();
  1309. initEditForm();
  1310. initEditor();
  1311. initOrganization();
  1312. initAdmin();
  1313. initCodeView();
  1314. initCookieWarn();
  1315. initSuggest();
  1316. // Repo clone url.
  1317. if ($('#repo-clone-url').length > 0) {
  1318. switch (localStorage.getItem('repo-clone-protocol')) {
  1319. case 'ssh':
  1320. if ($('#repo-clone-ssh').click().length === 0) {
  1321. $('#repo-clone-https').click();
  1322. }
  1323. break;
  1324. default:
  1325. $('#repo-clone-gin').click();
  1326. break;
  1327. }
  1328. }
  1329. var routes = {
  1330. 'div.user.settings': initUserSettings,
  1331. 'div.repository.settings.collaboration': initRepositoryCollaboration,
  1332. 'div.webhook.settings': initWebhookSettings
  1333. };
  1334. var selector;
  1335. for (selector in routes) {
  1336. if ($(selector).length > 0) {
  1337. routes[selector]();
  1338. break;
  1339. }
  1340. }
  1341. });
  1342. function changeHash(hash) {
  1343. if (history.pushState) {
  1344. history.pushState(null, null, hash);
  1345. }
  1346. else {
  1347. location.hash = hash;
  1348. }
  1349. }
  1350. function deSelect() {
  1351. if (window.getSelection) {
  1352. window.getSelection().removeAllRanges();
  1353. } else {
  1354. document.selection.empty();
  1355. }
  1356. }
  1357. function selectRange($list, $select, $from) {
  1358. $list.removeClass('active');
  1359. if ($from) {
  1360. var a = parseInt($select.attr('rel').substr(1));
  1361. var b = parseInt($from.attr('rel').substr(1));
  1362. var c;
  1363. if (a != b) {
  1364. if (a > b) {
  1365. c = a;
  1366. a = b;
  1367. b = c;
  1368. }
  1369. var classes = [];
  1370. for (var i = a; i <= b; i++) {
  1371. classes.push('.L' + i);
  1372. }
  1373. $list.filter(classes.join(',')).addClass('active');
  1374. changeHash('#L' + a + '-' + 'L' + b);
  1375. return
  1376. }
  1377. }
  1378. $select.addClass('active');
  1379. changeHash('#' + $select.attr('rel'));
  1380. }
  1381. $(function () {
  1382. if ($('.user.signin').length > 0) return;
  1383. $('form').areYouSure();
  1384. });