gogs.js 58 KB

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