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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078
  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. "code", "quote", "|",
  1055. "unordered-list", "ordered-list", "|",
  1056. "link", "image", "table", "horizontal-rule", "|",
  1057. "clean-block", "preview", "fullscreen"]
  1058. })
  1059. $(simplemde.codemirror.getInputField()).addClass("js-quick-submit");
  1060. }
  1061. }
  1062. var simpleMDEditor;
  1063. var codeMirrorEditor;
  1064. // For IE
  1065. String.prototype.endsWith = function (pattern) {
  1066. var d = this.length - pattern.length;
  1067. return d >= 0 && this.lastIndexOf(pattern) === d;
  1068. };
  1069. // Adding function to get the cursor position in a text field to jQuery object.
  1070. $.fn.getCursorPosition = function () {
  1071. var el = $(this).get(0);
  1072. var pos = 0;
  1073. if ('selectionStart' in el) {
  1074. pos = el.selectionStart;
  1075. } else if ('selection' in document) {
  1076. el.focus();
  1077. var Sel = document.selection.createRange();
  1078. var SelLength = document.selection.createRange().text.length;
  1079. Sel.moveStart('character', -el.value.length);
  1080. pos = Sel.text.length - SelLength;
  1081. }
  1082. return pos;
  1083. }
  1084. function setSimpleMDE($editArea) {
  1085. if (codeMirrorEditor) {
  1086. codeMirrorEditor.toTextArea();
  1087. codeMirrorEditor = null;
  1088. }
  1089. if (simpleMDEditor) {
  1090. return true;
  1091. }
  1092. simpleMDEditor = new SimpleMDE({
  1093. autoDownloadFontAwesome: false,
  1094. element: $editArea[0],
  1095. forceSync: true,
  1096. renderingConfig: {
  1097. singleLineBreaks: false
  1098. },
  1099. indentWithTabs: false,
  1100. tabSize: 4,
  1101. spellChecker: false,
  1102. previewRender: function (plainText, preview) { // Async method
  1103. setTimeout(function () {
  1104. // FIXME: still send render request when return back to edit mode
  1105. $.post($editArea.data('url'), {
  1106. "_csrf": csrf,
  1107. "mode": "gfm",
  1108. "context": $editArea.data('context'),
  1109. "text": plainText
  1110. },
  1111. function (data) {
  1112. preview.innerHTML = '<div class="markdown ui segment">' + data + '</div>';
  1113. emojify.run($('.editor-preview')[0]);
  1114. }
  1115. );
  1116. }, 0);
  1117. return "Loading...";
  1118. },
  1119. toolbar: ["bold", "italic", "strikethrough", "|",
  1120. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  1121. "code", "quote", "|",
  1122. "unordered-list", "ordered-list", "|",
  1123. "link", "image", "table", "horizontal-rule", "|",
  1124. "clean-block", "preview", "fullscreen", "side-by-side"]
  1125. });
  1126. return true;
  1127. }
  1128. function setCodeMirror($editArea) {
  1129. if (simpleMDEditor) {
  1130. simpleMDEditor.toTextArea();
  1131. simpleMDEditor = null;
  1132. }
  1133. if (codeMirrorEditor) {
  1134. return true;
  1135. }
  1136. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  1137. lineNumbers: true
  1138. });
  1139. codeMirrorEditor.on("change", function (cm, _change) {
  1140. $editArea.val(cm.getValue());
  1141. });
  1142. return true;
  1143. }
  1144. function initEditor() {
  1145. $('.js-quick-pull-choice-option').change(function () {
  1146. if ($(this).val() == 'commit-to-new-branch') {
  1147. $('.quick-pull-branch-name').show();
  1148. $('.quick-pull-branch-name input').prop('required',true);
  1149. } else {
  1150. $('.quick-pull-branch-name').hide();
  1151. $('.quick-pull-branch-name input').prop('required',false);
  1152. }
  1153. $('#commit-button').text($(this).attr('button_text'));
  1154. });
  1155. var $editFilename = $("#file-name");
  1156. $editFilename.keyup(function (e) {
  1157. var $section = $('.breadcrumb span.section');
  1158. var $divider = $('.breadcrumb div.divider');
  1159. var value;
  1160. var parts;
  1161. if (e.keyCode == 8) {
  1162. if ($(this).getCursorPosition() == 0) {
  1163. if ($section.length > 0) {
  1164. value = $section.last().find('a').text();
  1165. $(this).val(value + $(this).val());
  1166. $(this)[0].setSelectionRange(value.length, value.length);
  1167. $section.last().remove();
  1168. $divider.last().remove();
  1169. }
  1170. }
  1171. }
  1172. if (e.keyCode == 191) {
  1173. parts = $(this).val().split('/');
  1174. for (var i = 0; i < parts.length; ++i) {
  1175. value = parts[i];
  1176. if (i < parts.length - 1) {
  1177. if (value.length) {
  1178. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  1179. $('<div class="divider"> / </div>').insertBefore($(this));
  1180. }
  1181. }
  1182. else {
  1183. $(this).val(value);
  1184. }
  1185. $(this)[0].setSelectionRange(0, 0);
  1186. }
  1187. }
  1188. parts = [];
  1189. $('.breadcrumb span.section').each(function () {
  1190. var element = $(this);
  1191. if (element.find('a').length) {
  1192. parts.push(element.find('a').text());
  1193. } else {
  1194. parts.push(element.text());
  1195. }
  1196. });
  1197. if ($(this).val())
  1198. parts.push($(this).val());
  1199. $('#tree_path').val(parts.join('/'));
  1200. }).trigger('keyup');
  1201. var $editArea = $('.repository.editor textarea#edit_area');
  1202. if (!$editArea.length)
  1203. return;
  1204. var markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  1205. var lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  1206. $editFilename.on("keyup", function () {
  1207. var val = $editFilename.val(), m, mode, spec, extension, extWithDot, previewLink, dataUrl, apiCall;
  1208. extension = extWithDot = "";
  1209. m = /.+\.([^.]+)$/.exec(val);
  1210. if (m) {
  1211. extension = m[1];
  1212. extWithDot = "." + extension;
  1213. }
  1214. var info = CodeMirror.findModeByExtension(extension);
  1215. previewLink = $('a[data-tab=preview]');
  1216. if (info) {
  1217. mode = info.mode;
  1218. spec = info.mime;
  1219. apiCall = mode;
  1220. }
  1221. else {
  1222. apiCall = extension
  1223. }
  1224. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  1225. dataUrl = previewLink.data('url');
  1226. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  1227. previewLink.show();
  1228. }
  1229. else {
  1230. previewLink.hide();
  1231. }
  1232. // If this file is a Markdown extensions, we will load that editor and return
  1233. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  1234. if (setSimpleMDE($editArea)) {
  1235. return;
  1236. }
  1237. }
  1238. // Else we are going to use CodeMirror
  1239. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  1240. return;
  1241. }
  1242. if (mode) {
  1243. codeMirrorEditor.setOption("mode", spec);
  1244. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  1245. }
  1246. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  1247. codeMirrorEditor.setOption("lineWrapping", true);
  1248. }
  1249. else {
  1250. codeMirrorEditor.setOption("lineWrapping", false);
  1251. }
  1252. // get the filename without any folder
  1253. var value = $editFilename.val();
  1254. if (value.length === 0) {
  1255. return;
  1256. }
  1257. value = value.split('/');
  1258. value = value[value.length - 1];
  1259. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  1260. if (editorconfig.indent_style === 'tab') {
  1261. codeMirrorEditor.setOption("indentWithTabs", true);
  1262. codeMirrorEditor.setOption('extraKeys', {});
  1263. } else {
  1264. codeMirrorEditor.setOption("indentWithTabs", false);
  1265. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  1266. // - https://github.com/codemirror/CodeMirror/issues/988
  1267. // - https://codemirror.net/doc/manual.html#keymaps
  1268. codeMirrorEditor.setOption('extraKeys', {
  1269. Tab: function(cm) {
  1270. var spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  1271. cm.replaceSelection(spaces);
  1272. }
  1273. });
  1274. }
  1275. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  1276. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  1277. });
  1278. }).trigger('keyup');
  1279. }
  1280. function initOrganization() {
  1281. if ($('.organization').length == 0) {
  1282. return;
  1283. }
  1284. // Options
  1285. if ($('.organization.settings.options').length > 0) {
  1286. $('#org_name').keyup(function () {
  1287. var $prompt = $('#org-name-change-prompt');
  1288. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  1289. $prompt.show();
  1290. } else {
  1291. $prompt.hide();
  1292. }
  1293. });
  1294. }
  1295. }
  1296. function initUserSettings() {
  1297. // Options
  1298. if ($('.user.settings.profile').length > 0) {
  1299. $('#username').keyup(function () {
  1300. var $prompt = $('#name-change-prompt');
  1301. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1302. $prompt.show();
  1303. } else {
  1304. $prompt.hide();
  1305. }
  1306. });
  1307. }
  1308. }
  1309. function initWebhook() {
  1310. if ($('.new.webhook').length == 0) {
  1311. return;
  1312. }
  1313. $('.events.checkbox input').change(function () {
  1314. if ($(this).is(':checked')) {
  1315. $('.events.fields').show();
  1316. }
  1317. });
  1318. $('.non-events.checkbox input').change(function () {
  1319. if ($(this).is(':checked')) {
  1320. $('.events.fields').hide();
  1321. }
  1322. });
  1323. var updateContentType = function () {
  1324. var visible = $('#http_method').val() === 'POST';
  1325. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1326. };
  1327. updateContentType();
  1328. $('#http_method').change(function () {
  1329. updateContentType();
  1330. });
  1331. // Test delivery
  1332. $('#test-delivery').click(function () {
  1333. var $this = $(this);
  1334. $this.addClass('loading disabled');
  1335. $.post($this.data('link'), {
  1336. "_csrf": csrf
  1337. }).done(
  1338. setTimeout(function () {
  1339. window.location.href = $this.data('redirect');
  1340. }, 5000)
  1341. )
  1342. });
  1343. }
  1344. function initAdmin() {
  1345. if ($('.admin').length == 0) {
  1346. return;
  1347. }
  1348. // New user
  1349. if ($('.admin.new.user').length > 0 ||
  1350. $('.admin.edit.user').length > 0) {
  1351. $('#login_type').change(function () {
  1352. if ($(this).val().substring(0, 1) == '0') {
  1353. $('#login_name').removeAttr('required');
  1354. $('.non-local').hide();
  1355. $('.local').show();
  1356. $('#user_name').focus();
  1357. if ($(this).data('password') == "required") {
  1358. $('#password').attr('required', 'required');
  1359. }
  1360. } else {
  1361. $('#login_name').attr('required', 'required');
  1362. $('.non-local').show();
  1363. $('.local').hide();
  1364. $('#login_name').focus();
  1365. $('#password').removeAttr('required');
  1366. }
  1367. });
  1368. }
  1369. function onSecurityProtocolChange() {
  1370. if ($('#security_protocol').val() > 0) {
  1371. $('.has-tls').show();
  1372. } else {
  1373. $('.has-tls').hide();
  1374. }
  1375. }
  1376. function onUsePagedSearchChange() {
  1377. if ($('#use_paged_search').prop('checked')) {
  1378. $('.search-page-size').show()
  1379. .find('input').attr('required', 'required');
  1380. } else {
  1381. $('.search-page-size').hide()
  1382. .find('input').removeAttr('required');
  1383. }
  1384. }
  1385. function onOAuth2Change() {
  1386. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1387. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1388. var provider = $('#oauth2_provider').val();
  1389. switch (provider) {
  1390. case 'github':
  1391. case 'gitlab':
  1392. $('.oauth2_use_custom_url').show();
  1393. break;
  1394. case 'openidConnect':
  1395. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1396. $('.open_id_connect_auto_discovery_url').show();
  1397. break;
  1398. }
  1399. onOAuth2UseCustomURLChange();
  1400. }
  1401. function onOAuth2UseCustomURLChange() {
  1402. var provider = $('#oauth2_provider').val();
  1403. $('.oauth2_use_custom_url_field').hide();
  1404. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1405. if ($('#oauth2_use_custom_url').is(':checked')) {
  1406. if (!$('#oauth2_token_url').val()) {
  1407. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  1408. }
  1409. if (!$('#oauth2_auth_url').val()) {
  1410. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  1411. }
  1412. if (!$('#oauth2_profile_url').val()) {
  1413. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  1414. }
  1415. if (!$('#oauth2_email_url').val()) {
  1416. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  1417. }
  1418. switch (provider) {
  1419. case 'github':
  1420. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1421. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1422. break;
  1423. case 'gitlab':
  1424. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1425. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1426. $('#oauth2_email_url').val('');
  1427. break;
  1428. }
  1429. }
  1430. }
  1431. // New authentication
  1432. if ($('.admin.new.authentication').length > 0) {
  1433. $('#auth_type').change(function () {
  1434. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls .search-page-size').hide();
  1435. $('.ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required]').removeAttr('required');
  1436. $('.binddnrequired').removeClass("required");
  1437. var authType = $(this).val();
  1438. switch (authType) {
  1439. case '2': // LDAP
  1440. $('.ldap').show();
  1441. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1442. $('.binddnrequired').addClass("required");
  1443. break;
  1444. case '3': // SMTP
  1445. $('.smtp').show();
  1446. $('.has-tls').show();
  1447. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1448. break;
  1449. case '4': // PAM
  1450. $('.pam').show();
  1451. $('.pam input').attr('required', 'required');
  1452. break;
  1453. case '5': // LDAP
  1454. $('.dldap').show();
  1455. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1456. break;
  1457. case '6': // OAuth2
  1458. $('.oauth2').show();
  1459. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1460. onOAuth2Change();
  1461. break;
  1462. }
  1463. if (authType == '2' || authType == '5') {
  1464. onSecurityProtocolChange()
  1465. }
  1466. if (authType == '2') {
  1467. onUsePagedSearchChange();
  1468. }
  1469. });
  1470. $('#auth_type').change();
  1471. $('#security_protocol').change(onSecurityProtocolChange);
  1472. $('#use_paged_search').change(onUsePagedSearchChange);
  1473. $('#oauth2_provider').change(onOAuth2Change);
  1474. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1475. }
  1476. // Edit authentication
  1477. if ($('.admin.edit.authentication').length > 0) {
  1478. var authType = $('#auth_type').val();
  1479. if (authType == '2' || authType == '5') {
  1480. $('#security_protocol').change(onSecurityProtocolChange);
  1481. if (authType == '2') {
  1482. $('#use_paged_search').change(onUsePagedSearchChange);
  1483. }
  1484. } else if (authType == '6') {
  1485. $('#oauth2_provider').change(onOAuth2Change);
  1486. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1487. onOAuth2Change();
  1488. }
  1489. }
  1490. // Notice
  1491. if ($('.admin.notice')) {
  1492. var $detailModal = $('#detail-modal');
  1493. // Attach view detail modals
  1494. $('.view-detail').click(function () {
  1495. $detailModal.find('.content p').text($(this).data('content'));
  1496. $detailModal.modal('show');
  1497. return false;
  1498. });
  1499. // Select actions
  1500. var $checkboxes = $('.select.table .ui.checkbox');
  1501. $('.select.action').click(function () {
  1502. switch ($(this).data('action')) {
  1503. case 'select-all':
  1504. $checkboxes.checkbox('check');
  1505. break;
  1506. case 'deselect-all':
  1507. $checkboxes.checkbox('uncheck');
  1508. break;
  1509. case 'inverse':
  1510. $checkboxes.checkbox('toggle');
  1511. break;
  1512. }
  1513. });
  1514. $('#delete-selection').click(function () {
  1515. var $this = $(this);
  1516. $this.addClass("loading disabled");
  1517. var ids = [];
  1518. $checkboxes.each(function () {
  1519. if ($(this).checkbox('is checked')) {
  1520. ids.push($(this).data('id'));
  1521. }
  1522. });
  1523. $.post($this.data('link'), {
  1524. "_csrf": csrf,
  1525. "ids": ids
  1526. }).done(function () {
  1527. window.location.href = $this.data('redirect');
  1528. });
  1529. });
  1530. }
  1531. }
  1532. function buttonsClickOnEnter() {
  1533. $('.ui.button').keypress(function (e) {
  1534. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1535. $(this).click();
  1536. });
  1537. }
  1538. function searchUsers() {
  1539. var $searchUserBox = $('#search-user-box');
  1540. $searchUserBox.search({
  1541. minCharacters: 2,
  1542. apiSettings: {
  1543. url: suburl + '/api/v1/users/search?q={query}',
  1544. onResponse: function(response) {
  1545. var items = [];
  1546. $.each(response.data, function (_i, item) {
  1547. var title = item.login;
  1548. if (item.full_name && item.full_name.length > 0) {
  1549. title += ' (' + htmlEncode(item.full_name) + ')';
  1550. }
  1551. items.push({
  1552. title: title,
  1553. image: item.avatar_url
  1554. })
  1555. });
  1556. return { results: items }
  1557. }
  1558. },
  1559. searchFields: ['login', 'full_name'],
  1560. showNoResults: false
  1561. });
  1562. }
  1563. function searchRepositories() {
  1564. var $searchRepoBox = $('#search-repo-box');
  1565. $searchRepoBox.search({
  1566. minCharacters: 2,
  1567. apiSettings: {
  1568. url: suburl + '/api/v1/repos/search?q={query}&uid=' + $searchRepoBox.data('uid'),
  1569. onResponse: function(response) {
  1570. var items = [];
  1571. $.each(response.data, function (_i, item) {
  1572. items.push({
  1573. title: item.full_name.split("/")[1],
  1574. description: item.full_name
  1575. })
  1576. });
  1577. return { results: items }
  1578. }
  1579. },
  1580. searchFields: ['full_name'],
  1581. showNoResults: false
  1582. });
  1583. }
  1584. function initCodeView() {
  1585. if ($('.code-view .linenums').length > 0) {
  1586. $(document).on('click', '.lines-num span', function (e) {
  1587. var $select = $(this);
  1588. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1589. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1590. deSelect();
  1591. });
  1592. $(window).on('hashchange', function () {
  1593. var m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1594. var $list = $('.code-view ol.linenums > li');
  1595. var $first;
  1596. if (m) {
  1597. $first = $list.filter('.' + m[1]);
  1598. selectRange($list, $first, $list.filter('.' + m[2]));
  1599. $("html, body").scrollTop($first.offset().top - 200);
  1600. return;
  1601. }
  1602. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1603. if (m) {
  1604. $first = $list.filter('.L' + m[2]);
  1605. selectRange($list, $first);
  1606. $("html, body").scrollTop($first.offset().top - 200);
  1607. }
  1608. }).trigger('hashchange');
  1609. }
  1610. }
  1611. function initU2FAuth() {
  1612. if($('#wait-for-key').length === 0) {
  1613. return
  1614. }
  1615. u2fApi.ensureSupport()
  1616. .then(function () {
  1617. $.getJSON(suburl + '/user/u2f/challenge').success(function(req) {
  1618. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1619. .then(u2fSigned)
  1620. .catch(function (err) {
  1621. if(err === undefined) {
  1622. u2fError(1);
  1623. return
  1624. }
  1625. u2fError(err.metaData.code);
  1626. });
  1627. });
  1628. }).catch(function () {
  1629. // Fallback in case browser do not support U2F
  1630. window.location.href = suburl + "/user/two_factor"
  1631. })
  1632. }
  1633. function u2fSigned(resp) {
  1634. $.ajax({
  1635. url: suburl + '/user/u2f/sign',
  1636. type: "POST",
  1637. headers: {"X-Csrf-Token": csrf},
  1638. data: JSON.stringify(resp),
  1639. contentType: "application/json; charset=utf-8",
  1640. }).done(function(res){
  1641. window.location.replace(res);
  1642. }).fail(function () {
  1643. u2fError(1);
  1644. });
  1645. }
  1646. function u2fRegistered(resp) {
  1647. if (checkError(resp)) {
  1648. return;
  1649. }
  1650. $.ajax({
  1651. url: suburl + '/user/settings/security/u2f/register',
  1652. type: "POST",
  1653. headers: {"X-Csrf-Token": csrf},
  1654. data: JSON.stringify(resp),
  1655. contentType: "application/json; charset=utf-8",
  1656. success: function(){
  1657. reload();
  1658. },
  1659. fail: function () {
  1660. u2fError(1);
  1661. }
  1662. });
  1663. }
  1664. function checkError(resp) {
  1665. if (!('errorCode' in resp)) {
  1666. return false;
  1667. }
  1668. if (resp.errorCode === 0) {
  1669. return false;
  1670. }
  1671. u2fError(resp.errorCode);
  1672. return true;
  1673. }
  1674. function u2fError(errorType) {
  1675. var u2fErrors = {
  1676. 'browser': $('#unsupported-browser'),
  1677. 1: $('#u2f-error-1'),
  1678. 2: $('#u2f-error-2'),
  1679. 3: $('#u2f-error-3'),
  1680. 4: $('#u2f-error-4'),
  1681. 5: $('.u2f-error-5')
  1682. };
  1683. u2fErrors[errorType].removeClass('hide');
  1684. for(var type in u2fErrors){
  1685. if(type != errorType){
  1686. u2fErrors[type].addClass('hide');
  1687. }
  1688. }
  1689. $('#u2f-error').modal('show');
  1690. }
  1691. function initU2FRegister() {
  1692. $('#register-device').modal({allowMultiple: false});
  1693. $('#u2f-error').modal({allowMultiple: false});
  1694. $('#register-security-key').on('click', function(e) {
  1695. e.preventDefault();
  1696. u2fApi.ensureSupport()
  1697. .then(u2fRegisterRequest)
  1698. .catch(function() {
  1699. u2fError('browser');
  1700. })
  1701. })
  1702. }
  1703. function u2fRegisterRequest() {
  1704. $.post(suburl + "/user/settings/security/u2f/request_register", {
  1705. "_csrf": csrf,
  1706. "name": $('#nickname').val()
  1707. }).success(function(req) {
  1708. $("#nickname").closest("div.field").removeClass("error");
  1709. $('#register-device').modal('show');
  1710. if(req.registeredKeys === null) {
  1711. req.registeredKeys = []
  1712. }
  1713. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1714. .then(u2fRegistered)
  1715. .catch(function (reason) {
  1716. if(reason === undefined) {
  1717. u2fError(1);
  1718. return
  1719. }
  1720. u2fError(reason.metaData.code);
  1721. });
  1722. }).fail(function(xhr) {
  1723. if(xhr.status === 409) {
  1724. $("#nickname").closest("div.field").addClass("error");
  1725. }
  1726. });
  1727. }
  1728. function initWipTitle() {
  1729. $(".title_wip_desc > a").click(function (e) {
  1730. e.preventDefault();
  1731. var $issueTitle = $("#issue_title");
  1732. $issueTitle.focus();
  1733. var value = $issueTitle.val().trim().toUpperCase();
  1734. for (var i in wipPrefixes) {
  1735. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1736. return;
  1737. }
  1738. }
  1739. $issueTitle.val(wipPrefixes[0] + " " + $issueTitle.val());
  1740. });
  1741. }
  1742. $(document).ready(function () {
  1743. csrf = $('meta[name=_csrf]').attr("content");
  1744. suburl = $('meta[name=_suburl]').attr("content");
  1745. // Show exact time
  1746. $('.time-since').each(function () {
  1747. var time = new Date($(this).attr('title'))
  1748. if (!isNaN(time)){
  1749. $(this).attr('title', time.toLocaleString())
  1750. }
  1751. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1752. });
  1753. // Semantic UI modules.
  1754. $('.dropdown:not(.custom)').dropdown();
  1755. $('.jump.dropdown').dropdown({
  1756. action: 'hide',
  1757. onShow: function () {
  1758. $('.poping.up').popup('hide');
  1759. }
  1760. });
  1761. $('.slide.up.dropdown').dropdown({
  1762. transition: 'slide up'
  1763. });
  1764. $('.upward.dropdown').dropdown({
  1765. direction: 'upward'
  1766. });
  1767. $('.ui.accordion').accordion();
  1768. $('.ui.checkbox').checkbox();
  1769. $('.ui.progress').progress({
  1770. showActivity: false
  1771. });
  1772. $('.poping.up').popup();
  1773. $('.top.menu .poping.up').popup({
  1774. onShow: function () {
  1775. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1776. return false;
  1777. }
  1778. }
  1779. });
  1780. $('.tabular.menu .item').tab();
  1781. $('.tabable.menu .item').tab();
  1782. $('.toggle.button').click(function () {
  1783. $($(this).data('target')).slideToggle(100);
  1784. });
  1785. // make table <tr> element clickable like a link
  1786. $('tr[data-href]').click(function() {
  1787. window.location = $(this).data('href');
  1788. });
  1789. // Highlight JS
  1790. if (typeof hljs != 'undefined') {
  1791. const nodes = [].slice.call(document.querySelectorAll('pre code') || []);
  1792. for (let i = 0; i < nodes.length; i++) {
  1793. hljs.highlightBlock(nodes[i]);
  1794. }
  1795. }
  1796. // Dropzone
  1797. const $dropzone = $('#dropzone');
  1798. if ($dropzone.length > 0) {
  1799. const filenameDict = {};
  1800. new Dropzone("#dropzone", {
  1801. url: $dropzone.data('upload-url'),
  1802. headers: {"X-Csrf-Token": csrf},
  1803. maxFiles: $dropzone.data('max-file'),
  1804. maxFilesize: $dropzone.data('max-size'),
  1805. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  1806. addRemoveLinks: true,
  1807. dictDefaultMessage: $dropzone.data('default-message'),
  1808. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  1809. dictFileTooBig: $dropzone.data('file-too-big'),
  1810. dictRemoveFile: $dropzone.data('remove-file'),
  1811. init: function () {
  1812. this.on("success", function (file, data) {
  1813. filenameDict[file.name] = data.uuid;
  1814. var input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  1815. $('.files').append(input);
  1816. });
  1817. this.on("removedfile", function (file) {
  1818. if (file.name in filenameDict) {
  1819. $('#' + filenameDict[file.name]).remove();
  1820. }
  1821. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  1822. $.post($dropzone.data('remove-url'), {
  1823. file: filenameDict[file.name],
  1824. _csrf: $dropzone.data('csrf')
  1825. });
  1826. }
  1827. })
  1828. },
  1829. });
  1830. }
  1831. // Emojify
  1832. emojify.setConfig({
  1833. img_dir: suburl + '/vendor/plugins/emojify/images',
  1834. ignore_emoticons: true
  1835. });
  1836. var hasEmoji = document.getElementsByClassName('has-emoji');
  1837. for (var i = 0; i < hasEmoji.length; i++) {
  1838. emojify.run(hasEmoji[i]);
  1839. for (var j = 0; j < hasEmoji[i].childNodes.length; j++) {
  1840. if (hasEmoji[i].childNodes[j].nodeName === "A") {
  1841. emojify.run(hasEmoji[i].childNodes[j])
  1842. }
  1843. }
  1844. }
  1845. // Clipboard JS
  1846. var clipboard = new Clipboard('.clipboard');
  1847. clipboard.on('success', function (e) {
  1848. e.clearSelection();
  1849. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1850. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  1851. $('#' + e.trigger.getAttribute('id')).popup('show');
  1852. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1853. });
  1854. clipboard.on('error', function (e) {
  1855. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  1856. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  1857. $('#' + e.trigger.getAttribute('id')).popup('show');
  1858. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  1859. });
  1860. // Helpers.
  1861. $('.delete-button').click(showDeletePopup);
  1862. $('.delete-branch-button').click(showDeletePopup);
  1863. $('.undo-button').click(function() {
  1864. var $this = $(this);
  1865. $.post($this.data('url'), {
  1866. "_csrf": csrf,
  1867. "id": $this.data("id")
  1868. }).done(function(data) {
  1869. window.location.href = data.redirect;
  1870. });
  1871. });
  1872. $('.show-panel.button').click(function () {
  1873. $($(this).data('panel')).show();
  1874. });
  1875. $('.show-modal.button').click(function () {
  1876. $($(this).data('modal')).modal('show');
  1877. });
  1878. $('.delete-post.button').click(function () {
  1879. var $this = $(this);
  1880. $.post($this.data('request-url'), {
  1881. "_csrf": csrf
  1882. }).done(function () {
  1883. window.location.href = $this.data('done-url');
  1884. });
  1885. });
  1886. // Set anchor.
  1887. $('.markdown').each(function () {
  1888. var headers = {};
  1889. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  1890. var node = $(this);
  1891. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  1892. var name = val;
  1893. if (headers[val] > 0) {
  1894. name = val + '-' + headers[val];
  1895. }
  1896. if (headers[val] == undefined) {
  1897. headers[val] = 1;
  1898. } else {
  1899. headers[val] += 1;
  1900. }
  1901. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  1902. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  1903. });
  1904. });
  1905. $('.issue-checkbox').click(function() {
  1906. var numChecked = $('.issue-checkbox').children('input:checked').length;
  1907. if (numChecked > 0) {
  1908. $('#issue-filters').addClass("hide");
  1909. $('#issue-actions').removeClass("hide");
  1910. } else {
  1911. $('#issue-filters').removeClass("hide");
  1912. $('#issue-actions').addClass("hide");
  1913. }
  1914. });
  1915. $('.issue-action').click(function () {
  1916. let action = this.dataset.action;
  1917. let elementId = this.dataset.elementId;
  1918. let issueIDs = $('.issue-checkbox').children('input:checked').map(function() {
  1919. return this.dataset.issueId;
  1920. }).get().join();
  1921. let url = this.dataset.url;
  1922. if (elementId === '0' && url.substr(-9) === '/assignee'){
  1923. elementId = '';
  1924. action = 'clear';
  1925. }
  1926. updateIssuesMeta(url, action, issueIDs, elementId).then(reload);
  1927. });
  1928. buttonsClickOnEnter();
  1929. searchUsers();
  1930. searchRepositories();
  1931. initCommentForm();
  1932. initInstall();
  1933. initRepository();
  1934. initMigration();
  1935. initWikiForm();
  1936. initEditForm();
  1937. initEditor();
  1938. initOrganization();
  1939. initWebhook();
  1940. initAdmin();
  1941. initCodeView();
  1942. initVueApp();
  1943. initTeamSettings();
  1944. initCtrlEnterSubmit();
  1945. initNavbarContentToggle();
  1946. initTopicbar();
  1947. initU2FAuth();
  1948. initU2FRegister();
  1949. initIssueList();
  1950. initWipTitle();
  1951. initPullRequestReview();
  1952. // Repo clone url.
  1953. if ($('#repo-clone-url').length > 0) {
  1954. switch (localStorage.getItem('repo-clone-protocol')) {
  1955. case 'ssh':
  1956. if ($('#repo-clone-ssh').click().length === 0) {
  1957. $('#repo-clone-https').click();
  1958. }
  1959. break;
  1960. default:
  1961. $('#repo-clone-https').click();
  1962. break;
  1963. }
  1964. }
  1965. var routes = {
  1966. 'div.user.settings': initUserSettings,
  1967. 'div.repository.settings.collaboration': initRepositoryCollaboration
  1968. };
  1969. var selector;
  1970. for (selector in routes) {
  1971. if ($(selector).length > 0) {
  1972. routes[selector]();
  1973. break;
  1974. }
  1975. }
  1976. var $cloneAddr = $('#clone_addr');
  1977. $cloneAddr.change(function() {
  1978. var $repoName = $('#repo_name');
  1979. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank
  1980. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  1981. }
  1982. });
  1983. });
  1984. function changeHash(hash) {
  1985. if (history.pushState) {
  1986. history.pushState(null, null, hash);
  1987. }
  1988. else {
  1989. location.hash = hash;
  1990. }
  1991. }
  1992. function deSelect() {
  1993. if (window.getSelection) {
  1994. window.getSelection().removeAllRanges();
  1995. } else {
  1996. document.selection.empty();
  1997. }
  1998. }
  1999. function selectRange($list, $select, $from) {
  2000. $list.removeClass('active');
  2001. if ($from) {
  2002. var a = parseInt($select.attr('rel').substr(1));
  2003. var b = parseInt($from.attr('rel').substr(1));
  2004. var c;
  2005. if (a != b) {
  2006. if (a > b) {
  2007. c = a;
  2008. a = b;
  2009. b = c;
  2010. }
  2011. var classes = [];
  2012. for (var i = a; i <= b; i++) {
  2013. classes.push('.L' + i);
  2014. }
  2015. $list.filter(classes.join(',')).addClass('active');
  2016. changeHash('#L' + a + '-' + 'L' + b);
  2017. return
  2018. }
  2019. }
  2020. $select.addClass('active');
  2021. changeHash('#' + $select.attr('rel'));
  2022. }
  2023. $(function () {
  2024. // Warn users that try to leave a page after entering data into a form.
  2025. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2026. if ($('.user.signin').length === 0) {
  2027. $('form:not(.ignore-dirty)').areYouSure();
  2028. }
  2029. // Parse SSH Key
  2030. $("#ssh-key-content").on('change paste keyup',function(){
  2031. var arrays = $(this).val().split(" ");
  2032. var $title = $("#ssh-key-title")
  2033. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  2034. $title.val(arrays[2]);
  2035. }
  2036. });
  2037. });
  2038. function showDeletePopup() {
  2039. var $this = $(this);
  2040. var filter = "";
  2041. if ($this.attr("id")) {
  2042. filter += "#" + $this.attr("id")
  2043. }
  2044. var dialog = $('.delete.modal' + filter);
  2045. dialog.find('.name').text($this.data('name'));
  2046. dialog.modal({
  2047. closable: false,
  2048. onApprove: function() {
  2049. if ($this.data('type') == "form") {
  2050. $($this.data('form')).submit();
  2051. return;
  2052. }
  2053. $.post($this.data('url'), {
  2054. "_csrf": csrf,
  2055. "id": $this.data("id")
  2056. }).done(function(data) {
  2057. window.location.href = data.redirect;
  2058. });
  2059. }
  2060. }).modal('show');
  2061. return false;
  2062. }
  2063. function initVueComponents(){
  2064. var vueDelimeters = ['${', '}'];
  2065. Vue.component('repo-search', {
  2066. delimiters: vueDelimeters,
  2067. props: {
  2068. searchLimit: {
  2069. type: Number,
  2070. default: 10
  2071. },
  2072. suburl: {
  2073. type: String,
  2074. required: true
  2075. },
  2076. uid: {
  2077. type: Number,
  2078. required: true
  2079. },
  2080. organizations: {
  2081. type: Array,
  2082. default: []
  2083. },
  2084. isOrganization: {
  2085. type: Boolean,
  2086. default: true
  2087. },
  2088. canCreateOrganization: {
  2089. type: Boolean,
  2090. default: false
  2091. },
  2092. organizationsTotalCount: {
  2093. type: Number,
  2094. default: 0
  2095. },
  2096. moreReposLink: {
  2097. type: String,
  2098. default: ''
  2099. }
  2100. },
  2101. data: function() {
  2102. return {
  2103. tab: 'repos',
  2104. repos: [],
  2105. reposTotalCount: 0,
  2106. reposFilter: 'all',
  2107. searchQuery: '',
  2108. isLoading: false,
  2109. repoTypes: {
  2110. 'all': {
  2111. count: 0,
  2112. searchMode: '',
  2113. },
  2114. 'forks': {
  2115. count: 0,
  2116. searchMode: 'fork',
  2117. },
  2118. 'mirrors': {
  2119. count: 0,
  2120. searchMode: 'mirror',
  2121. },
  2122. 'sources': {
  2123. count: 0,
  2124. searchMode: 'source',
  2125. },
  2126. 'collaborative': {
  2127. count: 0,
  2128. searchMode: 'collaborative',
  2129. },
  2130. }
  2131. }
  2132. },
  2133. computed: {
  2134. showMoreReposLink: function() {
  2135. return this.repos.length > 0 && this.repos.length < this.repoTypes[this.reposFilter].count;
  2136. },
  2137. searchURL: function() {
  2138. return this.suburl + '/api/v1/repos/search?sort=updated&order=desc&uid=' + this.uid + '&q=' + this.searchQuery
  2139. + '&limit=' + this.searchLimit + '&mode=' + this.repoTypes[this.reposFilter].searchMode
  2140. + (this.reposFilter !== 'all' ? '&exclusive=1' : '');
  2141. },
  2142. repoTypeCount: function() {
  2143. return this.repoTypes[this.reposFilter].count;
  2144. }
  2145. },
  2146. mounted: function() {
  2147. this.searchRepos(this.reposFilter);
  2148. var self = this;
  2149. Vue.nextTick(function() {
  2150. self.$refs.search.focus();
  2151. });
  2152. },
  2153. methods: {
  2154. changeTab: function(t) {
  2155. this.tab = t;
  2156. },
  2157. changeReposFilter: function(filter) {
  2158. this.reposFilter = filter;
  2159. this.repos = [];
  2160. this.repoTypes[filter].count = 0;
  2161. this.searchRepos(filter);
  2162. },
  2163. showRepo: function(repo, filter) {
  2164. switch (filter) {
  2165. case 'sources':
  2166. return repo.owner.id == this.uid && !repo.mirror && !repo.fork;
  2167. case 'forks':
  2168. return repo.owner.id == this.uid && !repo.mirror && repo.fork;
  2169. case 'mirrors':
  2170. return repo.mirror;
  2171. case 'collaborative':
  2172. return repo.owner.id != this.uid && !repo.mirror;
  2173. default:
  2174. return true;
  2175. }
  2176. },
  2177. searchRepos: function(reposFilter) {
  2178. var self = this;
  2179. this.isLoading = true;
  2180. var searchedMode = this.repoTypes[reposFilter].searchMode;
  2181. var searchedURL = this.searchURL;
  2182. var searchedQuery = this.searchQuery;
  2183. $.getJSON(searchedURL, function(result, _textStatus, request) {
  2184. if (searchedURL == self.searchURL) {
  2185. self.repos = result.data;
  2186. var count = request.getResponseHeader('X-Total-Count');
  2187. if (searchedQuery === '' && searchedMode === '') {
  2188. self.reposTotalCount = count;
  2189. }
  2190. self.repoTypes[reposFilter].count = count;
  2191. }
  2192. }).always(function() {
  2193. if (searchedURL == self.searchURL) {
  2194. self.isLoading = false;
  2195. }
  2196. });
  2197. },
  2198. repoClass: function(repo) {
  2199. if (repo.fork) {
  2200. return 'octicon octicon-repo-forked';
  2201. } else if (repo.mirror) {
  2202. return 'octicon octicon-repo-clone';
  2203. } else if (repo.private) {
  2204. return 'octicon octicon-lock';
  2205. } else {
  2206. return 'octicon octicon-repo';
  2207. }
  2208. }
  2209. }
  2210. })
  2211. }
  2212. function initCtrlEnterSubmit() {
  2213. $(".js-quick-submit").keydown(function(e) {
  2214. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
  2215. $(this).closest("form").submit();
  2216. }
  2217. });
  2218. }
  2219. function initVueApp() {
  2220. var el = document.getElementById('app');
  2221. if (!el) {
  2222. return;
  2223. }
  2224. initVueComponents();
  2225. new Vue({
  2226. delimiters: ['${', '}'],
  2227. el: el,
  2228. data: {
  2229. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  2230. suburl: document.querySelector('meta[name=_suburl]').content,
  2231. uid: document.querySelector('meta[name=_context_uid]').content,
  2232. },
  2233. });
  2234. }
  2235. function timeAddManual() {
  2236. $('.mini.modal')
  2237. .modal({
  2238. duration: 200,
  2239. onApprove: function() {
  2240. $('#add_time_manual_form').submit();
  2241. }
  2242. }).modal('show')
  2243. ;
  2244. }
  2245. function toggleStopwatch() {
  2246. $("#toggle_stopwatch_form").submit();
  2247. }
  2248. function cancelStopwatch() {
  2249. $("#cancel_stopwatch_form").submit();
  2250. }
  2251. function initHeatmap(appElementId, heatmapUser, locale) {
  2252. var el = document.getElementById(appElementId);
  2253. if (!el) {
  2254. return;
  2255. }
  2256. locale = locale || {};
  2257. locale.contributions = locale.contributions || 'contributions';
  2258. locale.no_contributions = locale.no_contributions || 'No contributions';
  2259. var vueDelimeters = ['${', '}'];
  2260. Vue.component('activity-heatmap', {
  2261. delimiters: vueDelimeters,
  2262. props: {
  2263. user: {
  2264. type: String,
  2265. required: true
  2266. },
  2267. suburl: {
  2268. type: String,
  2269. required: true
  2270. },
  2271. locale: {
  2272. type: Object,
  2273. required: true
  2274. }
  2275. },
  2276. data: function () {
  2277. return {
  2278. isLoading: true,
  2279. colorRange: [],
  2280. endDate: null,
  2281. values: []
  2282. };
  2283. },
  2284. mounted: function() {
  2285. this.colorRange = [
  2286. this.getColor(0),
  2287. this.getColor(1),
  2288. this.getColor(2),
  2289. this.getColor(3),
  2290. this.getColor(4),
  2291. this.getColor(5)
  2292. ];
  2293. this.endDate = new Date();
  2294. this.loadHeatmap(this.user);
  2295. },
  2296. methods: {
  2297. loadHeatmap: function(userName) {
  2298. var self = this;
  2299. $.get(this.suburl + '/api/v1/users/' + userName + '/heatmap', function(chartRawData) {
  2300. var chartData = [];
  2301. for (var i = 0; i < chartRawData.length; i++) {
  2302. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2303. }
  2304. self.values = chartData;
  2305. self.isLoading = false;
  2306. });
  2307. },
  2308. getColor: function(idx) {
  2309. var el = document.createElement('div');
  2310. el.className = 'heatmap-color-' + idx;
  2311. document.body.appendChild(el);
  2312. var color = getComputedStyle(el).backgroundColor;
  2313. document.body.removeChild(el);
  2314. return color;
  2315. }
  2316. },
  2317. 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" />'
  2318. });
  2319. new Vue({
  2320. delimiters: vueDelimeters,
  2321. el: el,
  2322. data: {
  2323. suburl: document.querySelector('meta[name=_suburl]').content,
  2324. heatmapUser: heatmapUser,
  2325. locale: locale
  2326. },
  2327. });
  2328. }
  2329. function initFilterBranchTagDropdown(selector) {
  2330. $(selector).each(function() {
  2331. var $dropdown = $(this);
  2332. var $data = $dropdown.find('.data');
  2333. var data = {
  2334. items: [],
  2335. mode: $data.data('mode'),
  2336. searchTerm: '',
  2337. noResults: '',
  2338. canCreateBranch: false,
  2339. menuVisible: false,
  2340. active: 0
  2341. };
  2342. $data.find('.item').each(function() {
  2343. data.items.push({
  2344. name: $(this).text(),
  2345. url: $(this).data('url'),
  2346. branch: $(this).hasClass('branch'),
  2347. tag: $(this).hasClass('tag'),
  2348. selected: $(this).hasClass('selected')
  2349. });
  2350. });
  2351. $data.remove();
  2352. new Vue({
  2353. delimiters: ['${', '}'],
  2354. el: this,
  2355. data: data,
  2356. beforeMount: function () {
  2357. var vm = this;
  2358. this.noResults = vm.$el.getAttribute('data-no-results');
  2359. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2360. document.body.addEventListener('click', function(event) {
  2361. if (vm.$el.contains(event.target)) {
  2362. return;
  2363. }
  2364. if (vm.menuVisible) {
  2365. Vue.set(vm, 'menuVisible', false);
  2366. }
  2367. });
  2368. },
  2369. watch: {
  2370. menuVisible: function(visible) {
  2371. if (visible) {
  2372. this.focusSearchField();
  2373. }
  2374. }
  2375. },
  2376. computed: {
  2377. filteredItems: function() {
  2378. var vm = this;
  2379. var items = vm.items.filter(function (item) {
  2380. return ((vm.mode === 'branches' && item.branch)
  2381. || (vm.mode === 'tags' && item.tag))
  2382. && (!vm.searchTerm
  2383. || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2384. });
  2385. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2386. return items;
  2387. },
  2388. showNoResults: function() {
  2389. return this.filteredItems.length === 0
  2390. && !this.showCreateNewBranch;
  2391. },
  2392. showCreateNewBranch: function() {
  2393. var vm = this;
  2394. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2395. return false;
  2396. }
  2397. return vm.items.filter(function (item) {
  2398. return item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  2399. }).length === 0;
  2400. }
  2401. },
  2402. methods: {
  2403. selectItem: function(item) {
  2404. var prev = this.getSelected();
  2405. if (prev !== null) {
  2406. prev.selected = false;
  2407. }
  2408. item.selected = true;
  2409. window.location.href = item.url;
  2410. },
  2411. createNewBranch: function() {
  2412. if (!this.showCreateNewBranch) {
  2413. return;
  2414. }
  2415. this.$refs.newBranchForm.submit();
  2416. },
  2417. focusSearchField: function() {
  2418. var vm = this;
  2419. Vue.nextTick(function() {
  2420. vm.$refs.searchField.focus();
  2421. });
  2422. },
  2423. getSelected: function() {
  2424. for (var i = 0, j = this.items.length; i < j; ++i) {
  2425. if (this.items[i].selected)
  2426. return this.items[i];
  2427. }
  2428. return null;
  2429. },
  2430. getSelectedIndexInFiltered: function() {
  2431. for (var i = 0, j = this.filteredItems.length; i < j; ++i) {
  2432. if (this.filteredItems[i].selected)
  2433. return i;
  2434. }
  2435. return -1;
  2436. },
  2437. scrollToActive: function() {
  2438. var el = this.$refs['listItem' + this.active];
  2439. if (!el || el.length === 0) {
  2440. return;
  2441. }
  2442. if (Array.isArray(el)) {
  2443. el = el[0];
  2444. }
  2445. var cont = this.$refs.scrollContainer;
  2446. if (el.offsetTop < cont.scrollTop) {
  2447. cont.scrollTop = el.offsetTop;
  2448. }
  2449. else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2450. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2451. }
  2452. },
  2453. keydown: function(event) {
  2454. var vm = this;
  2455. if (event.keyCode === 40) {
  2456. // arrow down
  2457. event.preventDefault();
  2458. if (vm.active === -1) {
  2459. vm.active = vm.getSelectedIndexInFiltered();
  2460. }
  2461. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2462. return;
  2463. }
  2464. vm.active++;
  2465. vm.scrollToActive();
  2466. }
  2467. if (event.keyCode === 38) {
  2468. // arrow up
  2469. event.preventDefault();
  2470. if (vm.active === -1) {
  2471. vm.active = vm.getSelectedIndexInFiltered();
  2472. }
  2473. if (vm.active <= 0) {
  2474. return;
  2475. }
  2476. vm.active--;
  2477. vm.scrollToActive();
  2478. }
  2479. if (event.keyCode == 13) {
  2480. // enter
  2481. event.preventDefault();
  2482. if (vm.active >= vm.filteredItems.length) {
  2483. vm.createNewBranch();
  2484. } else if (vm.active >= 0) {
  2485. vm.selectItem(vm.filteredItems[vm.active]);
  2486. }
  2487. }
  2488. if (event.keyCode == 27) {
  2489. // escape
  2490. event.preventDefault();
  2491. vm.menuVisible = false;
  2492. }
  2493. }
  2494. }
  2495. });
  2496. });
  2497. }
  2498. $(".commit-button").click(function() {
  2499. $(this).parent().find('.commit-body').toggle();
  2500. });
  2501. function initNavbarContentToggle() {
  2502. var content = $('#navbar');
  2503. var toggle = $('#navbar-expand-toggle');
  2504. var isExpanded = false;
  2505. toggle.click(function() {
  2506. isExpanded = !isExpanded;
  2507. if (isExpanded) {
  2508. content.addClass('shown');
  2509. toggle.addClass('active');
  2510. }
  2511. else {
  2512. content.removeClass('shown');
  2513. toggle.removeClass('active');
  2514. }
  2515. });
  2516. }
  2517. function initTopicbar() {
  2518. var mgrBtn = $("#manage_topic"),
  2519. editDiv = $("#topic_edit"),
  2520. viewDiv = $("#repo-topics"),
  2521. saveBtn = $("#save_topic"),
  2522. topicDropdown = $('#topic_edit .dropdown'),
  2523. topicForm = $('#topic_edit.ui.form'),
  2524. topicPrompts;
  2525. mgrBtn.click(function() {
  2526. viewDiv.hide();
  2527. editDiv.css('display', ''); // show Semantic UI Grid
  2528. });
  2529. function getPrompts() {
  2530. var hidePrompt = $("div.hide#validate_prompt"),
  2531. prompts = {
  2532. countPrompt: hidePrompt.children('#count_prompt').text(),
  2533. formatPrompt: hidePrompt.children('#format_prompt').text()
  2534. };
  2535. hidePrompt.remove();
  2536. return prompts;
  2537. }
  2538. saveBtn.click(function() {
  2539. var topics = $("input[name=topics]").val();
  2540. $.post(saveBtn.data('link'), {
  2541. "_csrf": csrf,
  2542. "topics": topics
  2543. }, function(_data, _textStatus, xhr){
  2544. if (xhr.responseJSON.status === 'ok') {
  2545. viewDiv.children(".topic").remove();
  2546. if (topics.length) {
  2547. var topicArray = topics.split(",");
  2548. var last = viewDiv.children("a").last();
  2549. for (var i=0; i < topicArray.length; i++) {
  2550. $('<div class="ui small label topic" style="cursor:pointer;">'+topicArray[i]+'</div>').insertBefore(last)
  2551. }
  2552. }
  2553. editDiv.css('display', 'none');
  2554. viewDiv.show();
  2555. }
  2556. }).fail(function(xhr){
  2557. if (xhr.status === 422) {
  2558. if (xhr.responseJSON.invalidTopics.length > 0) {
  2559. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2560. var invalidTopics = xhr.responseJSON.invalidTopics,
  2561. topicLables = topicDropdown.children('a.ui.label');
  2562. topics.split(',').forEach(function(value, index) {
  2563. for (var i=0; i < invalidTopics.length; i++) {
  2564. if (invalidTopics[i] === value) {
  2565. topicLables.eq(index).removeClass("green").addClass("red");
  2566. }
  2567. }
  2568. });
  2569. } else {
  2570. topicPrompts.countPrompt = xhr.responseJSON.message;
  2571. }
  2572. }
  2573. }).always(function() {
  2574. topicForm.form('validate form');
  2575. });
  2576. });
  2577. topicDropdown.dropdown({
  2578. allowAdditions: true,
  2579. forceSelection: false,
  2580. fields: { name: "description", value: "data-value" },
  2581. saveRemoteData: false,
  2582. label: {
  2583. transition : 'horizontal flip',
  2584. duration : 200,
  2585. variation : false,
  2586. blue : true,
  2587. basic: true,
  2588. },
  2589. className: {
  2590. label: 'ui small label'
  2591. },
  2592. apiSettings: {
  2593. url: suburl + '/api/v1/topics/search?q={query}',
  2594. throttle: 500,
  2595. cache: false,
  2596. onResponse: function(res) {
  2597. let formattedResponse = {
  2598. success: false,
  2599. results: [],
  2600. };
  2601. const stripTags = function (text) {
  2602. return text.replace(/<[^>]*>?/gm, "");
  2603. };
  2604. let query = stripTags(this.urlData.query.trim());
  2605. let found_query = false;
  2606. let current_topics = [];
  2607. topicDropdown.find('div.label.visible.topic,a.label.visible').each(function(_,e){ current_topics.push(e.dataset.value); });
  2608. if (res.topics) {
  2609. let found = false;
  2610. for (let i=0;i < res.topics.length;i++) {
  2611. // skip currently added tags
  2612. if (current_topics.indexOf(res.topics[i].Name) != -1){
  2613. continue;
  2614. }
  2615. if (res.topics[i].Name.toLowerCase() === query.toLowerCase()){
  2616. found_query = true;
  2617. }
  2618. formattedResponse.results.push({"description": res.topics[i].Name, "data-value": res.topics[i].Name});
  2619. found = true;
  2620. }
  2621. formattedResponse.success = found;
  2622. }
  2623. if (query.length > 0 && !found_query){
  2624. formattedResponse.success = true;
  2625. formattedResponse.results.unshift({"description": query, "data-value": query});
  2626. } else if (query.length > 0 && found_query) {
  2627. formattedResponse.results.sort(function(a, b){
  2628. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  2629. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  2630. if (a.description > b.description) return -1;
  2631. if (a.description < b.description) return 1;
  2632. return 0;
  2633. });
  2634. }
  2635. return formattedResponse;
  2636. },
  2637. },
  2638. onLabelCreate: function(value) {
  2639. value = value.toLowerCase().trim();
  2640. this.attr("data-value", value).contents().first().replaceWith(value);
  2641. return $(this);
  2642. },
  2643. onAdd: function(addedValue, _addedText, $addedChoice) {
  2644. addedValue = addedValue.toLowerCase().trim();
  2645. $($addedChoice).attr('data-value', addedValue);
  2646. $($addedChoice).attr('data-text', addedValue);
  2647. }
  2648. });
  2649. $.fn.form.settings.rules.validateTopic = function(_values, regExp) {
  2650. var topics = topicDropdown.children('a.ui.label'),
  2651. status = topics.length === 0 || topics.last().attr("data-value").match(regExp);
  2652. if (!status) {
  2653. topics.last().removeClass("green").addClass("red");
  2654. }
  2655. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2656. };
  2657. topicPrompts = getPrompts();
  2658. topicForm.form({
  2659. on: 'change',
  2660. inline : true,
  2661. fields: {
  2662. topics: {
  2663. identifier: 'topics',
  2664. rules: [
  2665. {
  2666. type: 'validateTopic',
  2667. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2668. prompt: topicPrompts.formatPrompt
  2669. },
  2670. {
  2671. type: 'maxCount[25]',
  2672. prompt: topicPrompts.countPrompt
  2673. }
  2674. ]
  2675. },
  2676. }
  2677. });
  2678. }
  2679. function toggleDeadlineForm() {
  2680. $('#deadlineForm').fadeToggle(150);
  2681. }
  2682. function setDeadline() {
  2683. var deadline = $('#deadlineDate').val();
  2684. updateDeadline(deadline);
  2685. }
  2686. function updateDeadline(deadlineString) {
  2687. $('#deadline-err-invalid-date').hide();
  2688. $('#deadline-loader').addClass('loading');
  2689. var realDeadline = null;
  2690. if (deadlineString !== '') {
  2691. var newDate = Date.parse(deadlineString)
  2692. if (isNaN(newDate)) {
  2693. $('#deadline-loader').removeClass('loading');
  2694. $('#deadline-err-invalid-date').show();
  2695. return false;
  2696. }
  2697. realDeadline = new Date(newDate);
  2698. }
  2699. $.ajax($('#update-issue-deadline-form').attr('action') + '/deadline', {
  2700. data: JSON.stringify({
  2701. 'due_date': realDeadline,
  2702. }),
  2703. headers: {
  2704. 'X-Csrf-Token': csrf,
  2705. 'X-Remote': true,
  2706. },
  2707. contentType: 'application/json',
  2708. type: 'POST',
  2709. success: function () {
  2710. reload();
  2711. },
  2712. error: function () {
  2713. $('#deadline-loader').removeClass('loading');
  2714. $('#deadline-err-invalid-date').show();
  2715. }
  2716. });
  2717. }
  2718. function deleteDependencyModal(id, type) {
  2719. $('.remove-dependency')
  2720. .modal({
  2721. closable: false,
  2722. duration: 200,
  2723. onApprove: function () {
  2724. $('#removeDependencyID').val(id);
  2725. $('#dependencyType').val(type);
  2726. $('#removeDependencyForm').submit();
  2727. }
  2728. }).modal('show')
  2729. ;
  2730. }
  2731. function initIssueList() {
  2732. var repolink = $('#repolink').val();
  2733. $('#new-dependency-drop-list')
  2734. .dropdown({
  2735. apiSettings: {
  2736. url: suburl + '/api/v1/repos/' + repolink + '/issues?q={query}',
  2737. onResponse: function(response) {
  2738. var filteredResponse = {'success': true, 'results': []};
  2739. var currIssueId = $('#new-dependency-drop-list').data('issue-id');
  2740. // Parse the response from the api to work with our dropdown
  2741. $.each(response, function(_i, issue) {
  2742. // Don't list current issue in the dependency list.
  2743. if(issue.id === currIssueId) {
  2744. return;
  2745. }
  2746. filteredResponse.results.push({
  2747. 'name' : '#' + issue.number + '&nbsp;' + htmlEncode(issue.title),
  2748. 'value' : issue.id
  2749. });
  2750. });
  2751. return filteredResponse;
  2752. },
  2753. cache: false,
  2754. },
  2755. fullTextSearch: true
  2756. })
  2757. ;
  2758. }
  2759. function cancelCodeComment(btn) {
  2760. var form = $(btn).closest("form");
  2761. if(form.length > 0 && form.hasClass('comment-form')) {
  2762. form.addClass('hide');
  2763. form.parent().find('button.comment-form-reply').show();
  2764. } else {
  2765. form.closest('.comment-code-cloud').remove()
  2766. }
  2767. }
  2768. function onOAuthLoginClick() {
  2769. var oauthLoader = $('#oauth2-login-loader');
  2770. var oauthNav = $('#oauth2-login-navigator');
  2771. oauthNav.hide();
  2772. oauthLoader.removeClass('disabled');
  2773. setTimeout(function(){
  2774. // recover previous content to let user try again
  2775. // usually redirection will be performed before this action
  2776. oauthLoader.addClass('disabled');
  2777. oauthNav.show();
  2778. },5000);
  2779. }