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

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