You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779
  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. "context": $this.data('context'),
  62. "content": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  63. },
  64. function (data) {
  65. var $diffPreviewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('diff') + '"]');
  66. $diffPreviewPanel.html(data);
  67. emojify.run($diffPreviewPanel[0]);
  68. }
  69. );
  70. });
  71. }
  72. function initEditForm() {
  73. if ($('.edit.form').length == 0) {
  74. return;
  75. }
  76. initEditPreviewTab($('.edit.form'));
  77. initEditDiffTab($('.edit.form'));
  78. }
  79. function updateIssuesMeta(url, action, issueIds, elementId, afterSuccess) {
  80. $.ajax({
  81. type: "POST",
  82. url: url,
  83. data: {
  84. "_csrf": csrf,
  85. "action": action,
  86. "issue_ids": issueIds,
  87. "id": elementId
  88. },
  89. success: afterSuccess
  90. })
  91. }
  92. function initCommentForm() {
  93. if ($('.comment.form').length == 0) {
  94. return
  95. }
  96. initCommentPreviewTab($('.comment.form'));
  97. // Labels
  98. var $list = $('.ui.labels.list');
  99. var $noSelect = $list.find('.no-select');
  100. var $labelMenu = $('.select-label .menu');
  101. var hasLabelUpdateAction = $labelMenu.data('action') == 'update';
  102. $('.select-label').dropdown('setting', 'onHide', function(){
  103. if (hasLabelUpdateAction) {
  104. location.reload();
  105. }
  106. });
  107. $labelMenu.find('.item:not(.no-select)').click(function () {
  108. if ($(this).hasClass('checked')) {
  109. $(this).removeClass('checked');
  110. $(this).find('.octicon').removeClass('octicon-check');
  111. if (hasLabelUpdateAction) {
  112. updateIssuesMeta(
  113. $labelMenu.data('update-url'),
  114. "detach",
  115. $labelMenu.data('issue-id'),
  116. $(this).data('id')
  117. );
  118. }
  119. } else {
  120. $(this).addClass('checked');
  121. $(this).find('.octicon').addClass('octicon-check');
  122. if (hasLabelUpdateAction) {
  123. updateIssuesMeta(
  124. $labelMenu.data('update-url'),
  125. "attach",
  126. $labelMenu.data('issue-id'),
  127. $(this).data('id')
  128. );
  129. }
  130. }
  131. var labelIds = [];
  132. $(this).parent().find('.item').each(function () {
  133. if ($(this).hasClass('checked')) {
  134. labelIds.push($(this).data('id'));
  135. $($(this).data('id-selector')).removeClass('hide');
  136. } else {
  137. $($(this).data('id-selector')).addClass('hide');
  138. }
  139. });
  140. if (labelIds.length == 0) {
  141. $noSelect.removeClass('hide');
  142. } else {
  143. $noSelect.addClass('hide');
  144. }
  145. $($(this).parent().data('id')).val(labelIds.join(","));
  146. return false;
  147. });
  148. $labelMenu.find('.no-select.item').click(function () {
  149. if (hasLabelUpdateAction) {
  150. updateIssuesMeta(
  151. $labelMenu.data('update-url'),
  152. "clear",
  153. $labelMenu.data('issue-id'),
  154. ""
  155. );
  156. }
  157. $(this).parent().find('.item').each(function () {
  158. $(this).removeClass('checked');
  159. $(this).find('.octicon').removeClass('octicon-check');
  160. });
  161. $list.find('.item').each(function () {
  162. $(this).addClass('hide');
  163. });
  164. $noSelect.removeClass('hide');
  165. $($(this).parent().data('id')).val('');
  166. });
  167. function selectItem(select_id, input_id) {
  168. var $menu = $(select_id + ' .menu');
  169. var $list = $('.ui' + select_id + '.list');
  170. var hasUpdateAction = $menu.data('action') == 'update';
  171. $menu.find('.item:not(.no-select)').click(function () {
  172. $(this).parent().find('.item').each(function () {
  173. $(this).removeClass('selected active')
  174. });
  175. $(this).addClass('selected active');
  176. if (hasUpdateAction) {
  177. updateIssuesMeta(
  178. $menu.data('update-url'),
  179. "",
  180. $menu.data('issue-id'),
  181. $(this).data('id'),
  182. function() { location.reload(); }
  183. );
  184. }
  185. switch (input_id) {
  186. case '#milestone_id':
  187. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  188. $(this).text() + '</a>');
  189. break;
  190. case '#assignee_id':
  191. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  192. '<img class="ui avatar image" src=' + $(this).data('avatar') + '>' +
  193. $(this).text() + '</a>');
  194. }
  195. $('.ui' + select_id + '.list .no-select').addClass('hide');
  196. $(input_id).val($(this).data('id'));
  197. });
  198. $menu.find('.no-select.item').click(function () {
  199. $(this).parent().find('.item:not(.no-select)').each(function () {
  200. $(this).removeClass('selected active')
  201. });
  202. if (hasUpdateAction) {
  203. updateIssuesMeta(
  204. $menu.data('update-url'),
  205. "",
  206. $menu.data('issue-id'),
  207. $(this).data('id'),
  208. function() { location.reload(); }
  209. );
  210. }
  211. $list.find('.selected').html('');
  212. $list.find('.no-select').removeClass('hide');
  213. $(input_id).val('');
  214. });
  215. }
  216. // Milestone and assignee
  217. selectItem('.select-milestone', '#milestone_id');
  218. selectItem('.select-assignee', '#assignee_id');
  219. }
  220. function initInstall() {
  221. if ($('.install').length == 0) {
  222. return;
  223. }
  224. if ($('#db_host').val()=="") {
  225. $('#db_host').val("127.0.0.1:3306");
  226. $('#db_user').val("gitea");
  227. $('#db_name').val("gitea");
  228. }
  229. // Database type change detection.
  230. $("#db_type").change(function () {
  231. var sqliteDefault = 'data/gitea.db';
  232. var tidbDefault = 'data/gitea_tidb';
  233. var dbType = $(this).val();
  234. if (dbType === "SQLite3" || dbType === "TiDB") {
  235. $('#sql_settings').hide();
  236. $('#pgsql_settings').hide();
  237. $('#sqlite_settings').show();
  238. if (dbType === "SQLite3" && $('#db_path').val() == tidbDefault) {
  239. $('#db_path').val(sqliteDefault);
  240. } else if (dbType === "TiDB" && $('#db_path').val() == sqliteDefault) {
  241. $('#db_path').val(tidbDefault);
  242. }
  243. return;
  244. }
  245. var dbDefaults = {
  246. "MySQL": "127.0.0.1:3306",
  247. "PostgreSQL": "127.0.0.1:5432",
  248. "MSSQL": "127.0.0.1:1433"
  249. };
  250. $('#sqlite_settings').hide();
  251. $('#sql_settings').show();
  252. $('#pgsql_settings').toggle(dbType === "PostgreSQL");
  253. $.each(dbDefaults, function(type, defaultHost) {
  254. if ($('#db_host').val() == defaultHost) {
  255. $('#db_host').val(dbDefaults[dbType]);
  256. return false;
  257. }
  258. });
  259. });
  260. // TODO: better handling of exclusive relations.
  261. $('#offline-mode input').change(function () {
  262. if ($(this).is(':checked')) {
  263. $('#disable-gravatar').checkbox('check');
  264. $('#federated-avatar-lookup').checkbox('uncheck');
  265. }
  266. });
  267. $('#disable-gravatar input').change(function () {
  268. if ($(this).is(':checked')) {
  269. $('#federated-avatar-lookup').checkbox('uncheck');
  270. } else {
  271. $('#offline-mode').checkbox('uncheck');
  272. }
  273. });
  274. $('#federated-avatar-lookup input').change(function () {
  275. if ($(this).is(':checked')) {
  276. $('#disable-gravatar').checkbox('uncheck');
  277. $('#offline-mode').checkbox('uncheck');
  278. }
  279. });
  280. $('#disable-registration input').change(function () {
  281. if ($(this).is(':checked')) {
  282. $('#enable-captcha').checkbox('uncheck');
  283. }
  284. });
  285. $('#enable-captcha input').change(function () {
  286. if ($(this).is(':checked')) {
  287. $('#disable-registration').checkbox('uncheck');
  288. }
  289. });
  290. }
  291. function initRepository() {
  292. if ($('.repository').length == 0) {
  293. return;
  294. }
  295. function initFilterSearchDropdown(selector) {
  296. var $dropdown = $(selector);
  297. $dropdown.dropdown({
  298. fullTextSearch: true,
  299. onChange: function (text, value, $choice) {
  300. window.location.href = $choice.data('url');
  301. console.log($choice.data('url'))
  302. },
  303. message: {noResults: $dropdown.data('no-results')}
  304. });
  305. }
  306. // File list and commits
  307. if ($('.repository.file.list').length > 0 ||
  308. ('.repository.commits').length > 0) {
  309. initFilterSearchDropdown('.choose.reference .dropdown');
  310. $('.reference.column').click(function () {
  311. $('.choose.reference .scrolling.menu').css('display', 'none');
  312. $('.choose.reference .text').removeClass('black');
  313. $($(this).data('target')).css('display', 'block');
  314. $(this).find('.text').addClass('black');
  315. return false;
  316. });
  317. }
  318. // Wiki
  319. if ($('.repository.wiki.view').length > 0) {
  320. initFilterSearchDropdown('.choose.page .dropdown');
  321. }
  322. // Options
  323. if ($('.repository.settings.options').length > 0) {
  324. $('#repo_name').keyup(function () {
  325. var $prompt = $('#repo-name-change-prompt');
  326. if ($(this).val().toString().toLowerCase() != $(this).data('repo-name').toString().toLowerCase()) {
  327. $prompt.show();
  328. } else {
  329. $prompt.hide();
  330. }
  331. });
  332. // Enable or select internal/external wiki system and issue tracker.
  333. $('.enable-system').change(function () {
  334. if (this.checked) {
  335. $($(this).data('target')).removeClass('disabled');
  336. } else {
  337. $($(this).data('target')).addClass('disabled');
  338. }
  339. });
  340. $('.enable-system-radio').change(function () {
  341. if (this.value == 'false') {
  342. $($(this).data('target')).addClass('disabled');
  343. } else if (this.value == 'true') {
  344. $($(this).data('target')).removeClass('disabled');
  345. }
  346. });
  347. }
  348. // Labels
  349. if ($('.repository.labels').length > 0) {
  350. // Create label
  351. var $newLabelPanel = $('.new-label.segment');
  352. $('.new-label.button').click(function () {
  353. $newLabelPanel.show();
  354. });
  355. $('.new-label.segment .cancel').click(function () {
  356. $newLabelPanel.hide();
  357. });
  358. $('.color-picker').each(function () {
  359. $(this).minicolors();
  360. });
  361. $('.precolors .color').click(function () {
  362. var color_hex = $(this).data('color-hex');
  363. $('.color-picker').val(color_hex);
  364. $('.minicolors-swatch-color').css("background-color", color_hex);
  365. });
  366. $('.edit-label-button').click(function () {
  367. $('#label-modal-id').val($(this).data('id'));
  368. $('.edit-label .new-label-input').val($(this).data('title'));
  369. $('.edit-label .color-picker').val($(this).data('color'));
  370. $('.minicolors-swatch-color').css("background-color", $(this).data('color'));
  371. $('.edit-label.modal').modal({
  372. onApprove: function () {
  373. $('.edit-label.form').submit();
  374. }
  375. }).modal('show');
  376. return false;
  377. });
  378. }
  379. // Milestones
  380. if ($('.repository.milestones').length > 0) {
  381. }
  382. if ($('.repository.new.milestone').length > 0) {
  383. var $datepicker = $('.milestone.datepicker');
  384. $datepicker.datetimepicker({
  385. lang: $datepicker.data('lang'),
  386. inline: true,
  387. timepicker: false,
  388. startDate: $datepicker.data('start-date'),
  389. formatDate: 'Y-m-d',
  390. onSelectDate: function (ct) {
  391. $('#deadline').val(ct.dateFormat('Y-m-d'));
  392. }
  393. });
  394. $('#clear-date').click(function () {
  395. $('#deadline').val('');
  396. return false;
  397. });
  398. }
  399. // Issues
  400. if ($('.repository.view.issue').length > 0) {
  401. // Edit issue title
  402. var $issueTitle = $('#issue-title');
  403. var $editInput = $('#edit-title-input input');
  404. var editTitleToggle = function () {
  405. $issueTitle.toggle();
  406. $('.not-in-edit').toggle();
  407. $('#edit-title-input').toggle();
  408. $('.in-edit').toggle();
  409. $editInput.focus();
  410. return false;
  411. };
  412. $('#edit-title').click(editTitleToggle);
  413. $('#cancel-edit-title').click(editTitleToggle);
  414. $('#save-edit-title').click(editTitleToggle).click(function () {
  415. if ($editInput.val().length == 0 ||
  416. $editInput.val() == $issueTitle.text()) {
  417. $editInput.val($issueTitle.text());
  418. return false;
  419. }
  420. $.post($(this).data('update-url'), {
  421. "_csrf": csrf,
  422. "title": $editInput.val()
  423. },
  424. function (data) {
  425. $editInput.val(data.title);
  426. $issueTitle.text(data.title);
  427. location.reload();
  428. });
  429. return false;
  430. });
  431. // Edit issue or comment content
  432. $('.edit-content').click(function () {
  433. var $segment = $(this).parent().parent().parent().next();
  434. var $editContentZone = $segment.find('.edit-content-zone');
  435. var $renderContent = $segment.find('.render-content');
  436. var $rawContent = $segment.find('.raw-content');
  437. var $textarea;
  438. // Setup new form
  439. if ($editContentZone.html().length == 0) {
  440. $editContentZone.html($('#edit-content-form').html());
  441. $textarea = $segment.find('textarea');
  442. // Give new write/preview data-tab name to distinguish from others
  443. var $editContentForm = $editContentZone.find('.ui.comment.form');
  444. var $tabMenu = $editContentForm.find('.tabular.menu');
  445. $tabMenu.attr('data-write', $editContentZone.data('write'));
  446. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  447. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  448. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  449. $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write'));
  450. $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview'));
  451. initCommentPreviewTab($editContentForm);
  452. $editContentZone.find('.cancel.button').click(function () {
  453. $renderContent.show();
  454. $editContentZone.hide();
  455. });
  456. $editContentZone.find('.save.button').click(function () {
  457. $renderContent.show();
  458. $editContentZone.hide();
  459. $.post($editContentZone.data('update-url'), {
  460. "_csrf": csrf,
  461. "content": $textarea.val(),
  462. "context": $editContentZone.data('context')
  463. },
  464. function (data) {
  465. if (data.length == 0) {
  466. $renderContent.html($('#no-content').html());
  467. } else {
  468. $renderContent.html(data.content);
  469. emojify.run($renderContent[0]);
  470. $('pre code', $renderContent[0]).each(function (i, block) {
  471. hljs.highlightBlock(block);
  472. });
  473. }
  474. });
  475. });
  476. } else {
  477. $textarea = $segment.find('textarea');
  478. }
  479. // Show write/preview tab and copy raw content as needed
  480. $editContentZone.show();
  481. $renderContent.hide();
  482. if ($textarea.val().length == 0) {
  483. $textarea.val($rawContent.text());
  484. }
  485. $textarea.focus();
  486. return false;
  487. });
  488. // Delete comment
  489. $('.delete-comment').click(function () {
  490. var $this = $(this);
  491. if (confirm($this.data('locale'))) {
  492. $.post($this.data('url'), {
  493. "_csrf": csrf
  494. }).success(function () {
  495. $('#' + $this.data('comment-id')).remove();
  496. });
  497. }
  498. return false;
  499. });
  500. // Change status
  501. var $statusButton = $('#status-button');
  502. $('#comment-form .edit_area').keyup(function () {
  503. if ($(this).val().length == 0) {
  504. $statusButton.text($statusButton.data('status'))
  505. } else {
  506. $statusButton.text($statusButton.data('status-and-comment'))
  507. }
  508. });
  509. $statusButton.click(function () {
  510. $('#status').val($statusButton.data('status-val'));
  511. $('#comment-form').submit();
  512. });
  513. }
  514. // Diff
  515. if ($('.repository.diff').length > 0) {
  516. var $counter = $('.diff-counter');
  517. if ($counter.length >= 1) {
  518. $counter.each(function (i, item) {
  519. var $item = $(item);
  520. var addLine = $item.find('span[data-line].add').data("line");
  521. var delLine = $item.find('span[data-line].del').data("line");
  522. var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  523. $item.find(".bar .add").css("width", addPercent + "%");
  524. });
  525. }
  526. }
  527. // Quick start and repository home
  528. $('#repo-clone-ssh').click(function () {
  529. $('.clone-url').text($(this).data('link'));
  530. $('#repo-clone-url').val($(this).data('link'));
  531. $(this).addClass('blue');
  532. $('#repo-clone-https').removeClass('blue');
  533. localStorage.setItem('repo-clone-protocol', 'ssh');
  534. });
  535. $('#repo-clone-https').click(function () {
  536. $('.clone-url').text($(this).data('link'));
  537. $('#repo-clone-url').val($(this).data('link'));
  538. $(this).addClass('blue');
  539. $('#repo-clone-ssh').removeClass('blue');
  540. localStorage.setItem('repo-clone-protocol', 'https');
  541. });
  542. $('#repo-clone-url').click(function () {
  543. $(this).select();
  544. });
  545. // Pull request
  546. if ($('.repository.compare.pull').length > 0) {
  547. initFilterSearchDropdown('.choose.branch .dropdown');
  548. }
  549. }
  550. function initProtectedBranch() {
  551. $('#protectedBranch').change(function () {
  552. var $this = $(this);
  553. $.post($this.data('url'), {
  554. "_csrf": csrf,
  555. "canPush": true,
  556. "branchName": $this.val(),
  557. },
  558. function (data) {
  559. if (data.redirect) {
  560. window.location.href = data.redirect;
  561. } else {
  562. location.reload();
  563. }
  564. }
  565. );
  566. });
  567. $('.rm').click(function () {
  568. var $this = $(this);
  569. $.post($this.data('url'), {
  570. "_csrf": csrf,
  571. "canPush": false,
  572. "branchName": $this.data('val'),
  573. },
  574. function (data) {
  575. if (data.redirect) {
  576. window.location.href = data.redirect;
  577. } else {
  578. location.reload();
  579. }
  580. }
  581. );
  582. });
  583. }
  584. function initRepositoryCollaboration() {
  585. console.log('initRepositoryCollaboration');
  586. // Change collaborator access mode
  587. $('.access-mode.menu .item').click(function () {
  588. var $menu = $(this).parent();
  589. $.post($menu.data('url'), {
  590. "_csrf": csrf,
  591. "uid": $menu.data('uid'),
  592. "mode": $(this).data('value')
  593. })
  594. });
  595. }
  596. function initTeamSettings() {
  597. // Change team access mode
  598. $('.organization.new.team input[name=permission]').change(function () {
  599. var val = $('input[name=permission]:checked', '.organization.new.team').val()
  600. if (val === 'admin') {
  601. $('.organization.new.team .team-units').hide();
  602. } else {
  603. $('.organization.new.team .team-units').show();
  604. }
  605. });
  606. }
  607. function initWikiForm() {
  608. var $editArea = $('.repository.wiki textarea#edit_area');
  609. if ($editArea.length > 0) {
  610. new SimpleMDE({
  611. autoDownloadFontAwesome: false,
  612. element: $editArea[0],
  613. forceSync: true,
  614. previewRender: function (plainText, preview) { // Async method
  615. setTimeout(function () {
  616. // FIXME: still send render request when return back to edit mode
  617. $.post($editArea.data('url'), {
  618. "_csrf": csrf,
  619. "mode": "gfm",
  620. "context": $editArea.data('context'),
  621. "text": plainText
  622. },
  623. function (data) {
  624. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  625. emojify.run($('.editor-preview')[0]);
  626. $('.editor-preview').autolink();
  627. }
  628. );
  629. }, 0);
  630. return "Loading...";
  631. },
  632. renderingConfig: {
  633. singleLineBreaks: false
  634. },
  635. indentWithTabs: false,
  636. tabSize: 4,
  637. spellChecker: false,
  638. toolbar: ["bold", "italic", "strikethrough", "|",
  639. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  640. "code", "quote", "|",
  641. "unordered-list", "ordered-list", "|",
  642. "link", "image", "table", "horizontal-rule", "|",
  643. "clean-block", "preview", "fullscreen"]
  644. })
  645. }
  646. }
  647. var simpleMDEditor;
  648. var codeMirrorEditor;
  649. // For IE
  650. String.prototype.endsWith = function (pattern) {
  651. var d = this.length - pattern.length;
  652. return d >= 0 && this.lastIndexOf(pattern) === d;
  653. };
  654. // Adding function to get the cursor position in a text field to jQuery object.
  655. (function ($, undefined) {
  656. $.fn.getCursorPosition = function () {
  657. var el = $(this).get(0);
  658. var pos = 0;
  659. if ('selectionStart' in el) {
  660. pos = el.selectionStart;
  661. } else if ('selection' in document) {
  662. el.focus();
  663. var Sel = document.selection.createRange();
  664. var SelLength = document.selection.createRange().text.length;
  665. Sel.moveStart('character', -el.value.length);
  666. pos = Sel.text.length - SelLength;
  667. }
  668. return pos;
  669. }
  670. })(jQuery);
  671. function setSimpleMDE($editArea) {
  672. if (codeMirrorEditor) {
  673. codeMirrorEditor.toTextArea();
  674. codeMirrorEditor = null;
  675. }
  676. if (simpleMDEditor) {
  677. return true;
  678. }
  679. simpleMDEditor = new SimpleMDE({
  680. autoDownloadFontAwesome: false,
  681. element: $editArea[0],
  682. forceSync: true,
  683. renderingConfig: {
  684. singleLineBreaks: false
  685. },
  686. indentWithTabs: false,
  687. tabSize: 4,
  688. spellChecker: false,
  689. previewRender: function (plainText, preview) { // Async method
  690. setTimeout(function () {
  691. // FIXME: still send render request when return back to edit mode
  692. $.post($editArea.data('url'), {
  693. "_csrf": csrf,
  694. "mode": "gfm",
  695. "context": $editArea.data('context'),
  696. "text": plainText
  697. },
  698. function (data) {
  699. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  700. emojify.run($('.editor-preview')[0]);
  701. }
  702. );
  703. }, 0);
  704. return "Loading...";
  705. },
  706. toolbar: ["bold", "italic", "strikethrough", "|",
  707. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  708. "code", "quote", "|",
  709. "unordered-list", "ordered-list", "|",
  710. "link", "image", "table", "horizontal-rule", "|",
  711. "clean-block", "preview", "fullscreen", "side-by-side"]
  712. });
  713. return true;
  714. }
  715. function setCodeMirror($editArea) {
  716. if (simpleMDEditor) {
  717. simpleMDEditor.toTextArea();
  718. simpleMDEditor = null;
  719. }
  720. if (codeMirrorEditor) {
  721. return true;
  722. }
  723. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  724. lineNumbers: true
  725. });
  726. codeMirrorEditor.on("change", function (cm, change) {
  727. $editArea.val(cm.getValue());
  728. });
  729. return true;
  730. }
  731. function initEditor() {
  732. $('.js-quick-pull-choice-option').change(function () {
  733. if ($(this).val() == 'commit-to-new-branch') {
  734. $('.quick-pull-branch-name').show();
  735. $('.quick-pull-branch-name input').prop('required',true);
  736. } else {
  737. $('.quick-pull-branch-name').hide();
  738. $('.quick-pull-branch-name input').prop('required',false);
  739. }
  740. });
  741. var $editFilename = $("#file-name");
  742. $editFilename.keyup(function (e) {
  743. var $section = $('.breadcrumb span.section');
  744. var $divider = $('.breadcrumb div.divider');
  745. if (e.keyCode == 8) {
  746. if ($(this).getCursorPosition() == 0) {
  747. if ($section.length > 0) {
  748. var value = $section.last().find('a').text();
  749. $(this).val(value + $(this).val());
  750. $(this)[0].setSelectionRange(value.length, value.length);
  751. $section.last().remove();
  752. $divider.last().remove();
  753. }
  754. }
  755. }
  756. if (e.keyCode == 191) {
  757. var parts = $(this).val().split('/');
  758. for (var i = 0; i < parts.length; ++i) {
  759. var value = parts[i];
  760. if (i < parts.length - 1) {
  761. if (value.length) {
  762. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  763. $('<div class="divider"> / </div>').insertBefore($(this));
  764. }
  765. }
  766. else {
  767. $(this).val(value);
  768. }
  769. $(this)[0].setSelectionRange(0, 0);
  770. }
  771. }
  772. var parts = [];
  773. $('.breadcrumb span.section').each(function (i, element) {
  774. element = $(element);
  775. if (element.find('a').length) {
  776. parts.push(element.find('a').text());
  777. } else {
  778. parts.push(element.text());
  779. }
  780. });
  781. if ($(this).val())
  782. parts.push($(this).val());
  783. $('#tree_path').val(parts.join('/'));
  784. }).trigger('keyup');
  785. var $editArea = $('.repository.editor textarea#edit_area');
  786. if (!$editArea.length)
  787. return;
  788. var markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  789. var lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  790. $editFilename.on("keyup", function (e) {
  791. var val = $editFilename.val(), m, mode, spec, extension, extWithDot, previewLink, dataUrl, apiCall;
  792. extension = extWithDot = "";
  793. if (m = /.+\.([^.]+)$/.exec(val)) {
  794. extension = m[1];
  795. extWithDot = "." + extension;
  796. }
  797. var info = CodeMirror.findModeByExtension(extension);
  798. previewLink = $('a[data-tab=preview]');
  799. if (info) {
  800. mode = info.mode;
  801. spec = info.mime;
  802. apiCall = mode;
  803. }
  804. else {
  805. apiCall = extension
  806. }
  807. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  808. dataUrl = previewLink.data('url');
  809. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  810. previewLink.show();
  811. }
  812. else {
  813. previewLink.hide();
  814. }
  815. // If this file is a Markdown extensions, we will load that editor and return
  816. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  817. if (setSimpleMDE($editArea)) {
  818. return;
  819. }
  820. }
  821. // Else we are going to use CodeMirror
  822. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  823. return;
  824. }
  825. if (mode) {
  826. codeMirrorEditor.setOption("mode", spec);
  827. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  828. }
  829. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  830. codeMirrorEditor.setOption("lineWrapping", true);
  831. }
  832. else {
  833. codeMirrorEditor.setOption("lineWrapping", false);
  834. }
  835. // get the filename without any folder
  836. var value = $editFilename.val();
  837. if (value.length === 0) {
  838. return;
  839. }
  840. value = value.split('/');
  841. value = value[value.length - 1];
  842. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  843. if (editorconfig.indent_style === 'tab') {
  844. codeMirrorEditor.setOption("indentWithTabs", true);
  845. codeMirrorEditor.setOption('extraKeys', {});
  846. } else {
  847. codeMirrorEditor.setOption("indentWithTabs", false);
  848. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  849. // - https://github.com/codemirror/CodeMirror/issues/988
  850. // - https://codemirror.net/doc/manual.html#keymaps
  851. codeMirrorEditor.setOption('extraKeys', {
  852. Tab: function(cm) {
  853. var spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  854. cm.replaceSelection(spaces);
  855. }
  856. });
  857. }
  858. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  859. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  860. });
  861. }).trigger('keyup');
  862. }
  863. function initOrganization() {
  864. if ($('.organization').length == 0) {
  865. return;
  866. }
  867. // Options
  868. if ($('.organization.settings.options').length > 0) {
  869. $('#org_name').keyup(function () {
  870. var $prompt = $('#org-name-change-prompt');
  871. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  872. $prompt.show();
  873. } else {
  874. $prompt.hide();
  875. }
  876. });
  877. }
  878. }
  879. function initUserSettings() {
  880. console.log('initUserSettings');
  881. // Options
  882. if ($('.user.settings.profile').length > 0) {
  883. $('#username').keyup(function () {
  884. var $prompt = $('#name-change-prompt');
  885. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  886. $prompt.show();
  887. } else {
  888. $prompt.hide();
  889. }
  890. });
  891. }
  892. }
  893. function initWebhook() {
  894. if ($('.new.webhook').length == 0) {
  895. return;
  896. }
  897. $('.events.checkbox input').change(function () {
  898. if ($(this).is(':checked')) {
  899. $('.events.fields').show();
  900. }
  901. });
  902. $('.non-events.checkbox input').change(function () {
  903. if ($(this).is(':checked')) {
  904. $('.events.fields').hide();
  905. }
  906. });
  907. // Test delivery
  908. $('#test-delivery').click(function () {
  909. var $this = $(this);
  910. $this.addClass('loading disabled');
  911. $.post($this.data('link'), {
  912. "_csrf": csrf
  913. }).done(
  914. setTimeout(function () {
  915. window.location.href = $this.data('redirect');
  916. }, 5000)
  917. )
  918. });
  919. }
  920. function initAdmin() {
  921. if ($('.admin').length == 0) {
  922. return;
  923. }
  924. // New user
  925. if ($('.admin.new.user').length > 0 ||
  926. $('.admin.edit.user').length > 0) {
  927. $('#login_type').change(function () {
  928. if ($(this).val().substring(0, 1) == '0') {
  929. $('#login_name').removeAttr('required');
  930. $('.non-local').hide();
  931. $('.local').show();
  932. $('#user_name').focus();
  933. if ($(this).data('password') == "required") {
  934. $('#password').attr('required', 'required');
  935. }
  936. } else {
  937. $('#login_name').attr('required', 'required');
  938. $('.non-local').show();
  939. $('.local').hide();
  940. $('#login_name').focus();
  941. $('#password').removeAttr('required');
  942. }
  943. });
  944. }
  945. function onSecurityProtocolChange() {
  946. if ($('#security_protocol').val() > 0) {
  947. $('.has-tls').show();
  948. } else {
  949. $('.has-tls').hide();
  950. }
  951. }
  952. function onOAuth2Change() {
  953. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  954. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  955. var provider = $('#oauth2_provider').val();
  956. switch (provider) {
  957. case 'github':
  958. case 'gitlab':
  959. $('.oauth2_use_custom_url').show();
  960. break;
  961. case 'openidConnect':
  962. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  963. $('.open_id_connect_auto_discovery_url').show();
  964. break;
  965. }
  966. onOAuth2UseCustomURLChange();
  967. }
  968. function onOAuth2UseCustomURLChange() {
  969. var provider = $('#oauth2_provider').val();
  970. $('.oauth2_use_custom_url_field').hide();
  971. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  972. if ($('#oauth2_use_custom_url').is(':checked')) {
  973. if (!$('#oauth2_token_url').val()) {
  974. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  975. }
  976. if (!$('#oauth2_auth_url').val()) {
  977. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  978. }
  979. if (!$('#oauth2_profile_url').val()) {
  980. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  981. }
  982. if (!$('#oauth2_email_url').val()) {
  983. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  984. }
  985. switch (provider) {
  986. case 'github':
  987. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  988. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  989. break;
  990. case 'gitlab':
  991. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  992. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  993. $('#oauth2_email_url').val('');
  994. break;
  995. }
  996. }
  997. }
  998. // New authentication
  999. if ($('.admin.new.authentication').length > 0) {
  1000. $('#auth_type').change(function () {
  1001. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls').hide();
  1002. $('.ldap input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required] .has-tls input[required]').removeAttr('required');
  1003. var authType = $(this).val();
  1004. switch (authType) {
  1005. case '2': // LDAP
  1006. $('.ldap').show();
  1007. $('.ldap div.required:not(.dldap) input').attr('required', 'required');
  1008. break;
  1009. case '3': // SMTP
  1010. $('.smtp').show();
  1011. $('.has-tls').show();
  1012. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1013. break;
  1014. case '4': // PAM
  1015. $('.pam').show();
  1016. $('.pam input').attr('required', 'required');
  1017. break;
  1018. case '5': // LDAP
  1019. $('.dldap').show();
  1020. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1021. break;
  1022. case '6': // OAuth2
  1023. $('.oauth2').show();
  1024. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1025. onOAuth2Change();
  1026. break;
  1027. }
  1028. if (authType == '2' || authType == '5') {
  1029. onSecurityProtocolChange()
  1030. }
  1031. });
  1032. $('#auth_type').change();
  1033. $('#security_protocol').change(onSecurityProtocolChange);
  1034. $('#oauth2_provider').change(onOAuth2Change);
  1035. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1036. }
  1037. // Edit authentication
  1038. if ($('.admin.edit.authentication').length > 0) {
  1039. var authType = $('#auth_type').val();
  1040. if (authType == '2' || authType == '5') {
  1041. $('#security_protocol').change(onSecurityProtocolChange);
  1042. } else if (authType == '6') {
  1043. $('#oauth2_provider').change(onOAuth2Change);
  1044. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1045. onOAuth2Change();
  1046. }
  1047. }
  1048. // Notice
  1049. if ($('.admin.notice')) {
  1050. var $detailModal = $('#detail-modal');
  1051. // Attach view detail modals
  1052. $('.view-detail').click(function () {
  1053. $detailModal.find('.content p').text($(this).data('content'));
  1054. $detailModal.modal('show');
  1055. return false;
  1056. });
  1057. // Select actions
  1058. var $checkboxes = $('.select.table .ui.checkbox');
  1059. $('.select.action').click(function () {
  1060. switch ($(this).data('action')) {
  1061. case 'select-all':
  1062. $checkboxes.checkbox('check');
  1063. break;
  1064. case 'deselect-all':
  1065. $checkboxes.checkbox('uncheck');
  1066. break;
  1067. case 'inverse':
  1068. $checkboxes.checkbox('toggle');
  1069. break;
  1070. }
  1071. });
  1072. $('#delete-selection').click(function () {
  1073. var $this = $(this);
  1074. $this.addClass("loading disabled");
  1075. var ids = [];
  1076. $checkboxes.each(function () {
  1077. if ($(this).checkbox('is checked')) {
  1078. ids.push($(this).data('id'));
  1079. }
  1080. });
  1081. $.post($this.data('link'), {
  1082. "_csrf": csrf,
  1083. "ids": ids
  1084. }).done(function () {
  1085. window.location.href = $this.data('redirect');
  1086. });
  1087. });
  1088. }
  1089. }
  1090. function buttonsClickOnEnter() {
  1091. $('.ui.button').keypress(function (e) {
  1092. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1093. $(this).click();
  1094. });
  1095. }
  1096. function hideWhenLostFocus(body, parent) {
  1097. $(document).click(function (e) {
  1098. var target = e.target;
  1099. if (!$(target).is(body) && !$(target).parents().is(parent)) {
  1100. $(body).hide();
  1101. }
  1102. });
  1103. }
  1104. function searchUsers() {
  1105. if (!$('#search-user-box .results').length) {
  1106. return;
  1107. }
  1108. var $searchUserBox = $('#search-user-box');
  1109. var $results = $searchUserBox.find('.results');
  1110. $searchUserBox.keyup(function () {
  1111. var $this = $(this);
  1112. var keyword = $this.find('input').val();
  1113. if (keyword.length < 2) {
  1114. $results.hide();
  1115. return;
  1116. }
  1117. $.ajax({
  1118. url: suburl + '/api/v1/users/search?q=' + keyword,
  1119. dataType: "json",
  1120. success: function (response) {
  1121. var notEmpty = function (str) {
  1122. return str && str.length > 0;
  1123. };
  1124. $results.html('');
  1125. if (response.ok && response.data.length) {
  1126. var html = '';
  1127. $.each(response.data, function (i, item) {
  1128. html += '<div class="item"><img class="ui avatar image" src="' + item.avatar_url + '"><span class="username">' + item.login + '</span>';
  1129. if (notEmpty(item.full_name)) {
  1130. html += ' (' + item.full_name + ')';
  1131. }
  1132. html += '</div>';
  1133. });
  1134. $results.html(html);
  1135. $this.find('.results .item').click(function () {
  1136. $this.find('input').val($(this).find('.username').text());
  1137. $results.hide();
  1138. });
  1139. $results.show();
  1140. } else {
  1141. $results.hide();
  1142. }
  1143. }
  1144. });
  1145. });
  1146. $searchUserBox.find('input').focus(function () {
  1147. $searchUserBox.keyup();
  1148. });
  1149. hideWhenLostFocus('#search-user-box .results', '#search-user-box');
  1150. }
  1151. // FIXME: merge common parts in two functions
  1152. function searchRepositories() {
  1153. if (!$('#search-repo-box .results').length) {
  1154. return;
  1155. }
  1156. var $searchRepoBox = $('#search-repo-box');
  1157. var $results = $searchRepoBox.find('.results');
  1158. $searchRepoBox.keyup(function () {
  1159. var $this = $(this);
  1160. var keyword = $this.find('input').val();
  1161. if (keyword.length < 2) {
  1162. $results.hide();
  1163. return;
  1164. }
  1165. $.ajax({
  1166. url: suburl + '/api/v1/repos/search?q=' + keyword + "&uid=" + $searchRepoBox.data('uid'),
  1167. dataType: "json",
  1168. success: function (response) {
  1169. var notEmpty = function (str) {
  1170. return str && str.length > 0;
  1171. };
  1172. $results.html('');
  1173. if (response.ok && response.data.length) {
  1174. var html = '';
  1175. $.each(response.data, function (i, item) {
  1176. html += '<div class="item"><i class="icon octicon octicon-repo"></i> <span class="fullname">' + item.full_name + '</span></div>';
  1177. });
  1178. $results.html(html);
  1179. $this.find('.results .item').click(function () {
  1180. $this.find('input').val($(this).find('.fullname').text().split("/")[1]);
  1181. $results.hide();
  1182. });
  1183. $results.show();
  1184. } else {
  1185. $results.hide();
  1186. }
  1187. }
  1188. });
  1189. });
  1190. $searchRepoBox.find('input').focus(function () {
  1191. $searchRepoBox.keyup();
  1192. });
  1193. hideWhenLostFocus('#search-repo-box .results', '#search-repo-box');
  1194. }
  1195. function initCodeView() {
  1196. if ($('.code-view .linenums').length > 0) {
  1197. $(document).on('click', '.lines-num span', function (e) {
  1198. var $select = $(this);
  1199. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1200. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1201. deSelect();
  1202. });
  1203. $(window).on('hashchange', function (e) {
  1204. var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
  1205. var $list = $('.code-view ol.linenums > li');
  1206. var $first;
  1207. if (m) {
  1208. $first = $list.filter('.' + m[1]);
  1209. selectRange($list, $first, $list.filter('.' + m[2]));
  1210. $("html, body").scrollTop($first.offset().top - 200);
  1211. return;
  1212. }
  1213. m = window.location.hash.match(/^#(L\d+)$/);
  1214. if (m) {
  1215. $first = $list.filter('.' + m[1]);
  1216. selectRange($list, $first);
  1217. $("html, body").scrollTop($first.offset().top - 200);
  1218. }
  1219. }).trigger('hashchange');
  1220. }
  1221. }
  1222. $(document).ready(function () {
  1223. csrf = $('meta[name=_csrf]').attr("content");
  1224. suburl = $('meta[name=_suburl]').attr("content");
  1225. // Show exact time
  1226. $('.time-since').each(function () {
  1227. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1228. });
  1229. // Semantic UI modules.
  1230. $('.dropdown').dropdown();
  1231. $('.jump.dropdown').dropdown({
  1232. action: 'hide',
  1233. onShow: function () {
  1234. $('.poping.up').popup('hide');
  1235. }
  1236. });
  1237. $('.slide.up.dropdown').dropdown({
  1238. transition: 'slide up'
  1239. });
  1240. $('.upward.dropdown').dropdown({
  1241. direction: 'upward'
  1242. });
  1243. $('.ui.accordion').accordion();
  1244. $('.ui.checkbox').checkbox();
  1245. $('.ui.progress').progress({
  1246. showActivity: false
  1247. });
  1248. $('.poping.up').popup();
  1249. $('.top.menu .poping.up').popup({
  1250. onShow: function () {
  1251. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1252. return false;
  1253. }
  1254. }
  1255. });
  1256. $('.tabular.menu .item').tab();
  1257. $('.tabable.menu .item').tab();
  1258. $('.toggle.button').click(function () {
  1259. $($(this).data('target')).slideToggle(100);
  1260. });
  1261. // make table <tr> element clickable like a link
  1262. $('tr[data-href]').click(function(event) {
  1263. window.location = $(this).data('href');
  1264. });
  1265. // Highlight JS
  1266. if (typeof hljs != 'undefined') {
  1267. hljs.initHighlightingOnLoad();
  1268. }
  1269. // Dropzone
  1270. var $dropzone = $('#dropzone');
  1271. if ($dropzone.length > 0) {
  1272. // Disable auto discover for all elements:
  1273. Dropzone.autoDiscover = false;
  1274. var filenameDict = {};
  1275. $dropzone.dropzone({
  1276. url: $dropzone.data('upload-url'),
  1277. headers: {"X-Csrf-Token": csrf},
  1278. maxFiles: $dropzone.data('max-file'),
  1279. maxFilesize: $dropzone.data('max-size'),
  1280. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1281. addRemoveLinks: true,
  1282. dictDefaultMessage: $dropzone.data('default-message'),
  1283. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1284. dictFileTooBig: $dropzone.data('file-too-big'),
  1285. dictRemoveFile: $dropzone.data('remove-file'),
  1286. init: function () {
  1287. this.on("success", function (file, data) {
  1288. filenameDict[file.name] = data.uuid;
  1289. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  1290. $('.files').append(input);
  1291. });
  1292. this.on("removedfile", function (file) {
  1293. if (file.name in filenameDict) {
  1294. $('#' + filenameDict[file.name]).remove();
  1295. }
  1296. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1297. $.post($dropzone.data('remove-url'), {
  1298. file: filenameDict[file.name],
  1299. _csrf: $dropzone.data('csrf')
  1300. });
  1301. }
  1302. })
  1303. }
  1304. });
  1305. }
  1306. // Emojify
  1307. emojify.setConfig({
  1308. img_dir: suburl + '/img/emoji',
  1309. ignore_emoticons: true
  1310. });
  1311. var hasEmoji = document.getElementsByClassName('has-emoji');
  1312. for (var i = 0; i < hasEmoji.length; i++) {
  1313. emojify.run(hasEmoji[i]);
  1314. }
  1315. // Clipboard JS
  1316. var clipboard = new Clipboard('.clipboard');
  1317. clipboard.on('success', function (e) {
  1318. e.clearSelection();
  1319. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1320. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  1321. $('#' + e.trigger.getAttribute('id')).popup('show');
  1322. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1323. });
  1324. clipboard.on('error', function (e) {
  1325. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1326. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  1327. $('#' + e.trigger.getAttribute('id')).popup('show');
  1328. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1329. });
  1330. // Helpers.
  1331. $('.delete-button').click(function () {
  1332. var $this = $(this);
  1333. var filter = "";
  1334. if ($this.attr("id")) {
  1335. filter += "#"+$this.attr("id")
  1336. }
  1337. $('.delete.modal'+filter).modal({
  1338. closable: false,
  1339. onApprove: function () {
  1340. if ($this.data('type') == "form") {
  1341. $($this.data('form')).submit();
  1342. return;
  1343. }
  1344. $.post($this.data('url'), {
  1345. "_csrf": csrf,
  1346. "id": $this.data("id")
  1347. }).done(function (data) {
  1348. window.location.href = data.redirect;
  1349. });
  1350. }
  1351. }).modal('show');
  1352. return false;
  1353. });
  1354. $('.show-panel.button').click(function () {
  1355. $($(this).data('panel')).show();
  1356. });
  1357. $('.show-modal.button').click(function () {
  1358. $($(this).data('modal')).modal('show');
  1359. });
  1360. $('.delete-post.button').click(function () {
  1361. var $this = $(this);
  1362. $.post($this.data('request-url'), {
  1363. "_csrf": csrf
  1364. }).done(function () {
  1365. window.location.href = $this.data('done-url');
  1366. });
  1367. });
  1368. // Set anchor.
  1369. $('.markdown').each(function () {
  1370. var headers = {};
  1371. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  1372. var node = $(this);
  1373. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  1374. var name = val;
  1375. if (headers[val] > 0) {
  1376. name = val + '-' + headers[val];
  1377. }
  1378. if (headers[val] == undefined) {
  1379. headers[val] = 1;
  1380. } else {
  1381. headers[val] += 1;
  1382. }
  1383. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  1384. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  1385. });
  1386. });
  1387. $('.markdown').autolink();
  1388. $('.issue-checkbox').click(function() {
  1389. var numChecked = $('.issue-checkbox').children('input:checked').length;
  1390. if (numChecked > 0) {
  1391. $('.issue-filters').hide();
  1392. $('.issue-actions').show();
  1393. } else {
  1394. $('.issue-filters').show();
  1395. $('.issue-actions').hide();
  1396. }
  1397. });
  1398. $('.issue-action').click(function () {
  1399. var action = this.dataset.action
  1400. var elementId = this.dataset.elementId
  1401. var issueIDs = $('.issue-checkbox').children('input:checked').map(function() {
  1402. return this.dataset.issueId;
  1403. }).get().join();
  1404. var url = this.dataset.url
  1405. updateIssuesMeta(url, action, issueIDs, elementId, function() {
  1406. location.reload();
  1407. });
  1408. });
  1409. buttonsClickOnEnter();
  1410. searchUsers();
  1411. searchRepositories();
  1412. initCommentForm();
  1413. initInstall();
  1414. initRepository();
  1415. initWikiForm();
  1416. initEditForm();
  1417. initEditor();
  1418. initOrganization();
  1419. initProtectedBranch();
  1420. initWebhook();
  1421. initAdmin();
  1422. initCodeView();
  1423. initVueApp();
  1424. initTeamSettings();
  1425. // Repo clone url.
  1426. if ($('#repo-clone-url').length > 0) {
  1427. switch (localStorage.getItem('repo-clone-protocol')) {
  1428. case 'ssh':
  1429. if ($('#repo-clone-ssh').click().length === 0) {
  1430. $('#repo-clone-https').click();
  1431. }
  1432. break;
  1433. default:
  1434. $('#repo-clone-https').click();
  1435. break;
  1436. }
  1437. }
  1438. var routes = {
  1439. 'div.user.settings': initUserSettings,
  1440. 'div.repository.settings.collaboration': initRepositoryCollaboration
  1441. };
  1442. var selector;
  1443. for (selector in routes) {
  1444. if ($(selector).length > 0) {
  1445. routes[selector]();
  1446. break;
  1447. }
  1448. }
  1449. });
  1450. function changeHash(hash) {
  1451. if (history.pushState) {
  1452. history.pushState(null, null, hash);
  1453. }
  1454. else {
  1455. location.hash = hash;
  1456. }
  1457. }
  1458. function deSelect() {
  1459. if (window.getSelection) {
  1460. window.getSelection().removeAllRanges();
  1461. } else {
  1462. document.selection.empty();
  1463. }
  1464. }
  1465. function selectRange($list, $select, $from) {
  1466. $list.removeClass('active');
  1467. if ($from) {
  1468. var a = parseInt($select.attr('rel').substr(1));
  1469. var b = parseInt($from.attr('rel').substr(1));
  1470. var c;
  1471. if (a != b) {
  1472. if (a > b) {
  1473. c = a;
  1474. a = b;
  1475. b = c;
  1476. }
  1477. var classes = [];
  1478. for (var i = a; i <= b; i++) {
  1479. classes.push('.L' + i);
  1480. }
  1481. $list.filter(classes.join(',')).addClass('active');
  1482. changeHash('#L' + a + '-' + 'L' + b);
  1483. return
  1484. }
  1485. }
  1486. $select.addClass('active');
  1487. changeHash('#' + $select.attr('rel'));
  1488. }
  1489. $(function () {
  1490. if ($('.user.signin').length > 0) return;
  1491. $('form').areYouSure();
  1492. // Parse SSH Key
  1493. $("#ssh-key-content").on('change paste keyup',function(){
  1494. var arrays = $(this).val().split(" ");
  1495. var $title = $("#ssh-key-title")
  1496. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  1497. $title.val(arrays[2]);
  1498. }
  1499. });
  1500. });
  1501. function initVueComponents(){
  1502. var vueDelimeters = ['${', '}'];
  1503. Vue.component('repo-search', {
  1504. delimiters: vueDelimeters,
  1505. template: '#repo-search-template',
  1506. props: {
  1507. searchLimit: {
  1508. type: Number,
  1509. default: 10
  1510. },
  1511. suburl: {
  1512. type: String,
  1513. required: true
  1514. },
  1515. uid: {
  1516. type: Number,
  1517. required: true
  1518. },
  1519. },
  1520. data: function() {
  1521. return {
  1522. tab: 'repos',
  1523. repos: [],
  1524. reposTotal: 0,
  1525. reposFilter: 'all',
  1526. searchQuery: '',
  1527. isLoading: false
  1528. }
  1529. },
  1530. mounted: function() {
  1531. this.searchRepos();
  1532. var self = this;
  1533. Vue.nextTick(function() {
  1534. self.$refs.search.focus();
  1535. });
  1536. },
  1537. methods: {
  1538. changeTab: function(t) {
  1539. this.tab = t;
  1540. },
  1541. changeReposFilter: function(filter) {
  1542. this.reposFilter = filter;
  1543. },
  1544. showRepo: function(repo, filter) {
  1545. switch (filter) {
  1546. case 'sources':
  1547. return repo.owner.id == this.uid && !repo.mirror && !repo.fork;
  1548. case 'forks':
  1549. return repo.owner.id == this.uid && !repo.mirror && repo.fork;
  1550. case 'mirrors':
  1551. return repo.mirror;
  1552. case 'collaborative':
  1553. return repo.owner.id != this.uid;
  1554. default:
  1555. return true;
  1556. }
  1557. },
  1558. searchRepos: function() {
  1559. var self = this;
  1560. this.isLoading = true;
  1561. var searchedQuery = this.searchQuery;
  1562. $.getJSON(this.searchURL(), function(result, textStatus, request) {
  1563. if (searchedQuery == self.searchQuery) {
  1564. self.repos = result.data;
  1565. if (searchedQuery == "") {
  1566. self.reposTotal = request.getResponseHeader('X-Total-Count');
  1567. }
  1568. }
  1569. }).always(function() {
  1570. if (searchedQuery == self.searchQuery) {
  1571. self.isLoading = false;
  1572. }
  1573. });
  1574. },
  1575. searchURL: function() {
  1576. return this.suburl + '/api/v1/repos/search?uid=' + this.uid + '&q=' + this.searchQuery + '&limit=' + this.searchLimit;
  1577. },
  1578. repoClass: function(repo) {
  1579. if (repo.fork) {
  1580. return 'octicon octicon-repo-forked';
  1581. } else if (repo.mirror) {
  1582. return 'octicon octicon-repo-clone';
  1583. } else if (repo.private) {
  1584. return 'octicon octicon-lock';
  1585. } else {
  1586. return 'octicon octicon-repo';
  1587. }
  1588. }
  1589. }
  1590. })
  1591. }
  1592. function initVueApp() {
  1593. var el = document.getElementById('app');
  1594. if (!el) {
  1595. return;
  1596. }
  1597. initVueComponents();
  1598. new Vue({
  1599. delimiters: ['${', '}'],
  1600. el: el,
  1601. data: {
  1602. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  1603. suburl: document.querySelector('meta[name=_suburl]').content,
  1604. uid: document.querySelector('meta[name=_context_uid]').content,
  1605. },
  1606. });
  1607. }