gogs.js 50 KB

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