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

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