gogs.js 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  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. $('.github').hide();
  806. $('.has-tls').hide();
  807. var authType = $(this).val();
  808. switch (authType) {
  809. case '2': // LDAP
  810. $('.ldap').show();
  811. break;
  812. case '3': // SMTP
  813. $('.smtp').show();
  814. $('.has-tls').show();
  815. break;
  816. case '4': // PAM
  817. $('.pam').show();
  818. break;
  819. case '5': // LDAP
  820. $('.dldap').show();
  821. break;
  822. case '6': //GITHUB
  823. $('.github').show();
  824. break;
  825. }
  826. if (authType == '2' || authType == '5') {
  827. onSecurityProtocolChange()
  828. }
  829. });
  830. $('#security_protocol').change(onSecurityProtocolChange)
  831. }
  832. // Edit authentication
  833. if ($('.admin.edit.authentication').length > 0) {
  834. var authType = $('#auth_type').val();
  835. if (authType == '2' || authType == '5') {
  836. $('#security_protocol').change(onSecurityProtocolChange);
  837. }
  838. }
  839. // Notice
  840. if ($('.admin.notice')) {
  841. var $detailModal = $('#detail-modal');
  842. // Attach view detail modals
  843. $('.view-detail').click(function () {
  844. $detailModal.find('.content p').text($(this).data('content'));
  845. $detailModal.modal('show');
  846. return false;
  847. });
  848. // Select actions
  849. var $checkboxes = $('.select.table .ui.checkbox');
  850. $('.select.action').click(function () {
  851. switch ($(this).data('action')) {
  852. case 'select-all':
  853. $checkboxes.checkbox('check');
  854. break;
  855. case 'deselect-all':
  856. $checkboxes.checkbox('uncheck');
  857. break;
  858. case 'inverse':
  859. $checkboxes.checkbox('toggle');
  860. break;
  861. }
  862. });
  863. $('#delete-selection').click(function () {
  864. var $this = $(this);
  865. $this.addClass("loading disabled");
  866. var ids = [];
  867. $checkboxes.each(function () {
  868. if ($(this).checkbox('is checked')) {
  869. ids.push($(this).data('id'));
  870. }
  871. });
  872. $.post($this.data('link'), {
  873. "_csrf": csrf,
  874. "ids": ids
  875. }).done(function () {
  876. window.location.href = $this.data('redirect');
  877. });
  878. });
  879. }
  880. }
  881. function buttonsClickOnEnter() {
  882. $('.ui.button').keypress(function (e) {
  883. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  884. $(this).click();
  885. });
  886. }
  887. function hideWhenLostFocus(body, parent) {
  888. $(document).click(function (e) {
  889. var target = e.target;
  890. if (!$(target).is(body) && !$(target).parents().is(parent)) {
  891. $(body).hide();
  892. }
  893. });
  894. }
  895. function searchUsers() {
  896. if (!$('#search-user-box .results').length) {
  897. return;
  898. }
  899. var $searchUserBox = $('#search-user-box');
  900. var $results = $searchUserBox.find('.results');
  901. $searchUserBox.keyup(function () {
  902. var $this = $(this);
  903. var keyword = $this.find('input').val();
  904. if (keyword.length < 2) {
  905. $results.hide();
  906. return;
  907. }
  908. $.ajax({
  909. url: suburl + '/api/v1/users/search?q=' + keyword,
  910. dataType: "json",
  911. success: function (response) {
  912. var notEmpty = function (str) {
  913. return str && str.length > 0;
  914. };
  915. $results.html('');
  916. if (response.ok && response.data.length) {
  917. var html = '';
  918. $.each(response.data, function (i, item) {
  919. html += '<div class="item"><img class="ui avatar image" src="' + item.avatar_url + '"><span class="username">' + item.username + '</span>';
  920. if (notEmpty(item.full_name)) {
  921. html += ' (' + item.full_name + ')';
  922. }
  923. html += '</div>';
  924. });
  925. $results.html(html);
  926. $this.find('.results .item').click(function () {
  927. $this.find('input').val($(this).find('.username').text());
  928. $results.hide();
  929. });
  930. $results.show();
  931. } else {
  932. $results.hide();
  933. }
  934. }
  935. });
  936. });
  937. $searchUserBox.find('input').focus(function () {
  938. $searchUserBox.keyup();
  939. });
  940. hideWhenLostFocus('#search-user-box .results', '#search-user-box');
  941. }
  942. // FIXME: merge common parts in two functions
  943. function searchRepositories() {
  944. if (!$('#search-repo-box .results').length) {
  945. return;
  946. }
  947. var $searchRepoBox = $('#search-repo-box');
  948. var $results = $searchRepoBox.find('.results');
  949. $searchRepoBox.keyup(function () {
  950. var $this = $(this);
  951. var keyword = $this.find('input').val();
  952. if (keyword.length < 2) {
  953. $results.hide();
  954. return;
  955. }
  956. $.ajax({
  957. url: suburl + '/api/v1/repos/search?q=' + keyword + "&uid=" + $searchRepoBox.data('uid'),
  958. dataType: "json",
  959. success: function (response) {
  960. var notEmpty = function (str) {
  961. return str && str.length > 0;
  962. };
  963. $results.html('');
  964. if (response.ok && response.data.length) {
  965. var html = '';
  966. $.each(response.data, function (i, item) {
  967. html += '<div class="item"><i class="octicon octicon-repo"></i> <span class="fullname">' + item.full_name + '</span></div>';
  968. });
  969. $results.html(html);
  970. $this.find('.results .item').click(function () {
  971. $this.find('input').val($(this).find('.fullname').text().split("/")[1]);
  972. $results.hide();
  973. });
  974. $results.show();
  975. } else {
  976. $results.hide();
  977. }
  978. }
  979. });
  980. });
  981. $searchRepoBox.find('input').focus(function () {
  982. $searchRepoBox.keyup();
  983. });
  984. hideWhenLostFocus('#search-repo-box .results', '#search-repo-box');
  985. }
  986. function initCodeView() {
  987. if ($('.code-view .linenums').length > 0) {
  988. $(document).on('click', '.lines-num span', function (e) {
  989. var $select = $(this);
  990. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  991. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  992. deSelect();
  993. });
  994. $(window).on('hashchange', function (e) {
  995. var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
  996. var $list = $('.code-view ol.linenums > li');
  997. var $first;
  998. if (m) {
  999. $first = $list.filter('.' + m[1]);
  1000. selectRange($list, $first, $list.filter('.' + m[2]));
  1001. $("html, body").scrollTop($first.offset().top - 200);
  1002. return;
  1003. }
  1004. m = window.location.hash.match(/^#(L\d+)$/);
  1005. if (m) {
  1006. $first = $list.filter('.' + m[1]);
  1007. selectRange($list, $first);
  1008. $("html, body").scrollTop($first.offset().top - 200);
  1009. }
  1010. }).trigger('hashchange');
  1011. }
  1012. }
  1013. function initCookieWarn() {
  1014. // Automatically shows on init if cookie isnt set
  1015. if (Cookies.get('cookieok') === undefined) {
  1016. $('.cookie.nag')
  1017. .nag({
  1018. key: 'accepts-cookies',
  1019. value: true
  1020. })
  1021. ;
  1022. $('.nag.close').click(function () {
  1023. Cookies.set('cookieok', true, { expires: 365 })
  1024. })
  1025. }
  1026. }
  1027. function initSuggest() {
  1028. $('.ui.ginsearch')
  1029. .search({
  1030. apiSettings: {
  1031. url: '/api/v1/repos/suggest/{query}'
  1032. },
  1033. fields: {
  1034. results: 'Items',
  1035. title: 'Title'
  1036. },
  1037. minCharacters: 3,
  1038. showNoResults: false
  1039. })
  1040. ;
  1041. }
  1042. function initUserSettings() {
  1043. console.log('initUserSettings');
  1044. // Options
  1045. if ($('.user.settings.profile').length > 0) {
  1046. $('#username').keyup(function () {
  1047. var $prompt = $('#name-change-prompt');
  1048. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1049. $prompt.show();
  1050. } else {
  1051. $prompt.hide();
  1052. }
  1053. });
  1054. }
  1055. }
  1056. function initRepositoryCollaboration() {
  1057. console.log('initRepositoryCollaboration');
  1058. // Change collaborator access mode
  1059. $('.access-mode.menu .item').click(function () {
  1060. var $menu = $(this).parent();
  1061. $.post($menu.data('url'), {
  1062. "_csrf": csrf,
  1063. "uid": $menu.data('uid'),
  1064. "mode": $(this).data('value')
  1065. })
  1066. });
  1067. }
  1068. function initWebhookSettings() {
  1069. $('.events.checkbox input').change(function () {
  1070. if ($(this).is(':checked')) {
  1071. $('.events.fields').show();
  1072. }
  1073. });
  1074. $('.non-events.checkbox input').change(function () {
  1075. if ($(this).is(':checked')) {
  1076. $('.events.fields').hide();
  1077. }
  1078. });
  1079. // Highlight payload on first click
  1080. $('.hook.history.list .toggle.button').click(function () {
  1081. $($(this).data('target') + ' .nohighlight').each(function () {
  1082. var $this = $(this);
  1083. $this.removeClass('nohighlight');
  1084. setTimeout(function () { hljs.highlightBlock($this[0]) }, 500);
  1085. })
  1086. })
  1087. // Trigger delivery
  1088. $('.delivery.button, .redelivery.button').click(function () {
  1089. var $this = $(this);
  1090. $this.addClass('loading disabled');
  1091. $.post($this.data('link'), {
  1092. "_csrf": csrf
  1093. }).done(
  1094. setTimeout(function () {
  1095. window.location.href = $this.data('redirect');
  1096. }, 5000)
  1097. );
  1098. });
  1099. }
  1100. $(document).ready(function () {
  1101. csrf = $('meta[name=_csrf]').attr("content");
  1102. suburl = $('meta[name=_suburl]').attr("content");
  1103. // Set cursor to the end of autofocus input string
  1104. $('input[autofocus]').each(function () {
  1105. $(this).val($(this).val());
  1106. })
  1107. // Show exact time
  1108. $('.time-since').each(function () {
  1109. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1110. });
  1111. // Semantic UI modules.
  1112. $('.ui.dropdown').dropdown({
  1113. forceSelection: false
  1114. });
  1115. $('.jump.dropdown').dropdown({
  1116. action: 'select',
  1117. onShow: function () {
  1118. $('.poping.up').popup('hide');
  1119. }
  1120. });
  1121. $('.slide.up.dropdown').dropdown({
  1122. transition: 'slide up'
  1123. });
  1124. $('.upward.dropdown').dropdown({
  1125. direction: 'upward'
  1126. });
  1127. $('.ui.accordion').accordion();
  1128. $('.ui.checkbox').checkbox();
  1129. $('.ui.progress').progress({
  1130. showActivity: false
  1131. });
  1132. $('.poping.up').popup();
  1133. $('.top.menu .poping.up').popup({
  1134. onShow: function () {
  1135. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1136. return false;
  1137. }
  1138. }
  1139. });
  1140. $('.tabular.menu .item').tab();
  1141. $('.tabable.menu .item').tab();
  1142. $('.toggle.button').click(function () {
  1143. $($(this).data('target')).slideToggle(100);
  1144. });
  1145. // Highlight JS
  1146. if (typeof hljs != 'undefined') {
  1147. if (typeof(Worker) !== "undefined") {
  1148. addEventListener('load', function () {
  1149. var code = document.querySelector('code');
  1150. var worker = new Worker('/plugins/highlighter.js');
  1151. worker.onmessage = function (event) {
  1152. code.innerHTML = event.data;
  1153. }
  1154. worker.postMessage(code.textContent);
  1155. })
  1156. } else {
  1157. hljs.initHighlightingOnLoad()
  1158. }
  1159. }
  1160. // Dropzone
  1161. var $dropzone = $('#dropzone');
  1162. if ($dropzone.length > 0) {
  1163. // Disable auto discover for all elements:
  1164. Dropzone.autoDiscover = false;
  1165. var filenameDict = {};
  1166. $dropzone.dropzone({
  1167. url: $dropzone.data('upload-url'),
  1168. headers: { "X-Csrf-Token": csrf },
  1169. maxFiles: $dropzone.data('max-file'),
  1170. maxFilesize: $dropzone.data('max-size'),
  1171. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1172. addRemoveLinks: true,
  1173. dictDefaultMessage: $dropzone.data('default-message'),
  1174. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1175. dictFileTooBig: $dropzone.data('file-too-big'),
  1176. dictRemoveFile: $dropzone.data('remove-file'),
  1177. init: function () {
  1178. this.on("success", function (file, data) {
  1179. filenameDict[file.name] = data.uuid;
  1180. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  1181. $('.files').append(input);
  1182. });
  1183. this.on("removedfile", function (file) {
  1184. if (file.name in filenameDict) {
  1185. $('#' + filenameDict[file.name]).remove();
  1186. }
  1187. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1188. $.post($dropzone.data('remove-url'), {
  1189. file: filenameDict[file.name],
  1190. _csrf: $dropzone.data('csrf')
  1191. });
  1192. }
  1193. })
  1194. }
  1195. });
  1196. }
  1197. // Emojify
  1198. emojify.setConfig({
  1199. img_dir: suburl + '/img/emoji',
  1200. ignore_emoticons: true
  1201. });
  1202. var hasEmoji = document.getElementsByClassName('has-emoji');
  1203. for (var i = 0; i < hasEmoji.length; i++) {
  1204. emojify.run(hasEmoji[i]);
  1205. }
  1206. // Clipboard JS
  1207. var clipboard = new Clipboard('.clipboard');
  1208. clipboard.on('success', function (e) {
  1209. e.clearSelection();
  1210. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1211. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  1212. $('#' + e.trigger.getAttribute('id')).popup('show');
  1213. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1214. });
  1215. clipboard.on('error', function (e) {
  1216. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1217. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  1218. $('#' + e.trigger.getAttribute('id')).popup('show');
  1219. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1220. });
  1221. // Autosize
  1222. if ($('#description.autosize').length > 0) {
  1223. autosize($('#description'));
  1224. showMessageMaxLength(512, 'description', 'descLength');
  1225. }
  1226. // AJAX load buttons
  1227. $('.ajax-load-button').click(function () {
  1228. var $this = $(this);
  1229. $this.addClass('disabled');
  1230. $.ajax({
  1231. url: $this.data('url'),
  1232. headers: {
  1233. 'X-AJAX': "true"
  1234. }
  1235. }).success(function (data, status, request) {
  1236. $(data).insertBefore($this);
  1237. // Update new URL or remove self if no more feeds
  1238. var url = request.getResponseHeader('X-AJAX-URL');
  1239. if (url) {
  1240. $this.data('url', url);
  1241. $this.removeClass('disabled');
  1242. } else {
  1243. $this.remove();
  1244. }
  1245. });
  1246. });
  1247. // Helpers
  1248. $('.delete-button').click(function () {
  1249. var $this = $(this);
  1250. $('.delete.modal').modal({
  1251. closable: false,
  1252. onApprove: function () {
  1253. if ($this.data('type') == "form") {
  1254. $($this.data('form')).submit();
  1255. return;
  1256. }
  1257. $.post($this.data('url'), {
  1258. "_csrf": csrf,
  1259. "id": $this.data("id")
  1260. }).success(function (data) {
  1261. window.location.href = data.redirect;
  1262. });
  1263. }
  1264. }).modal('show');
  1265. return false;
  1266. });
  1267. $('.show-panel.button').click(function () {
  1268. $($(this).data('panel')).show();
  1269. });
  1270. $('.show-modal.button').click(function () {
  1271. $($(this).data('modal')).modal('show');
  1272. });
  1273. $('.delete-post.button').click(function () {
  1274. var $this = $(this);
  1275. $.post($this.data('request-url'), {
  1276. "_csrf": csrf
  1277. }).done(function () {
  1278. window.location.href = $this.data('done-url');
  1279. });
  1280. });
  1281. // To make arbitrary form element to behave like a submit button
  1282. $('.submit-button').click(function () {
  1283. $($(this).data('form')).submit();
  1284. });
  1285. // Check or select on option to enable/disable target region
  1286. $('.enable-system').change(function () {
  1287. if (this.checked) {
  1288. $($(this).data('target')).removeClass('disabled');
  1289. } else {
  1290. $($(this).data('target')).addClass('disabled');
  1291. }
  1292. });
  1293. $('.enable-system-radio').change(function () {
  1294. $($(this).data('enable')).removeClass('disabled');
  1295. $($(this).data('disable')).addClass('disabled');
  1296. });
  1297. // Set anchor.
  1298. $('.markdown').each(function () {
  1299. var headers = {};
  1300. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  1301. var node = $(this);
  1302. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  1303. var name = val;
  1304. if (headers[val] > 0) {
  1305. name = val + '-' + headers[val];
  1306. }
  1307. if (headers[val] == undefined) {
  1308. headers[val] = 1;
  1309. } else {
  1310. headers[val] += 1;
  1311. }
  1312. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  1313. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  1314. });
  1315. });
  1316. buttonsClickOnEnter();
  1317. searchUsers();
  1318. searchRepositories();
  1319. initCommentForm();
  1320. initRepository();
  1321. initWikiForm();
  1322. initEditForm();
  1323. initEditor();
  1324. initOrganization();
  1325. initAdmin();
  1326. initCodeView();
  1327. initCookieWarn();
  1328. initSuggest();
  1329. // Repo clone url.
  1330. if ($('#repo-clone-url').length > 0) {
  1331. switch (localStorage.getItem('repo-clone-protocol')) {
  1332. case 'ssh':
  1333. if ($('#repo-clone-ssh').click().length === 0) {
  1334. $('#repo-clone-https').click();
  1335. }
  1336. break;
  1337. default:
  1338. $('#repo-clone-gin').click();
  1339. break;
  1340. }
  1341. }
  1342. var routes = {
  1343. 'div.user.settings': initUserSettings,
  1344. 'div.repository.settings.collaboration': initRepositoryCollaboration,
  1345. 'div.webhook.settings': initWebhookSettings
  1346. };
  1347. var selector;
  1348. for (selector in routes) {
  1349. if ($(selector).length > 0) {
  1350. routes[selector]();
  1351. break;
  1352. }
  1353. }
  1354. });
  1355. function changeHash(hash) {
  1356. if (history.pushState) {
  1357. history.pushState(null, null, hash);
  1358. }
  1359. else {
  1360. location.hash = hash;
  1361. }
  1362. }
  1363. function deSelect() {
  1364. if (window.getSelection) {
  1365. window.getSelection().removeAllRanges();
  1366. } else {
  1367. document.selection.empty();
  1368. }
  1369. }
  1370. function selectRange($list, $select, $from) {
  1371. $list.removeClass('active');
  1372. if ($from) {
  1373. var a = parseInt($select.attr('rel').substr(1));
  1374. var b = parseInt($from.attr('rel').substr(1));
  1375. var c;
  1376. if (a != b) {
  1377. if (a > b) {
  1378. c = a;
  1379. a = b;
  1380. b = c;
  1381. }
  1382. var classes = [];
  1383. for (var i = a; i <= b; i++) {
  1384. classes.push('.L' + i);
  1385. }
  1386. $list.filter(classes.join(',')).addClass('active');
  1387. changeHash('#L' + a + '-' + 'L' + b);
  1388. return
  1389. }
  1390. }
  1391. $select.addClass('active');
  1392. changeHash('#' + $select.attr('rel'));
  1393. }
  1394. $(function () {
  1395. if ($('.user.signin').length > 0) return;
  1396. $('form').areYouSure();
  1397. });
  1398. // getByteLen counts bytes in a string's UTF-8 representation.
  1399. function getByteLen(normalVal) {
  1400. // Force string type
  1401. normalVal = String(normalVal);
  1402. var byteLen = 0;
  1403. for (var i = 0; i < normalVal.length; i++) {
  1404. var c = normalVal.charCodeAt(i);
  1405. byteLen += c < (1 << 7) ? 1 :
  1406. c < (1 << 11) ? 2 :
  1407. c < (1 << 16) ? 3 :
  1408. c < (1 << 21) ? 4 :
  1409. c < (1 << 26) ? 5 :
  1410. c < (1 << 31) ? 6 : Number.NaN;
  1411. }
  1412. return byteLen;
  1413. }
  1414. function showMessageMaxLength(maxLen, textElemId, counterId) {
  1415. var $msg = $('#' + textElemId);
  1416. $('#' + counterId).html(maxLen - getByteLen($msg.val()));
  1417. var onMessageKey = function (e) {
  1418. var $msg = $(this);
  1419. var text = $msg.val();
  1420. var len = getByteLen(text);
  1421. var remainder = maxLen - len;
  1422. if (len >= maxLen) {
  1423. $msg.val($msg.val().substr(0, maxLen));
  1424. remainder = 0;
  1425. }
  1426. $('#' + counterId).html(remainder);
  1427. };
  1428. $msg.keyup(onMessageKey).keydown(onMessageKey);
  1429. }