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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836
  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 insertAtCursor(field, value) {
  158. if (field.selectionStart || field.selectionStart === 0) {
  159. var startPos = field.selectionStart;
  160. var endPos = field.selectionEnd;
  161. field.value = field.value.substring(0, startPos)
  162. + value
  163. + field.value.substring(endPos, field.value.length);
  164. field.selectionStart = startPos + value.length;
  165. field.selectionEnd = startPos + value.length;
  166. } else {
  167. field.value += value;
  168. }
  169. }
  170. function replaceAndKeepCursor(field, oldval, newval) {
  171. if (field.selectionStart || field.selectionStart === 0) {
  172. var startPos = field.selectionStart;
  173. var endPos = field.selectionEnd;
  174. field.value = field.value.replace(oldval, newval);
  175. field.selectionStart = startPos + newval.length - oldval.length;
  176. field.selectionEnd = endPos + newval.length - oldval.length;
  177. } else {
  178. field.value = field.value.replace(oldval, newval);
  179. }
  180. }
  181. function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
  182. if (!pasteEvent.clipboardData) {
  183. return;
  184. }
  185. var items = pasteEvent.clipboardData.items;
  186. if (typeof(items) === "undefined") {
  187. return;
  188. }
  189. for (var i = 0; i < items.length; i++) {
  190. if (items[i].type.indexOf("image") === -1) continue;
  191. var blob = items[i].getAsFile();
  192. if (typeof(callback) === "function") {
  193. pasteEvent.preventDefault();
  194. pasteEvent.stopPropagation();
  195. callback(blob);
  196. }
  197. }
  198. }
  199. function uploadFile(file, callback) {
  200. var xhr = new XMLHttpRequest();
  201. xhr.onload = function() {
  202. if (xhr.status == 200) {
  203. callback(xhr.responseText);
  204. }
  205. };
  206. xhr.open("post", suburl + "/attachments", true);
  207. xhr.setRequestHeader("X-Csrf-Token", csrf);
  208. var formData = new FormData();
  209. formData.append('file', file, file.name);
  210. xhr.send(formData);
  211. }
  212. function initImagePaste(target) {
  213. target.each(function(i, field) {
  214. field.addEventListener('paste', function(event){
  215. retrieveImageFromClipboardAsBlob(event, function(img) {
  216. var name = img.name.substr(0, img.name.lastIndexOf('.'));
  217. insertAtCursor(field, '![' + name + ']()');
  218. uploadFile(img, function(res) {
  219. var data = JSON.parse(res);
  220. replaceAndKeepCursor(field, '![' + name + ']()', '![' + name + '](' + suburl + '/attachments/' + data.uuid + ')');
  221. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  222. $('.files').append(input);
  223. });
  224. });
  225. }, false);
  226. });
  227. }
  228. function initCommentForm() {
  229. if ($('.comment.form').length == 0) {
  230. return
  231. }
  232. initBranchSelector();
  233. initCommentPreviewTab($('.comment.form'));
  234. initImagePaste($('.comment.form textarea'));
  235. // Listsubmit
  236. function initListSubmits(selector, outerSelector) {
  237. var $list = $('.ui.' + outerSelector + '.list');
  238. var $noSelect = $list.find('.no-select');
  239. var $listMenu = $('.' + selector + ' .menu');
  240. var hasLabelUpdateAction = $listMenu.data('action') == 'update';
  241. $('.' + selector).dropdown('setting', 'onHide', function(){
  242. hasLabelUpdateAction = $listMenu.data('action') == 'update'; // Update the var
  243. if (hasLabelUpdateAction) {
  244. location.reload();
  245. }
  246. });
  247. $listMenu.find('.item:not(.no-select)').click(function () {
  248. // we don't need the action attribute when updating assignees
  249. if (selector == 'select-assignees-modify') {
  250. // UI magic. We need to do this here, otherwise it would destroy the functionality of
  251. // adding/removing labels
  252. if ($(this).hasClass('checked')) {
  253. $(this).removeClass('checked');
  254. $(this).find('.octicon').removeClass('octicon-check');
  255. } else {
  256. $(this).addClass('checked');
  257. $(this).find('.octicon').addClass('octicon-check');
  258. }
  259. updateIssuesMeta(
  260. $listMenu.data('update-url'),
  261. "",
  262. $listMenu.data('issue-id'),
  263. $(this).data('id')
  264. );
  265. $listMenu.data('action', 'update'); // Update to reload the page when we updated items
  266. return false;
  267. }
  268. if ($(this).hasClass('checked')) {
  269. $(this).removeClass('checked');
  270. $(this).find('.octicon').removeClass('octicon-check');
  271. if (hasLabelUpdateAction) {
  272. updateIssuesMeta(
  273. $listMenu.data('update-url'),
  274. "detach",
  275. $listMenu.data('issue-id'),
  276. $(this).data('id')
  277. );
  278. }
  279. } else {
  280. $(this).addClass('checked');
  281. $(this).find('.octicon').addClass('octicon-check');
  282. if (hasLabelUpdateAction) {
  283. updateIssuesMeta(
  284. $listMenu.data('update-url'),
  285. "attach",
  286. $listMenu.data('issue-id'),
  287. $(this).data('id')
  288. );
  289. }
  290. }
  291. var listIds = [];
  292. $(this).parent().find('.item').each(function () {
  293. if ($(this).hasClass('checked')) {
  294. listIds.push($(this).data('id'));
  295. $($(this).data('id-selector')).removeClass('hide');
  296. } else {
  297. $($(this).data('id-selector')).addClass('hide');
  298. }
  299. });
  300. if (listIds.length == 0) {
  301. $noSelect.removeClass('hide');
  302. } else {
  303. $noSelect.addClass('hide');
  304. }
  305. $($(this).parent().data('id')).val(listIds.join(","));
  306. return false;
  307. });
  308. $listMenu.find('.no-select.item').click(function () {
  309. if (hasLabelUpdateAction || selector == 'select-assignees-modify') {
  310. updateIssuesMeta(
  311. $listMenu.data('update-url'),
  312. "clear",
  313. $listMenu.data('issue-id'),
  314. ""
  315. );
  316. $listMenu.data('action', 'update'); // Update to reload the page when we updated items
  317. }
  318. $(this).parent().find('.item').each(function () {
  319. $(this).removeClass('checked');
  320. $(this).find('.octicon').removeClass('octicon-check');
  321. });
  322. $list.find('.item').each(function () {
  323. $(this).addClass('hide');
  324. });
  325. $noSelect.removeClass('hide');
  326. $($(this).parent().data('id')).val('');
  327. });
  328. }
  329. // Init labels and assignees
  330. initListSubmits('select-label', 'labels');
  331. initListSubmits('select-assignees', 'assignees');
  332. initListSubmits('select-assignees-modify', 'assignees');
  333. function selectItem(select_id, input_id) {
  334. var $menu = $(select_id + ' .menu');
  335. var $list = $('.ui' + select_id + '.list');
  336. var hasUpdateAction = $menu.data('action') == 'update';
  337. $menu.find('.item:not(.no-select)').click(function () {
  338. $(this).parent().find('.item').each(function () {
  339. $(this).removeClass('selected active')
  340. });
  341. $(this).addClass('selected active');
  342. if (hasUpdateAction) {
  343. updateIssuesMeta(
  344. $menu.data('update-url'),
  345. "",
  346. $menu.data('issue-id'),
  347. $(this).data('id'),
  348. function() { location.reload(); }
  349. );
  350. }
  351. switch (input_id) {
  352. case '#milestone_id':
  353. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  354. $(this).text() + '</a>');
  355. break;
  356. case '#assignee_id':
  357. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  358. '<img class="ui avatar image" src=' + $(this).data('avatar') + '>' +
  359. $(this).text() + '</a>');
  360. }
  361. $('.ui' + select_id + '.list .no-select').addClass('hide');
  362. $(input_id).val($(this).data('id'));
  363. });
  364. $menu.find('.no-select.item').click(function () {
  365. $(this).parent().find('.item:not(.no-select)').each(function () {
  366. $(this).removeClass('selected active')
  367. });
  368. if (hasUpdateAction) {
  369. updateIssuesMeta(
  370. $menu.data('update-url'),
  371. "",
  372. $menu.data('issue-id'),
  373. $(this).data('id'),
  374. function() { location.reload(); }
  375. );
  376. }
  377. $list.find('.selected').html('');
  378. $list.find('.no-select').removeClass('hide');
  379. $(input_id).val('');
  380. });
  381. }
  382. // Milestone and assignee
  383. selectItem('.select-milestone', '#milestone_id');
  384. selectItem('.select-assignee', '#assignee_id');
  385. }
  386. function initInstall() {
  387. if ($('.install').length == 0) {
  388. return;
  389. }
  390. if ($('#db_host').val()=="") {
  391. $('#db_host').val("127.0.0.1:3306");
  392. $('#db_user').val("gitea");
  393. $('#db_name').val("gitea");
  394. }
  395. // Database type change detection.
  396. $("#db_type").change(function () {
  397. var sqliteDefault = 'data/gitea.db';
  398. var tidbDefault = 'data/gitea_tidb';
  399. var dbType = $(this).val();
  400. if (dbType === "SQLite3" || dbType === "TiDB") {
  401. $('#sql_settings').hide();
  402. $('#pgsql_settings').hide();
  403. $('#sqlite_settings').show();
  404. if (dbType === "SQLite3" && $('#db_path').val() == tidbDefault) {
  405. $('#db_path').val(sqliteDefault);
  406. } else if (dbType === "TiDB" && $('#db_path').val() == sqliteDefault) {
  407. $('#db_path').val(tidbDefault);
  408. }
  409. return;
  410. }
  411. var dbDefaults = {
  412. "MySQL": "127.0.0.1:3306",
  413. "PostgreSQL": "127.0.0.1:5432",
  414. "MSSQL": "127.0.0.1:1433"
  415. };
  416. $('#sqlite_settings').hide();
  417. $('#sql_settings').show();
  418. $('#pgsql_settings').toggle(dbType === "PostgreSQL");
  419. $.each(dbDefaults, function(type, defaultHost) {
  420. if ($('#db_host').val() == defaultHost) {
  421. $('#db_host').val(dbDefaults[dbType]);
  422. return false;
  423. }
  424. });
  425. });
  426. // TODO: better handling of exclusive relations.
  427. $('#offline-mode input').change(function () {
  428. if ($(this).is(':checked')) {
  429. $('#disable-gravatar').checkbox('check');
  430. $('#federated-avatar-lookup').checkbox('uncheck');
  431. }
  432. });
  433. $('#disable-gravatar input').change(function () {
  434. if ($(this).is(':checked')) {
  435. $('#federated-avatar-lookup').checkbox('uncheck');
  436. } else {
  437. $('#offline-mode').checkbox('uncheck');
  438. }
  439. });
  440. $('#federated-avatar-lookup input').change(function () {
  441. if ($(this).is(':checked')) {
  442. $('#disable-gravatar').checkbox('uncheck');
  443. $('#offline-mode').checkbox('uncheck');
  444. }
  445. });
  446. $('#enable-openid-signin input').change(function () {
  447. if ($(this).is(':checked')) {
  448. if ( $('#disable-registration input').is(':checked') ) {
  449. } else {
  450. $('#enable-openid-signup').checkbox('check');
  451. }
  452. } else {
  453. $('#enable-openid-signup').checkbox('uncheck');
  454. }
  455. });
  456. $('#disable-registration input').change(function () {
  457. if ($(this).is(':checked')) {
  458. $('#enable-captcha').checkbox('uncheck');
  459. $('#enable-openid-signup').checkbox('uncheck');
  460. } else {
  461. $('#enable-openid-signup').checkbox('check');
  462. }
  463. });
  464. $('#enable-captcha input').change(function () {
  465. if ($(this).is(':checked')) {
  466. $('#disable-registration').checkbox('uncheck');
  467. }
  468. });
  469. }
  470. function initRepository() {
  471. if ($('.repository').length == 0) {
  472. return;
  473. }
  474. function initFilterSearchDropdown(selector) {
  475. var $dropdown = $(selector);
  476. $dropdown.dropdown({
  477. fullTextSearch: true,
  478. selectOnKeydown: false,
  479. onChange: function (text, value, $choice) {
  480. if ($choice.data('url')) {
  481. window.location.href = $choice.data('url');
  482. }
  483. },
  484. message: {noResults: $dropdown.data('no-results')}
  485. });
  486. }
  487. // File list and commits
  488. if ($('.repository.file.list').length > 0 ||
  489. ('.repository.commits').length > 0) {
  490. initFilterBranchTagDropdown('.choose.reference .dropdown');
  491. }
  492. // Wiki
  493. if ($('.repository.wiki.view').length > 0) {
  494. initFilterSearchDropdown('.choose.page .dropdown');
  495. }
  496. // Options
  497. if ($('.repository.settings.options').length > 0) {
  498. $('#repo_name').keyup(function () {
  499. var $prompt = $('#repo-name-change-prompt');
  500. if ($(this).val().toString().toLowerCase() != $(this).data('repo-name').toString().toLowerCase()) {
  501. $prompt.show();
  502. } else {
  503. $prompt.hide();
  504. }
  505. });
  506. // Enable or select internal/external wiki system and issue tracker.
  507. $('.enable-system').change(function () {
  508. if (this.checked) {
  509. $($(this).data('target')).removeClass('disabled');
  510. if (!$(this).data('context')) $($(this).data('context')).addClass('disabled');
  511. } else {
  512. $($(this).data('target')).addClass('disabled');
  513. if (!$(this).data('context')) $($(this).data('context')).removeClass('disabled');
  514. }
  515. });
  516. $('.enable-system-radio').change(function () {
  517. if (this.value == 'false') {
  518. $($(this).data('target')).addClass('disabled');
  519. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).removeClass('disabled');
  520. } else if (this.value == 'true') {
  521. $($(this).data('target')).removeClass('disabled');
  522. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).addClass('disabled');
  523. }
  524. });
  525. }
  526. // Labels
  527. if ($('.repository.labels').length > 0) {
  528. // Create label
  529. var $newLabelPanel = $('.new-label.segment');
  530. $('.new-label.button').click(function () {
  531. $newLabelPanel.show();
  532. });
  533. $('.new-label.segment .cancel').click(function () {
  534. $newLabelPanel.hide();
  535. });
  536. $('.color-picker').each(function () {
  537. $(this).minicolors();
  538. });
  539. $('.precolors .color').click(function () {
  540. var color_hex = $(this).data('color-hex');
  541. $('.color-picker').val(color_hex);
  542. $('.minicolors-swatch-color').css("background-color", color_hex);
  543. });
  544. $('.edit-label-button').click(function () {
  545. $('#label-modal-id').val($(this).data('id'));
  546. $('.edit-label .new-label-input').val($(this).data('title'));
  547. $('.edit-label .new-label-desc-input').val($(this).data('description'));
  548. $('.edit-label .color-picker').val($(this).data('color'));
  549. $('.minicolors-swatch-color').css("background-color", $(this).data('color'));
  550. $('.edit-label.modal').modal({
  551. onApprove: function () {
  552. $('.edit-label.form').submit();
  553. }
  554. }).modal('show');
  555. return false;
  556. });
  557. }
  558. // Milestones
  559. if ($('.repository.milestones').length > 0) {
  560. }
  561. if ($('.repository.new.milestone').length > 0) {
  562. var $datepicker = $('.milestone.datepicker');
  563. $datepicker.datetimepicker({
  564. lang: $datepicker.data('lang'),
  565. inline: true,
  566. timepicker: false,
  567. startDate: $datepicker.data('start-date'),
  568. formatDate: 'Y-m-d',
  569. onSelectDate: function (ct) {
  570. $('#deadline').val(ct.dateFormat('Y-m-d'));
  571. }
  572. });
  573. $('#clear-date').click(function () {
  574. $('#deadline').val('');
  575. return false;
  576. });
  577. }
  578. // Issues
  579. if ($('.repository.view.issue').length > 0) {
  580. // Edit issue title
  581. var $issueTitle = $('#issue-title');
  582. var $editInput = $('#edit-title-input input');
  583. var editTitleToggle = function () {
  584. $issueTitle.toggle();
  585. $('.not-in-edit').toggle();
  586. $('#edit-title-input').toggle();
  587. $('.in-edit').toggle();
  588. $editInput.focus();
  589. return false;
  590. };
  591. $('#edit-title').click(editTitleToggle);
  592. $('#cancel-edit-title').click(editTitleToggle);
  593. $('#save-edit-title').click(editTitleToggle).click(function () {
  594. if ($editInput.val().length == 0 ||
  595. $editInput.val() == $issueTitle.text()) {
  596. $editInput.val($issueTitle.text());
  597. return false;
  598. }
  599. $.post($(this).data('update-url'), {
  600. "_csrf": csrf,
  601. "title": $editInput.val()
  602. },
  603. function (data) {
  604. $editInput.val(data.title);
  605. $issueTitle.text(data.title);
  606. location.reload();
  607. });
  608. return false;
  609. });
  610. // Edit issue or comment content
  611. $('.edit-content').click(function () {
  612. var $segment = $(this).parent().parent().parent().next();
  613. var $editContentZone = $segment.find('.edit-content-zone');
  614. var $renderContent = $segment.find('.render-content');
  615. var $rawContent = $segment.find('.raw-content');
  616. var $textarea;
  617. // Setup new form
  618. if ($editContentZone.html().length == 0) {
  619. $editContentZone.html($('#edit-content-form').html());
  620. $textarea = $('#content');
  621. issuesTribute.attach($textarea.get());
  622. emojiTribute.attach($textarea.get());
  623. // Give new write/preview data-tab name to distinguish from others
  624. var $editContentForm = $editContentZone.find('.ui.comment.form');
  625. var $tabMenu = $editContentForm.find('.tabular.menu');
  626. $tabMenu.attr('data-write', $editContentZone.data('write'));
  627. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  628. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  629. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  630. $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write'));
  631. $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview'));
  632. initCommentPreviewTab($editContentForm);
  633. $editContentZone.find('.cancel.button').click(function () {
  634. $renderContent.show();
  635. $editContentZone.hide();
  636. });
  637. $editContentZone.find('.save.button').click(function () {
  638. $renderContent.show();
  639. $editContentZone.hide();
  640. $.post($editContentZone.data('update-url'), {
  641. "_csrf": csrf,
  642. "content": $textarea.val(),
  643. "context": $editContentZone.data('context')
  644. },
  645. function (data) {
  646. if (data.length == 0) {
  647. $renderContent.html($('#no-content').html());
  648. } else {
  649. $renderContent.html(data.content);
  650. emojify.run($renderContent[0]);
  651. $('pre code', $renderContent[0]).each(function (i, block) {
  652. hljs.highlightBlock(block);
  653. });
  654. }
  655. });
  656. });
  657. } else {
  658. $textarea = $segment.find('textarea');
  659. }
  660. // Show write/preview tab and copy raw content as needed
  661. $editContentZone.show();
  662. $renderContent.hide();
  663. if ($textarea.val().length == 0) {
  664. $textarea.val($rawContent.text());
  665. }
  666. $textarea.focus();
  667. return false;
  668. });
  669. // Delete comment
  670. $('.delete-comment').click(function () {
  671. var $this = $(this);
  672. if (confirm($this.data('locale'))) {
  673. $.post($this.data('url'), {
  674. "_csrf": csrf
  675. }).success(function () {
  676. $('#' + $this.data('comment-id')).remove();
  677. });
  678. }
  679. return false;
  680. });
  681. // Change status
  682. var $statusButton = $('#status-button');
  683. $('#comment-form .edit_area').keyup(function () {
  684. if ($(this).val().length == 0) {
  685. $statusButton.text($statusButton.data('status'))
  686. } else {
  687. $statusButton.text($statusButton.data('status-and-comment'))
  688. }
  689. });
  690. $statusButton.click(function () {
  691. $('#status').val($statusButton.data('status-val'));
  692. $('#comment-form').submit();
  693. });
  694. // Pull Request merge button
  695. var $mergeButton = $('.merge-button > button');
  696. $mergeButton.on('click', function(e) {
  697. e.preventDefault();
  698. $('.' + $(this).data('do') + '-fields').show();
  699. $(this).parent().hide();
  700. });
  701. $('.merge-button > .dropdown').dropdown({
  702. onChange: function (text, value, $choice) {
  703. if ($choice.data('do')) {
  704. $mergeButton.find('.button-text').text($choice.text());
  705. $mergeButton.data('do', $choice.data('do'));
  706. }
  707. }
  708. });
  709. $('.merge-cancel').on('click', function(e) {
  710. e.preventDefault();
  711. $(this).closest('.form').hide();
  712. $mergeButton.parent().show();
  713. });
  714. initReactionSelector();
  715. }
  716. // Diff
  717. if ($('.repository.diff').length > 0) {
  718. var $counter = $('.diff-counter');
  719. if ($counter.length >= 1) {
  720. $counter.each(function (i, item) {
  721. var $item = $(item);
  722. var addLine = $item.find('span[data-line].add').data("line");
  723. var delLine = $item.find('span[data-line].del').data("line");
  724. var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  725. $item.find(".bar .add").css("width", addPercent + "%");
  726. });
  727. }
  728. }
  729. // Quick start and repository home
  730. $('#repo-clone-ssh').click(function () {
  731. $('.clone-url').text($(this).data('link'));
  732. $('#repo-clone-url').val($(this).data('link'));
  733. $(this).addClass('blue');
  734. $('#repo-clone-https').removeClass('blue');
  735. localStorage.setItem('repo-clone-protocol', 'ssh');
  736. });
  737. $('#repo-clone-https').click(function () {
  738. $('.clone-url').text($(this).data('link'));
  739. $('#repo-clone-url').val($(this).data('link'));
  740. $(this).addClass('blue');
  741. $('#repo-clone-ssh').removeClass('blue');
  742. localStorage.setItem('repo-clone-protocol', 'https');
  743. });
  744. $('#repo-clone-url').click(function () {
  745. $(this).select();
  746. });
  747. // Pull request
  748. if ($('.repository.compare.pull').length > 0) {
  749. initFilterSearchDropdown('.choose.branch .dropdown');
  750. }
  751. // Branches
  752. if ($('.repository.settings.branches').length > 0) {
  753. initFilterSearchDropdown('.protected-branches .dropdown');
  754. $('.enable-protection, .enable-whitelist').change(function () {
  755. if (this.checked) {
  756. $($(this).data('target')).removeClass('disabled');
  757. } else {
  758. $($(this).data('target')).addClass('disabled');
  759. }
  760. });
  761. }
  762. }
  763. function initPullRequestReview() {
  764. $('.show-outdated').on('click', function (e) {
  765. e.preventDefault();
  766. var id = $(this).data('comment');
  767. $(this).addClass("hide");
  768. $("#code-comments-" + id).removeClass('hide');
  769. $("#code-preview-" + id).removeClass('hide');
  770. $("#hide-outdated-" + id).removeClass('hide');
  771. });
  772. $('.hide-outdated').on('click', function (e) {
  773. e.preventDefault();
  774. var id = $(this).data('comment');
  775. $(this).addClass("hide");
  776. $("#code-comments-" + id).addClass('hide');
  777. $("#code-preview-" + id).addClass('hide');
  778. $("#show-outdated-" + id).removeClass('hide');
  779. });
  780. $('button.comment-form-reply').on('click', function (e) {
  781. e.preventDefault();
  782. $(this).hide();
  783. var form = $(this).parent().find('.comment-form')
  784. form.removeClass('hide');
  785. assingMenuAttributes(form.find('.menu'));
  786. });
  787. // The following part is only for diff views
  788. if ($('.repository.pull.diff').length == 0) {
  789. return;
  790. }
  791. $('.diff-detail-box.ui.sticky').sticky();
  792. $('.btn-review').on('click', function(e) {
  793. e.preventDefault();
  794. $(this).closest('.dropdown').find('.menu').toggle('visible');
  795. }).closest('.dropdown').find('.link.close').on('click', function(e) {
  796. e.preventDefault();
  797. $(this).closest('.menu').toggle('visible');
  798. });
  799. $('.code-view .lines-code,.code-view .lines-num')
  800. .on('mouseenter', function() {
  801. var parent = $(this).closest('td');
  802. $(this).closest('tr').addClass(
  803. parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old')
  804. ? 'focus-lines-old' : 'focus-lines-new'
  805. );
  806. })
  807. .on('mouseleave', function() {
  808. $(this).closest('tr').removeClass('focus-lines-new focus-lines-old');
  809. });
  810. $('.add-code-comment').on('click', function(e) {
  811. e.preventDefault();
  812. var isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  813. var side = $(this).data('side');
  814. var idx = $(this).data('idx');
  815. var path = $(this).data('path');
  816. var form = $('#pull_review_add_comment').html();
  817. var tr = $(this).closest('tr');
  818. var ntr = tr.next();
  819. if (!ntr.hasClass('add-comment')) {
  820. ntr = $('<tr class="add-comment">'
  821. + (isSplit ? '<td class="lines-num"></td><td class="add-comment-left"></td><td class="lines-num"></td><td class="add-comment-right"></td>'
  822. : '<td class="lines-num"></td><td class="lines-num"></td><td class="add-comment-left add-comment-right"></td>')
  823. + '</tr>');
  824. tr.after(ntr);
  825. }
  826. var td = ntr.find('.add-comment-' + side);
  827. var commentCloud = td.find('.comment-code-cloud');
  828. if (commentCloud.length === 0) {
  829. td.html(form);
  830. commentCloud = td.find('.comment-code-cloud');
  831. assingMenuAttributes(commentCloud.find('.menu'));
  832. td.find("input[name='line']").val(idx);
  833. td.find("input[name='side']").val(side === "left" ? "previous":"proposed");
  834. td.find("input[name='path']").val(path);
  835. }
  836. commentCloud.find('textarea').focus();
  837. });
  838. }
  839. function assingMenuAttributes(menu) {
  840. var id = Math.floor(Math.random() * Math.floor(1000000));
  841. menu.attr('data-write', menu.attr('data-write') + id);
  842. menu.attr('data-preview', menu.attr('data-preview') + id);
  843. menu.find('.item').each(function(i, item) {
  844. $(item).attr('data-tab', $(item).attr('data-tab') + id);
  845. });
  846. menu.parent().find("*[data-tab='write']").attr('data-tab', 'write' + id);
  847. menu.parent().find("*[data-tab='preview']").attr('data-tab', 'preview' + id);
  848. initCommentPreviewTab(menu.parent(".form"));
  849. return id;
  850. }
  851. function initRepositoryCollaboration() {
  852. // Change collaborator access mode
  853. $('.access-mode.menu .item').click(function () {
  854. var $menu = $(this).parent();
  855. $.post($menu.data('url'), {
  856. "_csrf": csrf,
  857. "uid": $menu.data('uid'),
  858. "mode": $(this).data('value')
  859. })
  860. });
  861. }
  862. function initTeamSettings() {
  863. // Change team access mode
  864. $('.organization.new.team input[name=permission]').change(function () {
  865. var val = $('input[name=permission]:checked', '.organization.new.team').val()
  866. if (val === 'admin') {
  867. $('.organization.new.team .team-units').hide();
  868. } else {
  869. $('.organization.new.team .team-units').show();
  870. }
  871. });
  872. }
  873. function initWikiForm() {
  874. var $editArea = $('.repository.wiki textarea#edit_area');
  875. if ($editArea.length > 0) {
  876. var simplemde = new SimpleMDE({
  877. autoDownloadFontAwesome: false,
  878. element: $editArea[0],
  879. forceSync: true,
  880. previewRender: function (plainText, preview) { // Async method
  881. setTimeout(function () {
  882. // FIXME: still send render request when return back to edit mode
  883. $.post($editArea.data('url'), {
  884. "_csrf": csrf,
  885. "mode": "gfm",
  886. "context": $editArea.data('context'),
  887. "text": plainText
  888. },
  889. function (data) {
  890. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  891. emojify.run($('.editor-preview')[0]);
  892. }
  893. );
  894. }, 0);
  895. return "Loading...";
  896. },
  897. renderingConfig: {
  898. singleLineBreaks: false
  899. },
  900. indentWithTabs: false,
  901. tabSize: 4,
  902. spellChecker: false,
  903. toolbar: ["bold", "italic", "strikethrough", "|",
  904. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  905. "code", "quote", "|",
  906. "unordered-list", "ordered-list", "|",
  907. "link", "image", "table", "horizontal-rule", "|",
  908. "clean-block", "preview", "fullscreen"]
  909. })
  910. $(simplemde.codemirror.getInputField()).addClass("js-quick-submit");
  911. }
  912. }
  913. var simpleMDEditor;
  914. var codeMirrorEditor;
  915. // For IE
  916. String.prototype.endsWith = function (pattern) {
  917. var d = this.length - pattern.length;
  918. return d >= 0 && this.lastIndexOf(pattern) === d;
  919. };
  920. // Adding function to get the cursor position in a text field to jQuery object.
  921. (function ($, undefined) {
  922. $.fn.getCursorPosition = function () {
  923. var el = $(this).get(0);
  924. var pos = 0;
  925. if ('selectionStart' in el) {
  926. pos = el.selectionStart;
  927. } else if ('selection' in document) {
  928. el.focus();
  929. var Sel = document.selection.createRange();
  930. var SelLength = document.selection.createRange().text.length;
  931. Sel.moveStart('character', -el.value.length);
  932. pos = Sel.text.length - SelLength;
  933. }
  934. return pos;
  935. }
  936. })(jQuery);
  937. function setSimpleMDE($editArea) {
  938. if (codeMirrorEditor) {
  939. codeMirrorEditor.toTextArea();
  940. codeMirrorEditor = null;
  941. }
  942. if (simpleMDEditor) {
  943. return true;
  944. }
  945. simpleMDEditor = new SimpleMDE({
  946. autoDownloadFontAwesome: false,
  947. element: $editArea[0],
  948. forceSync: true,
  949. renderingConfig: {
  950. singleLineBreaks: false
  951. },
  952. indentWithTabs: false,
  953. tabSize: 4,
  954. spellChecker: false,
  955. previewRender: function (plainText, preview) { // Async method
  956. setTimeout(function () {
  957. // FIXME: still send render request when return back to edit mode
  958. $.post($editArea.data('url'), {
  959. "_csrf": csrf,
  960. "mode": "gfm",
  961. "context": $editArea.data('context'),
  962. "text": plainText
  963. },
  964. function (data) {
  965. preview.innerHTML = '<div class="markdown">' + data + '</div>';
  966. emojify.run($('.editor-preview')[0]);
  967. }
  968. );
  969. }, 0);
  970. return "Loading...";
  971. },
  972. toolbar: ["bold", "italic", "strikethrough", "|",
  973. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  974. "code", "quote", "|",
  975. "unordered-list", "ordered-list", "|",
  976. "link", "image", "table", "horizontal-rule", "|",
  977. "clean-block", "preview", "fullscreen", "side-by-side"]
  978. });
  979. return true;
  980. }
  981. function setCodeMirror($editArea) {
  982. if (simpleMDEditor) {
  983. simpleMDEditor.toTextArea();
  984. simpleMDEditor = null;
  985. }
  986. if (codeMirrorEditor) {
  987. return true;
  988. }
  989. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  990. lineNumbers: true
  991. });
  992. codeMirrorEditor.on("change", function (cm, change) {
  993. $editArea.val(cm.getValue());
  994. });
  995. return true;
  996. }
  997. function initEditor() {
  998. $('.js-quick-pull-choice-option').change(function () {
  999. if ($(this).val() == 'commit-to-new-branch') {
  1000. $('.quick-pull-branch-name').show();
  1001. $('.quick-pull-branch-name input').prop('required',true);
  1002. } else {
  1003. $('.quick-pull-branch-name').hide();
  1004. $('.quick-pull-branch-name input').prop('required',false);
  1005. }
  1006. });
  1007. var $editFilename = $("#file-name");
  1008. $editFilename.keyup(function (e) {
  1009. var $section = $('.breadcrumb span.section');
  1010. var $divider = $('.breadcrumb div.divider');
  1011. if (e.keyCode == 8) {
  1012. if ($(this).getCursorPosition() == 0) {
  1013. if ($section.length > 0) {
  1014. var value = $section.last().find('a').text();
  1015. $(this).val(value + $(this).val());
  1016. $(this)[0].setSelectionRange(value.length, value.length);
  1017. $section.last().remove();
  1018. $divider.last().remove();
  1019. }
  1020. }
  1021. }
  1022. if (e.keyCode == 191) {
  1023. var parts = $(this).val().split('/');
  1024. for (var i = 0; i < parts.length; ++i) {
  1025. var value = parts[i];
  1026. if (i < parts.length - 1) {
  1027. if (value.length) {
  1028. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  1029. $('<div class="divider"> / </div>').insertBefore($(this));
  1030. }
  1031. }
  1032. else {
  1033. $(this).val(value);
  1034. }
  1035. $(this)[0].setSelectionRange(0, 0);
  1036. }
  1037. }
  1038. var parts = [];
  1039. $('.breadcrumb span.section').each(function (i, element) {
  1040. element = $(element);
  1041. if (element.find('a').length) {
  1042. parts.push(element.find('a').text());
  1043. } else {
  1044. parts.push(element.text());
  1045. }
  1046. });
  1047. if ($(this).val())
  1048. parts.push($(this).val());
  1049. $('#tree_path').val(parts.join('/'));
  1050. }).trigger('keyup');
  1051. var $editArea = $('.repository.editor textarea#edit_area');
  1052. if (!$editArea.length)
  1053. return;
  1054. var markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  1055. var lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  1056. $editFilename.on("keyup", function (e) {
  1057. var val = $editFilename.val(), m, mode, spec, extension, extWithDot, previewLink, dataUrl, apiCall;
  1058. extension = extWithDot = "";
  1059. if (m = /.+\.([^.]+)$/.exec(val)) {
  1060. extension = m[1];
  1061. extWithDot = "." + extension;
  1062. }
  1063. var info = CodeMirror.findModeByExtension(extension);
  1064. previewLink = $('a[data-tab=preview]');
  1065. if (info) {
  1066. mode = info.mode;
  1067. spec = info.mime;
  1068. apiCall = mode;
  1069. }
  1070. else {
  1071. apiCall = extension
  1072. }
  1073. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  1074. dataUrl = previewLink.data('url');
  1075. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  1076. previewLink.show();
  1077. }
  1078. else {
  1079. previewLink.hide();
  1080. }
  1081. // If this file is a Markdown extensions, we will load that editor and return
  1082. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  1083. if (setSimpleMDE($editArea)) {
  1084. return;
  1085. }
  1086. }
  1087. // Else we are going to use CodeMirror
  1088. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  1089. return;
  1090. }
  1091. if (mode) {
  1092. codeMirrorEditor.setOption("mode", spec);
  1093. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  1094. }
  1095. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  1096. codeMirrorEditor.setOption("lineWrapping", true);
  1097. }
  1098. else {
  1099. codeMirrorEditor.setOption("lineWrapping", false);
  1100. }
  1101. // get the filename without any folder
  1102. var value = $editFilename.val();
  1103. if (value.length === 0) {
  1104. return;
  1105. }
  1106. value = value.split('/');
  1107. value = value[value.length - 1];
  1108. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  1109. if (editorconfig.indent_style === 'tab') {
  1110. codeMirrorEditor.setOption("indentWithTabs", true);
  1111. codeMirrorEditor.setOption('extraKeys', {});
  1112. } else {
  1113. codeMirrorEditor.setOption("indentWithTabs", false);
  1114. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  1115. // - https://github.com/codemirror/CodeMirror/issues/988
  1116. // - https://codemirror.net/doc/manual.html#keymaps
  1117. codeMirrorEditor.setOption('extraKeys', {
  1118. Tab: function(cm) {
  1119. var spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  1120. cm.replaceSelection(spaces);
  1121. }
  1122. });
  1123. }
  1124. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  1125. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  1126. });
  1127. }).trigger('keyup');
  1128. }
  1129. function initOrganization() {
  1130. if ($('.organization').length == 0) {
  1131. return;
  1132. }
  1133. // Options
  1134. if ($('.organization.settings.options').length > 0) {
  1135. $('#org_name').keyup(function () {
  1136. var $prompt = $('#org-name-change-prompt');
  1137. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  1138. $prompt.show();
  1139. } else {
  1140. $prompt.hide();
  1141. }
  1142. });
  1143. }
  1144. }
  1145. function initUserSettings() {
  1146. // Options
  1147. if ($('.user.settings.profile').length > 0) {
  1148. $('#username').keyup(function () {
  1149. var $prompt = $('#name-change-prompt');
  1150. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1151. $prompt.show();
  1152. } else {
  1153. $prompt.hide();
  1154. }
  1155. });
  1156. }
  1157. }
  1158. function initWebhook() {
  1159. if ($('.new.webhook').length == 0) {
  1160. return;
  1161. }
  1162. $('.events.checkbox input').change(function () {
  1163. if ($(this).is(':checked')) {
  1164. $('.events.fields').show();
  1165. }
  1166. });
  1167. $('.non-events.checkbox input').change(function () {
  1168. if ($(this).is(':checked')) {
  1169. $('.events.fields').hide();
  1170. }
  1171. });
  1172. // Test delivery
  1173. $('#test-delivery').click(function () {
  1174. var $this = $(this);
  1175. $this.addClass('loading disabled');
  1176. $.post($this.data('link'), {
  1177. "_csrf": csrf
  1178. }).done(
  1179. setTimeout(function () {
  1180. window.location.href = $this.data('redirect');
  1181. }, 5000)
  1182. )
  1183. });
  1184. }
  1185. function initAdmin() {
  1186. if ($('.admin').length == 0) {
  1187. return;
  1188. }
  1189. // New user
  1190. if ($('.admin.new.user').length > 0 ||
  1191. $('.admin.edit.user').length > 0) {
  1192. $('#login_type').change(function () {
  1193. if ($(this).val().substring(0, 1) == '0') {
  1194. $('#login_name').removeAttr('required');
  1195. $('.non-local').hide();
  1196. $('.local').show();
  1197. $('#user_name').focus();
  1198. if ($(this).data('password') == "required") {
  1199. $('#password').attr('required', 'required');
  1200. }
  1201. } else {
  1202. $('#login_name').attr('required', 'required');
  1203. $('.non-local').show();
  1204. $('.local').hide();
  1205. $('#login_name').focus();
  1206. $('#password').removeAttr('required');
  1207. }
  1208. });
  1209. }
  1210. function onSecurityProtocolChange() {
  1211. if ($('#security_protocol').val() > 0) {
  1212. $('.has-tls').show();
  1213. } else {
  1214. $('.has-tls').hide();
  1215. }
  1216. }
  1217. function onUsePagedSearchChange() {
  1218. if ($('#use_paged_search').prop('checked')) {
  1219. $('.search-page-size').show()
  1220. .find('input').attr('required', 'required');
  1221. } else {
  1222. $('.search-page-size').hide()
  1223. .find('input').removeAttr('required');
  1224. }
  1225. }
  1226. function onOAuth2Change() {
  1227. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1228. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1229. var provider = $('#oauth2_provider').val();
  1230. switch (provider) {
  1231. case 'github':
  1232. case 'gitlab':
  1233. $('.oauth2_use_custom_url').show();
  1234. break;
  1235. case 'openidConnect':
  1236. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1237. $('.open_id_connect_auto_discovery_url').show();
  1238. break;
  1239. }
  1240. onOAuth2UseCustomURLChange();
  1241. }
  1242. function onOAuth2UseCustomURLChange() {
  1243. var provider = $('#oauth2_provider').val();
  1244. $('.oauth2_use_custom_url_field').hide();
  1245. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1246. if ($('#oauth2_use_custom_url').is(':checked')) {
  1247. if (!$('#oauth2_token_url').val()) {
  1248. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  1249. }
  1250. if (!$('#oauth2_auth_url').val()) {
  1251. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  1252. }
  1253. if (!$('#oauth2_profile_url').val()) {
  1254. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  1255. }
  1256. if (!$('#oauth2_email_url').val()) {
  1257. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  1258. }
  1259. switch (provider) {
  1260. case 'github':
  1261. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1262. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1263. break;
  1264. case 'gitlab':
  1265. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1266. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1267. $('#oauth2_email_url').val('');
  1268. break;
  1269. }
  1270. }
  1271. }
  1272. // New authentication
  1273. if ($('.admin.new.authentication').length > 0) {
  1274. $('#auth_type').change(function () {
  1275. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls .search-page-size').hide();
  1276. $('.ldap input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required]').removeAttr('required');
  1277. var authType = $(this).val();
  1278. switch (authType) {
  1279. case '2': // LDAP
  1280. $('.ldap').show();
  1281. $('.ldap div.required:not(.dldap) input').attr('required', 'required');
  1282. break;
  1283. case '3': // SMTP
  1284. $('.smtp').show();
  1285. $('.has-tls').show();
  1286. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1287. break;
  1288. case '4': // PAM
  1289. $('.pam').show();
  1290. $('.pam input').attr('required', 'required');
  1291. break;
  1292. case '5': // LDAP
  1293. $('.dldap').show();
  1294. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1295. break;
  1296. case '6': // OAuth2
  1297. $('.oauth2').show();
  1298. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1299. onOAuth2Change();
  1300. break;
  1301. }
  1302. if (authType == '2' || authType == '5') {
  1303. onSecurityProtocolChange()
  1304. }
  1305. if (authType == '2') {
  1306. onUsePagedSearchChange();
  1307. }
  1308. });
  1309. $('#auth_type').change();
  1310. $('#security_protocol').change(onSecurityProtocolChange);
  1311. $('#use_paged_search').change(onUsePagedSearchChange);
  1312. $('#oauth2_provider').change(onOAuth2Change);
  1313. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1314. }
  1315. // Edit authentication
  1316. if ($('.admin.edit.authentication').length > 0) {
  1317. var authType = $('#auth_type').val();
  1318. if (authType == '2' || authType == '5') {
  1319. $('#security_protocol').change(onSecurityProtocolChange);
  1320. if (authType == '2') {
  1321. $('#use_paged_search').change(onUsePagedSearchChange);
  1322. }
  1323. } else if (authType == '6') {
  1324. $('#oauth2_provider').change(onOAuth2Change);
  1325. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1326. onOAuth2Change();
  1327. }
  1328. }
  1329. // Notice
  1330. if ($('.admin.notice')) {
  1331. var $detailModal = $('#detail-modal');
  1332. // Attach view detail modals
  1333. $('.view-detail').click(function () {
  1334. $detailModal.find('.content p').text($(this).data('content'));
  1335. $detailModal.modal('show');
  1336. return false;
  1337. });
  1338. // Select actions
  1339. var $checkboxes = $('.select.table .ui.checkbox');
  1340. $('.select.action').click(function () {
  1341. switch ($(this).data('action')) {
  1342. case 'select-all':
  1343. $checkboxes.checkbox('check');
  1344. break;
  1345. case 'deselect-all':
  1346. $checkboxes.checkbox('uncheck');
  1347. break;
  1348. case 'inverse':
  1349. $checkboxes.checkbox('toggle');
  1350. break;
  1351. }
  1352. });
  1353. $('#delete-selection').click(function () {
  1354. var $this = $(this);
  1355. $this.addClass("loading disabled");
  1356. var ids = [];
  1357. $checkboxes.each(function () {
  1358. if ($(this).checkbox('is checked')) {
  1359. ids.push($(this).data('id'));
  1360. }
  1361. });
  1362. $.post($this.data('link'), {
  1363. "_csrf": csrf,
  1364. "ids": ids
  1365. }).done(function () {
  1366. window.location.href = $this.data('redirect');
  1367. });
  1368. });
  1369. }
  1370. }
  1371. function buttonsClickOnEnter() {
  1372. $('.ui.button').keypress(function (e) {
  1373. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1374. $(this).click();
  1375. });
  1376. }
  1377. function hideWhenLostFocus(body, parent) {
  1378. $(document).click(function (e) {
  1379. var target = e.target;
  1380. if (!$(target).is(body) && !$(target).parents().is(parent)) {
  1381. $(body).hide();
  1382. }
  1383. });
  1384. }
  1385. function searchUsers() {
  1386. var $searchUserBox = $('#search-user-box');
  1387. $searchUserBox.search({
  1388. minCharacters: 2,
  1389. apiSettings: {
  1390. url: suburl + '/api/v1/users/search?q={query}',
  1391. onResponse: function(response) {
  1392. var items = [];
  1393. $.each(response.data, function (i, item) {
  1394. var title = item.login;
  1395. if (item.full_name && item.full_name.length > 0) {
  1396. title += ' (' + item.full_name + ')';
  1397. }
  1398. items.push({
  1399. title: title,
  1400. image: item.avatar_url
  1401. })
  1402. });
  1403. return { results: items }
  1404. }
  1405. },
  1406. searchFields: ['login', 'full_name'],
  1407. showNoResults: false
  1408. });
  1409. }
  1410. function searchRepositories() {
  1411. var $searchRepoBox = $('#search-repo-box');
  1412. $searchRepoBox.search({
  1413. minCharacters: 2,
  1414. apiSettings: {
  1415. url: suburl + '/api/v1/repos/search?q={query}&uid=' + $searchRepoBox.data('uid'),
  1416. onResponse: function(response) {
  1417. var items = [];
  1418. $.each(response.data, function (i, item) {
  1419. items.push({
  1420. title: item.full_name.split("/")[1],
  1421. description: item.full_name
  1422. })
  1423. });
  1424. return { results: items }
  1425. }
  1426. },
  1427. searchFields: ['full_name'],
  1428. showNoResults: false
  1429. });
  1430. }
  1431. function initCodeView() {
  1432. if ($('.code-view .linenums').length > 0) {
  1433. $(document).on('click', '.lines-num span', function (e) {
  1434. var $select = $(this);
  1435. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1436. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1437. deSelect();
  1438. });
  1439. $(window).on('hashchange', function (e) {
  1440. var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
  1441. var $list = $('.code-view ol.linenums > li');
  1442. var $first;
  1443. if (m) {
  1444. $first = $list.filter('.' + m[1]);
  1445. selectRange($list, $first, $list.filter('.' + m[2]));
  1446. $("html, body").scrollTop($first.offset().top - 200);
  1447. return;
  1448. }
  1449. m = window.location.hash.match(/^#(L\d+)$/);
  1450. if (m) {
  1451. $first = $list.filter('.' + m[1]);
  1452. selectRange($list, $first);
  1453. $("html, body").scrollTop($first.offset().top - 200);
  1454. }
  1455. }).trigger('hashchange');
  1456. }
  1457. }
  1458. function initU2FAuth() {
  1459. if($('#wait-for-key').length === 0) {
  1460. return
  1461. }
  1462. u2fApi.ensureSupport()
  1463. .then(function () {
  1464. $.getJSON(suburl + '/user/u2f/challenge').success(function(req) {
  1465. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1466. .then(u2fSigned)
  1467. .catch(function (err) {
  1468. if(err === undefined) {
  1469. u2fError(1);
  1470. return
  1471. }
  1472. u2fError(err.metaData.code);
  1473. });
  1474. });
  1475. }).catch(function () {
  1476. // Fallback in case browser do not support U2F
  1477. window.location.href = suburl + "/user/two_factor"
  1478. })
  1479. }
  1480. function u2fSigned(resp) {
  1481. $.ajax({
  1482. url: suburl + '/user/u2f/sign',
  1483. type: "POST",
  1484. headers: {"X-Csrf-Token": csrf},
  1485. data: JSON.stringify(resp),
  1486. contentType: "application/json; charset=utf-8",
  1487. }).done(function(res){
  1488. window.location.replace(res);
  1489. }).fail(function (xhr, textStatus) {
  1490. u2fError(1);
  1491. });
  1492. }
  1493. function u2fRegistered(resp) {
  1494. if (checkError(resp)) {
  1495. return;
  1496. }
  1497. $.ajax({
  1498. url: suburl + '/user/settings/security/u2f/register',
  1499. type: "POST",
  1500. headers: {"X-Csrf-Token": csrf},
  1501. data: JSON.stringify(resp),
  1502. contentType: "application/json; charset=utf-8",
  1503. success: function(){
  1504. window.location.reload();
  1505. },
  1506. fail: function (xhr, textStatus) {
  1507. u2fError(1);
  1508. }
  1509. });
  1510. }
  1511. function checkError(resp) {
  1512. if (!('errorCode' in resp)) {
  1513. return false;
  1514. }
  1515. if (resp.errorCode === 0) {
  1516. return false;
  1517. }
  1518. u2fError(resp.errorCode);
  1519. return true;
  1520. }
  1521. function u2fError(errorType) {
  1522. var u2fErrors = {
  1523. 'browser': $('#unsupported-browser'),
  1524. 1: $('#u2f-error-1'),
  1525. 2: $('#u2f-error-2'),
  1526. 3: $('#u2f-error-3'),
  1527. 4: $('#u2f-error-4'),
  1528. 5: $('.u2f-error-5')
  1529. };
  1530. u2fErrors[errorType].removeClass('hide');
  1531. for(var type in u2fErrors){
  1532. if(type != errorType){
  1533. u2fErrors[type].addClass('hide');
  1534. }
  1535. }
  1536. $('#u2f-error').modal('show');
  1537. }
  1538. function initU2FRegister() {
  1539. $('#register-device').modal({allowMultiple: false});
  1540. $('#u2f-error').modal({allowMultiple: false});
  1541. $('#register-security-key').on('click', function(e) {
  1542. e.preventDefault();
  1543. u2fApi.ensureSupport()
  1544. .then(u2fRegisterRequest)
  1545. .catch(function() {
  1546. u2fError('browser');
  1547. })
  1548. })
  1549. }
  1550. function u2fRegisterRequest() {
  1551. $.post(suburl + "/user/settings/security/u2f/request_register", {
  1552. "_csrf": csrf,
  1553. "name": $('#nickname').val()
  1554. }).success(function(req) {
  1555. $("#nickname").closest("div.field").removeClass("error");
  1556. $('#register-device').modal('show');
  1557. if(req.registeredKeys === null) {
  1558. req.registeredKeys = []
  1559. }
  1560. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1561. .then(u2fRegistered)
  1562. .catch(function (reason) {
  1563. if(reason === undefined) {
  1564. u2fError(1);
  1565. return
  1566. }
  1567. u2fError(reason.metaData.code);
  1568. });
  1569. }).fail(function(xhr, status, error) {
  1570. if(xhr.status === 409) {
  1571. $("#nickname").closest("div.field").addClass("error");
  1572. }
  1573. });
  1574. }
  1575. function initWipTitle() {
  1576. $(".title_wip_desc > a").click(function (e) {
  1577. e.preventDefault();
  1578. var $issueTitle = $("#issue_title");
  1579. $issueTitle.focus();
  1580. var value = $issueTitle.val().trim().toUpperCase();
  1581. for (var i in wipPrefixes) {
  1582. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1583. return;
  1584. }
  1585. }
  1586. $issueTitle.val(wipPrefixes[0] + " " + $issueTitle.val());
  1587. });
  1588. }
  1589. $(document).ready(function () {
  1590. csrf = $('meta[name=_csrf]').attr("content");
  1591. suburl = $('meta[name=_suburl]').attr("content");
  1592. // Show exact time
  1593. $('.time-since').each(function () {
  1594. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1595. });
  1596. // Semantic UI modules.
  1597. $('.dropdown:not(.custom)').dropdown();
  1598. $('.jump.dropdown').dropdown({
  1599. action: 'hide',
  1600. onShow: function () {
  1601. $('.poping.up').popup('hide');
  1602. }
  1603. });
  1604. $('.slide.up.dropdown').dropdown({
  1605. transition: 'slide up'
  1606. });
  1607. $('.upward.dropdown').dropdown({
  1608. direction: 'upward'
  1609. });
  1610. $('.ui.accordion').accordion();
  1611. $('.ui.checkbox').checkbox();
  1612. $('.ui.progress').progress({
  1613. showActivity: false
  1614. });
  1615. $('.poping.up').popup();
  1616. $('.top.menu .poping.up').popup({
  1617. onShow: function () {
  1618. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1619. return false;
  1620. }
  1621. }
  1622. });
  1623. $('.tabular.menu .item').tab();
  1624. $('.tabable.menu .item').tab();
  1625. $('.toggle.button').click(function () {
  1626. $($(this).data('target')).slideToggle(100);
  1627. });
  1628. // make table <tr> element clickable like a link
  1629. $('tr[data-href]').click(function(event) {
  1630. window.location = $(this).data('href');
  1631. });
  1632. // Highlight JS
  1633. if (typeof hljs != 'undefined') {
  1634. hljs.initHighlightingOnLoad();
  1635. }
  1636. // Dropzone
  1637. var $dropzone = $('#dropzone');
  1638. if ($dropzone.length > 0) {
  1639. // Disable auto discover for all elements:
  1640. Dropzone.autoDiscover = false;
  1641. var filenameDict = {};
  1642. $dropzone.dropzone({
  1643. url: $dropzone.data('upload-url'),
  1644. headers: {"X-Csrf-Token": csrf},
  1645. maxFiles: $dropzone.data('max-file'),
  1646. maxFilesize: $dropzone.data('max-size'),
  1647. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1648. addRemoveLinks: true,
  1649. dictDefaultMessage: $dropzone.data('default-message'),
  1650. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1651. dictFileTooBig: $dropzone.data('file-too-big'),
  1652. dictRemoveFile: $dropzone.data('remove-file'),
  1653. init: function () {
  1654. this.on("success", function (file, data) {
  1655. filenameDict[file.name] = data.uuid;
  1656. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  1657. $('.files').append(input);
  1658. });
  1659. this.on("removedfile", function (file) {
  1660. if (file.name in filenameDict) {
  1661. $('#' + filenameDict[file.name]).remove();
  1662. }
  1663. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1664. $.post($dropzone.data('remove-url'), {
  1665. file: filenameDict[file.name],
  1666. _csrf: $dropzone.data('csrf')
  1667. });
  1668. }
  1669. })
  1670. }
  1671. });
  1672. }
  1673. // Emojify
  1674. emojify.setConfig({
  1675. img_dir: suburl + '/vendor/plugins/emojify/images',
  1676. ignore_emoticons: true
  1677. });
  1678. var hasEmoji = document.getElementsByClassName('has-emoji');
  1679. for (var i = 0; i < hasEmoji.length; i++) {
  1680. emojify.run(hasEmoji[i]);
  1681. for (var j = 0; j < hasEmoji[i].childNodes.length; j++) {
  1682. if (hasEmoji[i].childNodes[j].nodeName === "A") {
  1683. emojify.run(hasEmoji[i].childNodes[j])
  1684. }
  1685. }
  1686. }
  1687. // Clipboard JS
  1688. var clipboard = new Clipboard('.clipboard');
  1689. clipboard.on('success', function (e) {
  1690. e.clearSelection();
  1691. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1692. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  1693. $('#' + e.trigger.getAttribute('id')).popup('show');
  1694. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1695. });
  1696. clipboard.on('error', function (e) {
  1697. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1698. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  1699. $('#' + e.trigger.getAttribute('id')).popup('show');
  1700. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1701. });
  1702. // Helpers.
  1703. $('.delete-button').click(showDeletePopup);
  1704. $('.delete-branch-button').click(showDeletePopup);
  1705. $('.undo-button').click(function() {
  1706. var $this = $(this);
  1707. $.post($this.data('url'), {
  1708. "_csrf": csrf,
  1709. "id": $this.data("id")
  1710. }).done(function(data) {
  1711. window.location.href = data.redirect;
  1712. });
  1713. });
  1714. $('.show-panel.button').click(function () {
  1715. $($(this).data('panel')).show();
  1716. });
  1717. $('.show-modal.button').click(function () {
  1718. $($(this).data('modal')).modal('show');
  1719. });
  1720. $('.delete-post.button').click(function () {
  1721. var $this = $(this);
  1722. $.post($this.data('request-url'), {
  1723. "_csrf": csrf
  1724. }).done(function () {
  1725. window.location.href = $this.data('done-url');
  1726. });
  1727. });
  1728. // Set anchor.
  1729. $('.markdown').each(function () {
  1730. var headers = {};
  1731. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  1732. var node = $(this);
  1733. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  1734. var name = val;
  1735. if (headers[val] > 0) {
  1736. name = val + '-' + headers[val];
  1737. }
  1738. if (headers[val] == undefined) {
  1739. headers[val] = 1;
  1740. } else {
  1741. headers[val] += 1;
  1742. }
  1743. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  1744. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  1745. });
  1746. });
  1747. $('.issue-checkbox').click(function() {
  1748. var numChecked = $('.issue-checkbox').children('input:checked').length;
  1749. if (numChecked > 0) {
  1750. $('#issue-filters').hide();
  1751. $('#issue-actions').show();
  1752. } else {
  1753. $('#issue-filters').show();
  1754. $('#issue-actions').hide();
  1755. }
  1756. });
  1757. $('.issue-action').click(function () {
  1758. var action = this.dataset.action
  1759. var elementId = this.dataset.elementId
  1760. var issueIDs = $('.issue-checkbox').children('input:checked').map(function() {
  1761. return this.dataset.issueId;
  1762. }).get().join();
  1763. var url = this.dataset.url
  1764. updateIssuesMeta(url, action, issueIDs, elementId, function() {
  1765. location.reload();
  1766. });
  1767. });
  1768. buttonsClickOnEnter();
  1769. searchUsers();
  1770. searchRepositories();
  1771. initCommentForm();
  1772. initInstall();
  1773. initRepository();
  1774. initWikiForm();
  1775. initEditForm();
  1776. initEditor();
  1777. initOrganization();
  1778. initWebhook();
  1779. initAdmin();
  1780. initCodeView();
  1781. initVueApp();
  1782. initTeamSettings();
  1783. initCtrlEnterSubmit();
  1784. initNavbarContentToggle();
  1785. initTopicbar();
  1786. initU2FAuth();
  1787. initU2FRegister();
  1788. initIssueList();
  1789. initWipTitle();
  1790. initPullRequestReview();
  1791. // Repo clone url.
  1792. if ($('#repo-clone-url').length > 0) {
  1793. switch (localStorage.getItem('repo-clone-protocol')) {
  1794. case 'ssh':
  1795. if ($('#repo-clone-ssh').click().length === 0) {
  1796. $('#repo-clone-https').click();
  1797. }
  1798. break;
  1799. default:
  1800. $('#repo-clone-https').click();
  1801. break;
  1802. }
  1803. }
  1804. var routes = {
  1805. 'div.user.settings': initUserSettings,
  1806. 'div.repository.settings.collaboration': initRepositoryCollaboration
  1807. };
  1808. var selector;
  1809. for (selector in routes) {
  1810. if ($(selector).length > 0) {
  1811. routes[selector]();
  1812. break;
  1813. }
  1814. }
  1815. });
  1816. function changeHash(hash) {
  1817. if (history.pushState) {
  1818. history.pushState(null, null, hash);
  1819. }
  1820. else {
  1821. location.hash = hash;
  1822. }
  1823. }
  1824. function deSelect() {
  1825. if (window.getSelection) {
  1826. window.getSelection().removeAllRanges();
  1827. } else {
  1828. document.selection.empty();
  1829. }
  1830. }
  1831. function selectRange($list, $select, $from) {
  1832. $list.removeClass('active');
  1833. if ($from) {
  1834. var a = parseInt($select.attr('rel').substr(1));
  1835. var b = parseInt($from.attr('rel').substr(1));
  1836. var c;
  1837. if (a != b) {
  1838. if (a > b) {
  1839. c = a;
  1840. a = b;
  1841. b = c;
  1842. }
  1843. var classes = [];
  1844. for (var i = a; i <= b; i++) {
  1845. classes.push('.L' + i);
  1846. }
  1847. $list.filter(classes.join(',')).addClass('active');
  1848. changeHash('#L' + a + '-' + 'L' + b);
  1849. return
  1850. }
  1851. }
  1852. $select.addClass('active');
  1853. changeHash('#' + $select.attr('rel'));
  1854. }
  1855. $(function () {
  1856. // Warn users that try to leave a page after entering data into a form.
  1857. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  1858. if ($('.user.signin').length === 0) {
  1859. $('form:not(.ignore-dirty)').areYouSure();
  1860. }
  1861. // Parse SSH Key
  1862. $("#ssh-key-content").on('change paste keyup',function(){
  1863. var arrays = $(this).val().split(" ");
  1864. var $title = $("#ssh-key-title")
  1865. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  1866. $title.val(arrays[2]);
  1867. }
  1868. });
  1869. });
  1870. function showDeletePopup() {
  1871. var $this = $(this);
  1872. var filter = "";
  1873. if ($this.attr("id")) {
  1874. filter += "#" + $this.attr("id")
  1875. }
  1876. var dialog = $('.delete.modal' + filter);
  1877. dialog.find('.repo-name').text($this.data('repo-name'));
  1878. dialog.modal({
  1879. closable: false,
  1880. onApprove: function() {
  1881. if ($this.data('type') == "form") {
  1882. $($this.data('form')).submit();
  1883. return;
  1884. }
  1885. $.post($this.data('url'), {
  1886. "_csrf": csrf,
  1887. "id": $this.data("id")
  1888. }).done(function(data) {
  1889. window.location.href = data.redirect;
  1890. });
  1891. }
  1892. }).modal('show');
  1893. return false;
  1894. }
  1895. function initVueComponents(){
  1896. var vueDelimeters = ['${', '}'];
  1897. Vue.component('repo-search', {
  1898. delimiters: vueDelimeters,
  1899. props: {
  1900. searchLimit: {
  1901. type: Number,
  1902. default: 10
  1903. },
  1904. suburl: {
  1905. type: String,
  1906. required: true
  1907. },
  1908. uid: {
  1909. type: Number,
  1910. required: true
  1911. },
  1912. organizations: {
  1913. type: Array,
  1914. default: []
  1915. },
  1916. isOrganization: {
  1917. type: Boolean,
  1918. default: true
  1919. },
  1920. canCreateOrganization: {
  1921. type: Boolean,
  1922. default: false
  1923. },
  1924. organizationsTotalCount: {
  1925. type: Number,
  1926. default: 0
  1927. },
  1928. moreReposLink: {
  1929. type: String,
  1930. default: ''
  1931. }
  1932. },
  1933. data: function() {
  1934. return {
  1935. tab: 'repos',
  1936. repos: [],
  1937. reposTotalCount: 0,
  1938. reposFilter: 'all',
  1939. searchQuery: '',
  1940. isLoading: false,
  1941. repoTypes: {
  1942. 'all': {
  1943. count: 0,
  1944. searchMode: '',
  1945. },
  1946. 'forks': {
  1947. count: 0,
  1948. searchMode: 'fork',
  1949. },
  1950. 'mirrors': {
  1951. count: 0,
  1952. searchMode: 'mirror',
  1953. },
  1954. 'sources': {
  1955. count: 0,
  1956. searchMode: 'source',
  1957. },
  1958. 'collaborative': {
  1959. count: 0,
  1960. searchMode: 'collaborative',
  1961. },
  1962. }
  1963. }
  1964. },
  1965. computed: {
  1966. showMoreReposLink: function() {
  1967. return this.repos.length > 0 && this.repos.length < this.repoTypes[this.reposFilter].count;
  1968. },
  1969. searchURL: function() {
  1970. 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' : '');
  1971. },
  1972. repoTypeCount: function() {
  1973. return this.repoTypes[this.reposFilter].count;
  1974. }
  1975. },
  1976. mounted: function() {
  1977. this.searchRepos(this.reposFilter);
  1978. var self = this;
  1979. Vue.nextTick(function() {
  1980. self.$refs.search.focus();
  1981. });
  1982. },
  1983. methods: {
  1984. changeTab: function(t) {
  1985. this.tab = t;
  1986. },
  1987. changeReposFilter: function(filter) {
  1988. this.reposFilter = filter;
  1989. this.repos = [];
  1990. this.repoTypes[filter].count = 0;
  1991. this.searchRepos(filter);
  1992. },
  1993. showRepo: function(repo, filter) {
  1994. switch (filter) {
  1995. case 'sources':
  1996. return repo.owner.id == this.uid && !repo.mirror && !repo.fork;
  1997. case 'forks':
  1998. return repo.owner.id == this.uid && !repo.mirror && repo.fork;
  1999. case 'mirrors':
  2000. return repo.mirror;
  2001. case 'collaborative':
  2002. return repo.owner.id != this.uid && !repo.mirror;
  2003. default:
  2004. return true;
  2005. }
  2006. },
  2007. searchRepos: function(reposFilter) {
  2008. var self = this;
  2009. this.isLoading = true;
  2010. var searchedMode = this.repoTypes[reposFilter].searchMode;
  2011. var searchedURL = this.searchURL;
  2012. var searchedQuery = this.searchQuery;
  2013. $.getJSON(searchedURL, function(result, textStatus, request) {
  2014. if (searchedURL == self.searchURL) {
  2015. self.repos = result.data;
  2016. var count = request.getResponseHeader('X-Total-Count');
  2017. if (searchedQuery === '' && searchedMode === '') {
  2018. self.reposTotalCount = count;
  2019. }
  2020. self.repoTypes[reposFilter].count = count;
  2021. }
  2022. }).always(function() {
  2023. if (searchedURL == self.searchURL) {
  2024. self.isLoading = false;
  2025. }
  2026. });
  2027. },
  2028. repoClass: function(repo) {
  2029. if (repo.fork) {
  2030. return 'octicon octicon-repo-forked';
  2031. } else if (repo.mirror) {
  2032. return 'octicon octicon-repo-clone';
  2033. } else if (repo.private) {
  2034. return 'octicon octicon-lock';
  2035. } else {
  2036. return 'octicon octicon-repo';
  2037. }
  2038. }
  2039. }
  2040. })
  2041. }
  2042. function initCtrlEnterSubmit() {
  2043. $(".js-quick-submit").keydown(function(e) {
  2044. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
  2045. $(this).closest("form").submit();
  2046. }
  2047. });
  2048. }
  2049. function initVueApp() {
  2050. var el = document.getElementById('app');
  2051. if (!el) {
  2052. return;
  2053. }
  2054. initVueComponents();
  2055. new Vue({
  2056. delimiters: ['${', '}'],
  2057. el: el,
  2058. data: {
  2059. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  2060. suburl: document.querySelector('meta[name=_suburl]').content,
  2061. uid: document.querySelector('meta[name=_context_uid]').content,
  2062. },
  2063. });
  2064. }
  2065. function timeAddManual() {
  2066. $('.mini.modal')
  2067. .modal({
  2068. duration: 200,
  2069. onApprove: function() {
  2070. $('#add_time_manual_form').submit();
  2071. }
  2072. }).modal('show')
  2073. ;
  2074. }
  2075. function toggleStopwatch() {
  2076. $("#toggle_stopwatch_form").submit();
  2077. }
  2078. function cancelStopwatch() {
  2079. $("#cancel_stopwatch_form").submit();
  2080. }
  2081. function initHeatmap(appElementId, heatmapUser, locale) {
  2082. var el = document.getElementById(appElementId);
  2083. if (!el) {
  2084. return;
  2085. }
  2086. locale = locale || {};
  2087. locale.contributions = locale.contributions || 'contributions';
  2088. locale.no_contributions = locale.no_contributions || 'No contributions';
  2089. var vueDelimeters = ['${', '}'];
  2090. Vue.component('activity-heatmap', {
  2091. delimiters: vueDelimeters,
  2092. props: {
  2093. user: {
  2094. type: String,
  2095. required: true
  2096. },
  2097. suburl: {
  2098. type: String,
  2099. required: true
  2100. },
  2101. locale: {
  2102. type: Object,
  2103. required: true
  2104. }
  2105. },
  2106. data: function () {
  2107. return {
  2108. isLoading: true,
  2109. colorRange: [],
  2110. endDate: null,
  2111. values: []
  2112. };
  2113. },
  2114. mounted: function() {
  2115. this.colorRange = [
  2116. this.getColor(0),
  2117. this.getColor(1),
  2118. this.getColor(2),
  2119. this.getColor(3),
  2120. this.getColor(4),
  2121. this.getColor(5)
  2122. ];
  2123. console.log(this.colorRange);
  2124. this.endDate = new Date();
  2125. this.loadHeatmap(this.user);
  2126. },
  2127. methods: {
  2128. loadHeatmap: function(userName) {
  2129. var self = this;
  2130. $.get(this.suburl + '/api/v1/users/' + userName + '/heatmap', function(chartRawData) {
  2131. var chartData = [];
  2132. for (var i = 0; i < chartRawData.length; i++) {
  2133. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2134. }
  2135. self.values = chartData;
  2136. self.isLoading = false;
  2137. });
  2138. },
  2139. getColor: function(idx) {
  2140. var el = document.createElement('div');
  2141. el.className = 'heatmap-color-' + idx;
  2142. document.body.appendChild(el);
  2143. var color = getComputedStyle(el).backgroundColor;
  2144. document.body.removeChild(el);
  2145. return color;
  2146. }
  2147. },
  2148. template: '<div><div v-show="isLoading"><slot name="loading"></slot></div><calendar-heatmap v-show="!isLoading" :locale="locale" :no-data-text="locale.no_contributions" :tooltip-unit="locale.contributions" :end-date="endDate" :values="values" :range-color="colorRange" />'
  2149. });
  2150. new Vue({
  2151. delimiters: vueDelimeters,
  2152. el: el,
  2153. data: {
  2154. suburl: document.querySelector('meta[name=_suburl]').content,
  2155. heatmapUser: heatmapUser,
  2156. locale: locale
  2157. },
  2158. });
  2159. }
  2160. function initFilterBranchTagDropdown(selector) {
  2161. $(selector).each(function() {
  2162. var $dropdown = $(this);
  2163. var $data = $dropdown.find('.data');
  2164. var data = {
  2165. items: [],
  2166. mode: $data.data('mode'),
  2167. searchTerm: '',
  2168. noResults: '',
  2169. canCreateBranch: false,
  2170. menuVisible: false,
  2171. active: 0
  2172. };
  2173. $data.find('.item').each(function() {
  2174. data.items.push({
  2175. name: $(this).text(),
  2176. url: $(this).data('url'),
  2177. branch: $(this).hasClass('branch'),
  2178. tag: $(this).hasClass('tag'),
  2179. selected: $(this).hasClass('selected')
  2180. });
  2181. });
  2182. $data.remove();
  2183. new Vue({
  2184. delimiters: ['${', '}'],
  2185. el: this,
  2186. data: data,
  2187. beforeMount: function () {
  2188. var vm = this;
  2189. this.noResults = vm.$el.getAttribute('data-no-results');
  2190. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2191. document.body.addEventListener('click', function(event) {
  2192. if (vm.$el.contains(event.target)) {
  2193. return;
  2194. }
  2195. if (vm.menuVisible) {
  2196. Vue.set(vm, 'menuVisible', false);
  2197. }
  2198. });
  2199. },
  2200. watch: {
  2201. menuVisible: function(visible) {
  2202. if (visible) {
  2203. this.focusSearchField();
  2204. }
  2205. }
  2206. },
  2207. computed: {
  2208. filteredItems: function() {
  2209. var vm = this;
  2210. var items = vm.items.filter(function (item) {
  2211. return ((vm.mode === 'branches' && item.branch)
  2212. || (vm.mode === 'tags' && item.tag))
  2213. && (!vm.searchTerm
  2214. || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2215. });
  2216. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2217. return items;
  2218. },
  2219. showNoResults: function() {
  2220. return this.filteredItems.length === 0
  2221. && !this.showCreateNewBranch;
  2222. },
  2223. showCreateNewBranch: function() {
  2224. var vm = this;
  2225. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2226. return false;
  2227. }
  2228. return vm.items.filter(function (item) {
  2229. return item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  2230. }).length === 0;
  2231. }
  2232. },
  2233. methods: {
  2234. selectItem: function(item) {
  2235. var prev = this.getSelected();
  2236. if (prev !== null) {
  2237. prev.selected = false;
  2238. }
  2239. item.selected = true;
  2240. window.location.href = item.url;
  2241. },
  2242. createNewBranch: function() {
  2243. if (!this.showCreateNewBranch) {
  2244. return;
  2245. }
  2246. this.$refs.newBranchForm.submit();
  2247. },
  2248. focusSearchField: function() {
  2249. var vm = this;
  2250. Vue.nextTick(function() {
  2251. vm.$refs.searchField.focus();
  2252. });
  2253. },
  2254. getSelected: function() {
  2255. for (var i = 0, j = this.items.length; i < j; ++i) {
  2256. if (this.items[i].selected)
  2257. return this.items[i];
  2258. }
  2259. return null;
  2260. },
  2261. getSelectedIndexInFiltered: function() {
  2262. for (var i = 0, j = this.filteredItems.length; i < j; ++i) {
  2263. if (this.filteredItems[i].selected)
  2264. return i;
  2265. }
  2266. return -1;
  2267. },
  2268. scrollToActive: function() {
  2269. var el = this.$refs['listItem' + this.active];
  2270. if (!el || el.length === 0) {
  2271. return;
  2272. }
  2273. if (Array.isArray(el)) {
  2274. el = el[0];
  2275. }
  2276. var cont = this.$refs.scrollContainer;
  2277. if (el.offsetTop < cont.scrollTop) {
  2278. cont.scrollTop = el.offsetTop;
  2279. }
  2280. else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2281. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2282. }
  2283. },
  2284. keydown: function(event) {
  2285. var vm = this;
  2286. if (event.keyCode === 40) {
  2287. // arrow down
  2288. event.preventDefault();
  2289. if (vm.active === -1) {
  2290. vm.active = vm.getSelectedIndexInFiltered();
  2291. }
  2292. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2293. return;
  2294. }
  2295. vm.active++;
  2296. vm.scrollToActive();
  2297. }
  2298. if (event.keyCode === 38) {
  2299. // arrow up
  2300. event.preventDefault();
  2301. if (vm.active === -1) {
  2302. vm.active = vm.getSelectedIndexInFiltered();
  2303. }
  2304. if (vm.active <= 0) {
  2305. return;
  2306. }
  2307. vm.active--;
  2308. vm.scrollToActive();
  2309. }
  2310. if (event.keyCode == 13) {
  2311. // enter
  2312. event.preventDefault();
  2313. if (vm.active >= vm.filteredItems.length) {
  2314. vm.createNewBranch();
  2315. } else if (vm.active >= 0) {
  2316. vm.selectItem(vm.filteredItems[vm.active]);
  2317. }
  2318. }
  2319. if (event.keyCode == 27) {
  2320. // escape
  2321. event.preventDefault();
  2322. vm.menuVisible = false;
  2323. }
  2324. }
  2325. }
  2326. });
  2327. });
  2328. }
  2329. $(".commit-button").click(function() {
  2330. $(this).parent().find('.commit-body').toggle();
  2331. });
  2332. function initNavbarContentToggle() {
  2333. var content = $('#navbar');
  2334. var toggle = $('#navbar-expand-toggle');
  2335. var isExpanded = false;
  2336. toggle.click(function() {
  2337. isExpanded = !isExpanded;
  2338. if (isExpanded) {
  2339. content.addClass('shown');
  2340. toggle.addClass('active');
  2341. }
  2342. else {
  2343. content.removeClass('shown');
  2344. toggle.removeClass('active');
  2345. }
  2346. });
  2347. }
  2348. function initTopicbar() {
  2349. var mgrBtn = $("#manage_topic"),
  2350. editDiv = $("#topic_edit"),
  2351. viewDiv = $("#repo-topic"),
  2352. saveBtn = $("#save_topic"),
  2353. topicDropdown = $('#topic_edit .dropdown'),
  2354. topicForm = $('#topic_edit.ui.form'),
  2355. topicPrompts;
  2356. mgrBtn.click(function() {
  2357. viewDiv.hide();
  2358. editDiv.css('display', ''); // show Semantic UI Grid
  2359. });
  2360. function getPrompts() {
  2361. var hidePrompt = $("div.hide#validate_prompt"),
  2362. prompts = {
  2363. countPrompt: hidePrompt.children('#count_prompt').text(),
  2364. formatPrompt: hidePrompt.children('#format_prompt').text()
  2365. };
  2366. hidePrompt.remove();
  2367. return prompts;
  2368. }
  2369. saveBtn.click(function() {
  2370. var topics = $("input[name=topics]").val();
  2371. $.post(saveBtn.data('link'), {
  2372. "_csrf": csrf,
  2373. "topics": topics
  2374. }, function(data, textStatus, xhr){
  2375. if (xhr.responseJSON.status === 'ok') {
  2376. viewDiv.children(".topic").remove();
  2377. if (topics.length === 0) {
  2378. return
  2379. }
  2380. var topicArray = topics.split(",");
  2381. var last = viewDiv.children("a").last();
  2382. for (var i=0; i < topicArray.length; i++) {
  2383. $('<div class="ui green basic label topic" style="cursor:pointer;">'+topicArray[i]+'</div>').insertBefore(last)
  2384. }
  2385. editDiv.css('display', 'none'); // hide Semantic UI Grid
  2386. viewDiv.show();
  2387. }
  2388. }).fail(function(xhr){
  2389. if (xhr.status === 422) {
  2390. if (xhr.responseJSON.invalidTopics.length > 0) {
  2391. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2392. var invalidTopics = xhr.responseJSON.invalidTopics,
  2393. topicLables = topicDropdown.children('a.ui.label');
  2394. topics.split(',').forEach(function(value, index) {
  2395. for (var i=0; i < invalidTopics.length; i++) {
  2396. if (invalidTopics[i] === value) {
  2397. topicLables.eq(index).removeClass("green").addClass("red");
  2398. }
  2399. }
  2400. });
  2401. } else {
  2402. topicPrompts.countPrompt = xhr.responseJSON.message;
  2403. }
  2404. }
  2405. }).always(function() {
  2406. topicForm.form('validate form');
  2407. });
  2408. });
  2409. topicDropdown.dropdown({
  2410. allowAdditions: true,
  2411. fields: { name: "description", value: "data-value" },
  2412. saveRemoteData: false,
  2413. label: {
  2414. transition : 'horizontal flip',
  2415. duration : 200,
  2416. variation : false,
  2417. blue : true,
  2418. basic: true,
  2419. },
  2420. className: {
  2421. label: 'ui green basic label'
  2422. },
  2423. apiSettings: {
  2424. url: suburl + '/api/v1/topics/search?q={query}',
  2425. throttle: 500,
  2426. cache: false,
  2427. onResponse: function(res) {
  2428. var formattedResponse = {
  2429. success: false,
  2430. results: [],
  2431. };
  2432. if (res.topics) {
  2433. formattedResponse.success = true;
  2434. for (var i=0;i < res.topics.length;i++) {
  2435. formattedResponse.results.push({"description": res.topics[i].Name, "data-value":res.topics[i].Name})
  2436. }
  2437. }
  2438. return formattedResponse;
  2439. },
  2440. },
  2441. onLabelCreate: function(value) {
  2442. value = value.toLowerCase().trim();
  2443. this.attr("data-value", value).contents().first().replaceWith(value);
  2444. return $(this);
  2445. },
  2446. onAdd: function(addedValue, addedText, $addedChoice) {
  2447. addedValue = addedValue.toLowerCase().trim();
  2448. $($addedChoice).attr('data-value', addedValue);
  2449. $($addedChoice).attr('data-text', addedValue);
  2450. }
  2451. });
  2452. $.fn.form.settings.rules.validateTopic = function(values, regExp) {
  2453. var topics = topicDropdown.children('a.ui.label'),
  2454. status = topics.length === 0 || topics.last().attr("data-value").match(regExp);
  2455. if (!status) {
  2456. topics.last().removeClass("green").addClass("red");
  2457. }
  2458. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2459. };
  2460. topicPrompts = getPrompts();
  2461. topicForm.form({
  2462. on: 'change',
  2463. inline : true,
  2464. fields: {
  2465. topics: {
  2466. identifier: 'topics',
  2467. rules: [
  2468. {
  2469. type: 'validateTopic',
  2470. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2471. prompt: topicPrompts.formatPrompt
  2472. },
  2473. {
  2474. type: 'maxCount[25]',
  2475. prompt: topicPrompts.countPrompt
  2476. }
  2477. ]
  2478. },
  2479. }
  2480. });
  2481. }
  2482. function toggleDeadlineForm() {
  2483. $('#deadlineForm').fadeToggle(150);
  2484. }
  2485. function setDeadline() {
  2486. var deadline = $('#deadlineDate').val();
  2487. updateDeadline(deadline);
  2488. }
  2489. function updateDeadline(deadlineString) {
  2490. $('#deadline-err-invalid-date').hide();
  2491. $('#deadline-loader').addClass('loading');
  2492. var realDeadline = null;
  2493. if (deadlineString !== '') {
  2494. var newDate = Date.parse(deadlineString)
  2495. if (isNaN(newDate)) {
  2496. $('#deadline-loader').removeClass('loading');
  2497. $('#deadline-err-invalid-date').show();
  2498. return false;
  2499. }
  2500. realDeadline = new Date(newDate);
  2501. }
  2502. $.ajax($('#update-issue-deadline-form').attr('action') + '/deadline', {
  2503. data: JSON.stringify({
  2504. 'due_date': realDeadline,
  2505. }),
  2506. headers: {
  2507. 'X-Csrf-Token': csrf,
  2508. 'X-Remote': true,
  2509. },
  2510. contentType: 'application/json',
  2511. type: 'POST',
  2512. success: function () {
  2513. window.location.reload();
  2514. },
  2515. error: function () {
  2516. $('#deadline-loader').removeClass('loading');
  2517. $('#deadline-err-invalid-date').show();
  2518. }
  2519. });
  2520. }
  2521. function deleteDependencyModal(id, type) {
  2522. $('.remove-dependency')
  2523. .modal({
  2524. closable: false,
  2525. duration: 200,
  2526. onApprove: function () {
  2527. $('#removeDependencyID').val(id);
  2528. $('#dependencyType').val(type);
  2529. $('#removeDependencyForm').submit();
  2530. }
  2531. }).modal('show')
  2532. ;
  2533. }
  2534. function initIssueList() {
  2535. var repolink = $('#repolink').val();
  2536. $('.new-dependency-drop-list')
  2537. .dropdown({
  2538. apiSettings: {
  2539. url: suburl + '/api/v1/repos/' + repolink + '/issues?q={query}',
  2540. onResponse: function(response) {
  2541. var filteredResponse = {'success': true, 'results': []};
  2542. // Parse the response from the api to work with our dropdown
  2543. $.each(response, function(index, issue) {
  2544. filteredResponse.results.push({
  2545. 'name' : '#' + issue.number + '&nbsp;' + issue.title,
  2546. 'value' : issue.id
  2547. });
  2548. });
  2549. return filteredResponse;
  2550. },
  2551. },
  2552. fullTextSearch: true
  2553. })
  2554. ;
  2555. }
  2556. function cancelCodeComment(btn) {
  2557. var form = $(btn).closest("form");
  2558. if(form.length > 0 && form.hasClass('comment-form')) {
  2559. form.addClass('hide');
  2560. form.parent().find('button.comment-form-reply').show();
  2561. } else {
  2562. form.closest('.comment-code-cloud').remove()
  2563. }
  2564. }