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

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