gogs.js 58 KB

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