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 72KB

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