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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122
  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. $('#commit-button').text($(this).attr('button_text'));
  1187. });
  1188. const $editFilename = $("#file-name");
  1189. $editFilename.keyup(function (e) {
  1190. const $section = $('.breadcrumb span.section');
  1191. const $divider = $('.breadcrumb div.divider');
  1192. let value;
  1193. let parts;
  1194. if (e.keyCode == 8) {
  1195. if ($(this).getCursorPosition() == 0) {
  1196. if ($section.length > 0) {
  1197. value = $section.last().find('a').text();
  1198. $(this).val(value + $(this).val());
  1199. $(this)[0].setSelectionRange(value.length, value.length);
  1200. $section.last().remove();
  1201. $divider.last().remove();
  1202. }
  1203. }
  1204. }
  1205. if (e.keyCode == 191) {
  1206. parts = $(this).val().split('/');
  1207. for (let i = 0; i < parts.length; ++i) {
  1208. value = parts[i];
  1209. if (i < parts.length - 1) {
  1210. if (value.length) {
  1211. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  1212. $('<div class="divider"> / </div>').insertBefore($(this));
  1213. }
  1214. }
  1215. else {
  1216. $(this).val(value);
  1217. }
  1218. $(this)[0].setSelectionRange(0, 0);
  1219. }
  1220. }
  1221. parts = [];
  1222. $('.breadcrumb span.section').each(function () {
  1223. const element = $(this);
  1224. if (element.find('a').length) {
  1225. parts.push(element.find('a').text());
  1226. } else {
  1227. parts.push(element.text());
  1228. }
  1229. });
  1230. if ($(this).val())
  1231. parts.push($(this).val());
  1232. $('#tree_path').val(parts.join('/'));
  1233. }).trigger('keyup');
  1234. const $editArea = $('.repository.editor textarea#edit_area');
  1235. if (!$editArea.length)
  1236. return;
  1237. const markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  1238. const lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  1239. $editFilename.on("keyup", function () {
  1240. const val = $editFilename.val();
  1241. let mode, spec, extension, extWithDot, dataUrl, apiCall;
  1242. extension = extWithDot = "";
  1243. const m = /.+\.([^.]+)$/.exec(val);
  1244. if (m) {
  1245. extension = m[1];
  1246. extWithDot = "." + extension;
  1247. }
  1248. const info = CodeMirror.findModeByExtension(extension);
  1249. const previewLink = $('a[data-tab=preview]');
  1250. if (info) {
  1251. mode = info.mode;
  1252. spec = info.mime;
  1253. apiCall = mode;
  1254. }
  1255. else {
  1256. apiCall = extension
  1257. }
  1258. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  1259. dataUrl = previewLink.data('url');
  1260. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  1261. previewLink.show();
  1262. }
  1263. else {
  1264. previewLink.hide();
  1265. }
  1266. // If this file is a Markdown extensions, we will load that editor and return
  1267. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  1268. if (setSimpleMDE($editArea)) {
  1269. return;
  1270. }
  1271. }
  1272. // Else we are going to use CodeMirror
  1273. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  1274. return;
  1275. }
  1276. if (mode) {
  1277. codeMirrorEditor.setOption("mode", spec);
  1278. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  1279. }
  1280. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  1281. codeMirrorEditor.setOption("lineWrapping", true);
  1282. }
  1283. else {
  1284. codeMirrorEditor.setOption("lineWrapping", false);
  1285. }
  1286. // get the filename without any folder
  1287. let value = $editFilename.val();
  1288. if (value.length === 0) {
  1289. return;
  1290. }
  1291. value = value.split('/');
  1292. value = value[value.length - 1];
  1293. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  1294. if (editorconfig.indent_style === 'tab') {
  1295. codeMirrorEditor.setOption("indentWithTabs", true);
  1296. codeMirrorEditor.setOption('extraKeys', {});
  1297. } else {
  1298. codeMirrorEditor.setOption("indentWithTabs", false);
  1299. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  1300. // - https://github.com/codemirror/CodeMirror/issues/988
  1301. // - https://codemirror.net/doc/manual.html#keymaps
  1302. codeMirrorEditor.setOption('extraKeys', {
  1303. Tab: function(cm) {
  1304. const spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  1305. cm.replaceSelection(spaces);
  1306. }
  1307. });
  1308. }
  1309. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  1310. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  1311. });
  1312. }).trigger('keyup');
  1313. }
  1314. function initOrganization() {
  1315. if ($('.organization').length == 0) {
  1316. return;
  1317. }
  1318. // Options
  1319. if ($('.organization.settings.options').length > 0) {
  1320. $('#org_name').keyup(function () {
  1321. const $prompt = $('#org-name-change-prompt');
  1322. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  1323. $prompt.show();
  1324. } else {
  1325. $prompt.hide();
  1326. }
  1327. });
  1328. }
  1329. }
  1330. function initUserSettings() {
  1331. // Options
  1332. if ($('.user.settings.profile').length > 0) {
  1333. $('#username').keyup(function () {
  1334. const $prompt = $('#name-change-prompt');
  1335. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1336. $prompt.show();
  1337. } else {
  1338. $prompt.hide();
  1339. }
  1340. });
  1341. }
  1342. }
  1343. function initWebhook() {
  1344. if ($('.new.webhook').length == 0) {
  1345. return;
  1346. }
  1347. $('.events.checkbox input').change(function () {
  1348. if ($(this).is(':checked')) {
  1349. $('.events.fields').show();
  1350. }
  1351. });
  1352. $('.non-events.checkbox input').change(function () {
  1353. if ($(this).is(':checked')) {
  1354. $('.events.fields').hide();
  1355. }
  1356. });
  1357. const updateContentType = function () {
  1358. const visible = $('#http_method').val() === 'POST';
  1359. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1360. };
  1361. updateContentType();
  1362. $('#http_method').change(function () {
  1363. updateContentType();
  1364. });
  1365. // Test delivery
  1366. $('#test-delivery').click(function () {
  1367. const $this = $(this);
  1368. $this.addClass('loading disabled');
  1369. $.post($this.data('link'), {
  1370. "_csrf": csrf
  1371. }).done(
  1372. setTimeout(function () {
  1373. window.location.href = $this.data('redirect');
  1374. }, 5000)
  1375. )
  1376. });
  1377. }
  1378. function initAdmin() {
  1379. if ($('.admin').length == 0) {
  1380. return;
  1381. }
  1382. // New user
  1383. if ($('.admin.new.user').length > 0 ||
  1384. $('.admin.edit.user').length > 0) {
  1385. $('#login_type').change(function () {
  1386. if ($(this).val().substring(0, 1) == '0') {
  1387. $('#login_name').removeAttr('required');
  1388. $('.non-local').hide();
  1389. $('.local').show();
  1390. $('#user_name').focus();
  1391. if ($(this).data('password') == "required") {
  1392. $('#password').attr('required', 'required');
  1393. }
  1394. } else {
  1395. $('#login_name').attr('required', 'required');
  1396. $('.non-local').show();
  1397. $('.local').hide();
  1398. $('#login_name').focus();
  1399. $('#password').removeAttr('required');
  1400. }
  1401. });
  1402. }
  1403. function onSecurityProtocolChange() {
  1404. if ($('#security_protocol').val() > 0) {
  1405. $('.has-tls').show();
  1406. } else {
  1407. $('.has-tls').hide();
  1408. }
  1409. }
  1410. function onUsePagedSearchChange() {
  1411. if ($('#use_paged_search').prop('checked')) {
  1412. $('.search-page-size').show()
  1413. .find('input').attr('required', 'required');
  1414. } else {
  1415. $('.search-page-size').hide()
  1416. .find('input').removeAttr('required');
  1417. }
  1418. }
  1419. function onOAuth2Change() {
  1420. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1421. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1422. const provider = $('#oauth2_provider').val();
  1423. switch (provider) {
  1424. case 'github':
  1425. case 'gitlab':
  1426. $('.oauth2_use_custom_url').show();
  1427. break;
  1428. case 'openidConnect':
  1429. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1430. $('.open_id_connect_auto_discovery_url').show();
  1431. break;
  1432. }
  1433. onOAuth2UseCustomURLChange();
  1434. }
  1435. function onOAuth2UseCustomURLChange() {
  1436. const provider = $('#oauth2_provider').val();
  1437. $('.oauth2_use_custom_url_field').hide();
  1438. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1439. if ($('#oauth2_use_custom_url').is(':checked')) {
  1440. if (!$('#oauth2_token_url').val()) {
  1441. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  1442. }
  1443. if (!$('#oauth2_auth_url').val()) {
  1444. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  1445. }
  1446. if (!$('#oauth2_profile_url').val()) {
  1447. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  1448. }
  1449. if (!$('#oauth2_email_url').val()) {
  1450. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  1451. }
  1452. switch (provider) {
  1453. case 'github':
  1454. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1455. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1456. break;
  1457. case 'gitlab':
  1458. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1459. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1460. $('#oauth2_email_url').val('');
  1461. break;
  1462. }
  1463. }
  1464. }
  1465. // New authentication
  1466. if ($('.admin.new.authentication').length > 0) {
  1467. $('#auth_type').change(function () {
  1468. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls .search-page-size').hide();
  1469. $('.ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required]').removeAttr('required');
  1470. $('.binddnrequired').removeClass("required");
  1471. const authType = $(this).val();
  1472. switch (authType) {
  1473. case '2': // LDAP
  1474. $('.ldap').show();
  1475. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1476. $('.binddnrequired').addClass("required");
  1477. break;
  1478. case '3': // SMTP
  1479. $('.smtp').show();
  1480. $('.has-tls').show();
  1481. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1482. break;
  1483. case '4': // PAM
  1484. $('.pam').show();
  1485. $('.pam input').attr('required', 'required');
  1486. break;
  1487. case '5': // LDAP
  1488. $('.dldap').show();
  1489. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1490. break;
  1491. case '6': // OAuth2
  1492. $('.oauth2').show();
  1493. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1494. onOAuth2Change();
  1495. break;
  1496. }
  1497. if (authType == '2' || authType == '5') {
  1498. onSecurityProtocolChange()
  1499. }
  1500. if (authType == '2') {
  1501. onUsePagedSearchChange();
  1502. }
  1503. });
  1504. $('#auth_type').change();
  1505. $('#security_protocol').change(onSecurityProtocolChange);
  1506. $('#use_paged_search').change(onUsePagedSearchChange);
  1507. $('#oauth2_provider').change(onOAuth2Change);
  1508. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1509. }
  1510. // Edit authentication
  1511. if ($('.admin.edit.authentication').length > 0) {
  1512. const authType = $('#auth_type').val();
  1513. if (authType == '2' || authType == '5') {
  1514. $('#security_protocol').change(onSecurityProtocolChange);
  1515. if (authType == '2') {
  1516. $('#use_paged_search').change(onUsePagedSearchChange);
  1517. }
  1518. } else if (authType == '6') {
  1519. $('#oauth2_provider').change(onOAuth2Change);
  1520. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1521. onOAuth2Change();
  1522. }
  1523. }
  1524. // Notice
  1525. if ($('.admin.notice')) {
  1526. const $detailModal = $('#detail-modal');
  1527. // Attach view detail modals
  1528. $('.view-detail').click(function () {
  1529. $detailModal.find('.content p').text($(this).data('content'));
  1530. $detailModal.modal('show');
  1531. return false;
  1532. });
  1533. // Select actions
  1534. const $checkboxes = $('.select.table .ui.checkbox');
  1535. $('.select.action').click(function () {
  1536. switch ($(this).data('action')) {
  1537. case 'select-all':
  1538. $checkboxes.checkbox('check');
  1539. break;
  1540. case 'deselect-all':
  1541. $checkboxes.checkbox('uncheck');
  1542. break;
  1543. case 'inverse':
  1544. $checkboxes.checkbox('toggle');
  1545. break;
  1546. }
  1547. });
  1548. $('#delete-selection').click(function () {
  1549. const $this = $(this);
  1550. $this.addClass("loading disabled");
  1551. const ids = [];
  1552. $checkboxes.each(function () {
  1553. if ($(this).checkbox('is checked')) {
  1554. ids.push($(this).data('id'));
  1555. }
  1556. });
  1557. $.post($this.data('link'), {
  1558. "_csrf": csrf,
  1559. "ids": ids
  1560. }).done(function () {
  1561. window.location.href = $this.data('redirect');
  1562. });
  1563. });
  1564. }
  1565. }
  1566. function buttonsClickOnEnter() {
  1567. $('.ui.button').keypress(function (e) {
  1568. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1569. $(this).click();
  1570. });
  1571. }
  1572. function searchUsers() {
  1573. const $searchUserBox = $('#search-user-box');
  1574. $searchUserBox.search({
  1575. minCharacters: 2,
  1576. apiSettings: {
  1577. url: suburl + '/api/v1/users/search?q={query}',
  1578. onResponse: function(response) {
  1579. const items = [];
  1580. $.each(response.data, function (_i, item) {
  1581. let title = item.login;
  1582. if (item.full_name && item.full_name.length > 0) {
  1583. title += ' (' + htmlEncode(item.full_name) + ')';
  1584. }
  1585. items.push({
  1586. title: title,
  1587. image: item.avatar_url
  1588. })
  1589. });
  1590. return { results: items }
  1591. }
  1592. },
  1593. searchFields: ['login', 'full_name'],
  1594. showNoResults: false
  1595. });
  1596. }
  1597. function searchRepositories() {
  1598. const $searchRepoBox = $('#search-repo-box');
  1599. $searchRepoBox.search({
  1600. minCharacters: 2,
  1601. apiSettings: {
  1602. url: suburl + '/api/v1/repos/search?q={query}&uid=' + $searchRepoBox.data('uid'),
  1603. onResponse: function(response) {
  1604. const items = [];
  1605. $.each(response.data, function (_i, item) {
  1606. items.push({
  1607. title: item.full_name.split("/")[1],
  1608. description: item.full_name
  1609. })
  1610. });
  1611. return { results: items }
  1612. }
  1613. },
  1614. searchFields: ['full_name'],
  1615. showNoResults: false
  1616. });
  1617. }
  1618. function initCodeView() {
  1619. if ($('.code-view .linenums').length > 0) {
  1620. $(document).on('click', '.lines-num span', function (e) {
  1621. const $select = $(this);
  1622. const $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1623. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1624. deSelect();
  1625. });
  1626. $(window).on('hashchange', function () {
  1627. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1628. const $list = $('.code-view ol.linenums > li');
  1629. let $first;
  1630. if (m) {
  1631. $first = $list.filter('.' + m[1]);
  1632. selectRange($list, $first, $list.filter('.' + m[2]));
  1633. $("html, body").scrollTop($first.offset().top - 200);
  1634. return;
  1635. }
  1636. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1637. if (m) {
  1638. $first = $list.filter('.L' + m[2]);
  1639. selectRange($list, $first);
  1640. $("html, body").scrollTop($first.offset().top - 200);
  1641. }
  1642. }).trigger('hashchange');
  1643. }
  1644. }
  1645. function initU2FAuth() {
  1646. if($('#wait-for-key').length === 0) {
  1647. return
  1648. }
  1649. u2fApi.ensureSupport()
  1650. .then(function () {
  1651. $.getJSON(suburl + '/user/u2f/challenge').success(function(req) {
  1652. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1653. .then(u2fSigned)
  1654. .catch(function (err) {
  1655. if(err === undefined) {
  1656. u2fError(1);
  1657. return
  1658. }
  1659. u2fError(err.metaData.code);
  1660. });
  1661. });
  1662. }).catch(function () {
  1663. // Fallback in case browser do not support U2F
  1664. window.location.href = suburl + "/user/two_factor"
  1665. })
  1666. }
  1667. function u2fSigned(resp) {
  1668. $.ajax({
  1669. url: suburl + '/user/u2f/sign',
  1670. type: "POST",
  1671. headers: {"X-Csrf-Token": csrf},
  1672. data: JSON.stringify(resp),
  1673. contentType: "application/json; charset=utf-8",
  1674. }).done(function(res){
  1675. window.location.replace(res);
  1676. }).fail(function () {
  1677. u2fError(1);
  1678. });
  1679. }
  1680. function u2fRegistered(resp) {
  1681. if (checkError(resp)) {
  1682. return;
  1683. }
  1684. $.ajax({
  1685. url: suburl + '/user/settings/security/u2f/register',
  1686. type: "POST",
  1687. headers: {"X-Csrf-Token": csrf},
  1688. data: JSON.stringify(resp),
  1689. contentType: "application/json; charset=utf-8",
  1690. success: function(){
  1691. reload();
  1692. },
  1693. fail: function () {
  1694. u2fError(1);
  1695. }
  1696. });
  1697. }
  1698. function checkError(resp) {
  1699. if (!('errorCode' in resp)) {
  1700. return false;
  1701. }
  1702. if (resp.errorCode === 0) {
  1703. return false;
  1704. }
  1705. u2fError(resp.errorCode);
  1706. return true;
  1707. }
  1708. function u2fError(errorType) {
  1709. const u2fErrors = {
  1710. 'browser': $('#unsupported-browser'),
  1711. 1: $('#u2f-error-1'),
  1712. 2: $('#u2f-error-2'),
  1713. 3: $('#u2f-error-3'),
  1714. 4: $('#u2f-error-4'),
  1715. 5: $('.u2f-error-5')
  1716. };
  1717. u2fErrors[errorType].removeClass('hide');
  1718. for(const type in u2fErrors){
  1719. if(type != errorType){
  1720. u2fErrors[type].addClass('hide');
  1721. }
  1722. }
  1723. $('#u2f-error').modal('show');
  1724. }
  1725. function initU2FRegister() {
  1726. $('#register-device').modal({allowMultiple: false});
  1727. $('#u2f-error').modal({allowMultiple: false});
  1728. $('#register-security-key').on('click', function(e) {
  1729. e.preventDefault();
  1730. u2fApi.ensureSupport()
  1731. .then(u2fRegisterRequest)
  1732. .catch(function() {
  1733. u2fError('browser');
  1734. })
  1735. })
  1736. }
  1737. function u2fRegisterRequest() {
  1738. $.post(suburl + "/user/settings/security/u2f/request_register", {
  1739. "_csrf": csrf,
  1740. "name": $('#nickname').val()
  1741. }).success(function(req) {
  1742. $("#nickname").closest("div.field").removeClass("error");
  1743. $('#register-device').modal('show');
  1744. if(req.registeredKeys === null) {
  1745. req.registeredKeys = []
  1746. }
  1747. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1748. .then(u2fRegistered)
  1749. .catch(function (reason) {
  1750. if(reason === undefined) {
  1751. u2fError(1);
  1752. return
  1753. }
  1754. u2fError(reason.metaData.code);
  1755. });
  1756. }).fail(function(xhr) {
  1757. if(xhr.status === 409) {
  1758. $("#nickname").closest("div.field").addClass("error");
  1759. }
  1760. });
  1761. }
  1762. function initWipTitle() {
  1763. $(".title_wip_desc > a").click(function (e) {
  1764. e.preventDefault();
  1765. const $issueTitle = $("#issue_title");
  1766. $issueTitle.focus();
  1767. const value = $issueTitle.val().trim().toUpperCase();
  1768. for (const i in wipPrefixes) {
  1769. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1770. return;
  1771. }
  1772. }
  1773. $issueTitle.val(wipPrefixes[0] + " " + $issueTitle.val());
  1774. });
  1775. }
  1776. $(document).ready(function () {
  1777. csrf = $('meta[name=_csrf]').attr("content");
  1778. suburl = $('meta[name=_suburl]').attr("content");
  1779. // Show exact time
  1780. $('.time-since').each(function () {
  1781. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  1782. });
  1783. // Semantic UI modules.
  1784. $('.dropdown:not(.custom)').dropdown();
  1785. $('.jump.dropdown').dropdown({
  1786. action: 'hide',
  1787. onShow: function () {
  1788. $('.poping.up').popup('hide');
  1789. }
  1790. });
  1791. $('.slide.up.dropdown').dropdown({
  1792. transition: 'slide up'
  1793. });
  1794. $('.upward.dropdown').dropdown({
  1795. direction: 'upward'
  1796. });
  1797. $('.ui.accordion').accordion();
  1798. $('.ui.checkbox').checkbox();
  1799. $('.ui.progress').progress({
  1800. showActivity: false
  1801. });
  1802. $('.poping.up').popup();
  1803. $('.top.menu .poping.up').popup({
  1804. onShow: function () {
  1805. if ($('.top.menu .menu.transition').hasClass('visible')) {
  1806. return false;
  1807. }
  1808. }
  1809. });
  1810. $('.tabular.menu .item').tab();
  1811. $('.tabable.menu .item').tab();
  1812. $('.toggle.button').click(function () {
  1813. $($(this).data('target')).slideToggle(100);
  1814. });
  1815. // make table <tr> element clickable like a link
  1816. $('tr[data-href]').click(function() {
  1817. window.location = $(this).data('href');
  1818. });
  1819. // Highlight JS
  1820. if (typeof hljs != 'undefined') {
  1821. const nodes = [].slice.call(document.querySelectorAll('pre code') || []);
  1822. for (let i = 0; i < nodes.length; i++) {
  1823. hljs.highlightBlock(nodes[i]);
  1824. }
  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. totalContributions: 0,
  2326. };
  2327. },
  2328. mounted: function() {
  2329. this.colorRange = [
  2330. this.getColor(0),
  2331. this.getColor(1),
  2332. this.getColor(2),
  2333. this.getColor(3),
  2334. this.getColor(4),
  2335. this.getColor(5)
  2336. ];
  2337. this.endDate = new Date();
  2338. this.loadHeatmap(this.user);
  2339. },
  2340. methods: {
  2341. loadHeatmap: function(userName) {
  2342. const self = this;
  2343. $.get(this.suburl + '/api/v1/users/' + userName + '/heatmap', function(chartRawData) {
  2344. const chartData = [];
  2345. for (let i = 0; i < chartRawData.length; i++) {
  2346. self.totalContributions += chartRawData[i].contributions;
  2347. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2348. }
  2349. self.values = chartData;
  2350. self.isLoading = false;
  2351. });
  2352. },
  2353. getColor: function(idx) {
  2354. const el = document.createElement('div');
  2355. el.className = 'heatmap-color-' + idx;
  2356. document.body.appendChild(el);
  2357. const color = getComputedStyle(el).backgroundColor;
  2358. document.body.removeChild(el);
  2359. return color;
  2360. }
  2361. },
  2362. template: '<div><div v-show="isLoading"><slot name="loading"></slot></div><h4 class="total-contributions" v-if="!isLoading"><span v-html="totalContributions"></span> total contributions in the last 12 months</h4><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" />'
  2363. });
  2364. new Vue({
  2365. delimiters: vueDelimeters,
  2366. el: el,
  2367. data: {
  2368. suburl: document.querySelector('meta[name=_suburl]').content,
  2369. heatmapUser: heatmapUser,
  2370. locale: locale
  2371. },
  2372. });
  2373. }
  2374. function initFilterBranchTagDropdown(selector) {
  2375. $(selector).each(function() {
  2376. const $dropdown = $(this);
  2377. const $data = $dropdown.find('.data');
  2378. const data = {
  2379. items: [],
  2380. mode: $data.data('mode'),
  2381. searchTerm: '',
  2382. noResults: '',
  2383. canCreateBranch: false,
  2384. menuVisible: false,
  2385. active: 0
  2386. };
  2387. $data.find('.item').each(function() {
  2388. data.items.push({
  2389. name: $(this).text(),
  2390. url: $(this).data('url'),
  2391. branch: $(this).hasClass('branch'),
  2392. tag: $(this).hasClass('tag'),
  2393. selected: $(this).hasClass('selected')
  2394. });
  2395. });
  2396. $data.remove();
  2397. new Vue({
  2398. delimiters: ['${', '}'],
  2399. el: this,
  2400. data: data,
  2401. beforeMount: function () {
  2402. const vm = this;
  2403. this.noResults = vm.$el.getAttribute('data-no-results');
  2404. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2405. document.body.addEventListener('click', function(event) {
  2406. if (vm.$el.contains(event.target)) {
  2407. return;
  2408. }
  2409. if (vm.menuVisible) {
  2410. Vue.set(vm, 'menuVisible', false);
  2411. }
  2412. });
  2413. },
  2414. watch: {
  2415. menuVisible: function(visible) {
  2416. if (visible) {
  2417. this.focusSearchField();
  2418. }
  2419. }
  2420. },
  2421. computed: {
  2422. filteredItems: function() {
  2423. const vm = this;
  2424. const items = vm.items.filter(function (item) {
  2425. return ((vm.mode === 'branches' && item.branch)
  2426. || (vm.mode === 'tags' && item.tag))
  2427. && (!vm.searchTerm
  2428. || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2429. });
  2430. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2431. return items;
  2432. },
  2433. showNoResults: function() {
  2434. return this.filteredItems.length === 0
  2435. && !this.showCreateNewBranch;
  2436. },
  2437. showCreateNewBranch: function() {
  2438. const vm = this;
  2439. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2440. return false;
  2441. }
  2442. return vm.items.filter(function (item) {
  2443. return item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  2444. }).length === 0;
  2445. }
  2446. },
  2447. methods: {
  2448. selectItem: function(item) {
  2449. const prev = this.getSelected();
  2450. if (prev !== null) {
  2451. prev.selected = false;
  2452. }
  2453. item.selected = true;
  2454. window.location.href = item.url;
  2455. },
  2456. createNewBranch: function() {
  2457. if (!this.showCreateNewBranch) {
  2458. return;
  2459. }
  2460. this.$refs.newBranchForm.submit();
  2461. },
  2462. focusSearchField: function() {
  2463. const vm = this;
  2464. Vue.nextTick(function() {
  2465. vm.$refs.searchField.focus();
  2466. });
  2467. },
  2468. getSelected: function() {
  2469. for (let i = 0, j = this.items.length; i < j; ++i) {
  2470. if (this.items[i].selected)
  2471. return this.items[i];
  2472. }
  2473. return null;
  2474. },
  2475. getSelectedIndexInFiltered: function() {
  2476. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  2477. if (this.filteredItems[i].selected)
  2478. return i;
  2479. }
  2480. return -1;
  2481. },
  2482. scrollToActive: function() {
  2483. let el = this.$refs['listItem' + this.active];
  2484. if (!el || el.length === 0) {
  2485. return;
  2486. }
  2487. if (Array.isArray(el)) {
  2488. el = el[0];
  2489. }
  2490. const cont = this.$refs.scrollContainer;
  2491. if (el.offsetTop < cont.scrollTop) {
  2492. cont.scrollTop = el.offsetTop;
  2493. }
  2494. else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2495. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2496. }
  2497. },
  2498. keydown: function(event) {
  2499. const vm = this;
  2500. if (event.keyCode === 40) {
  2501. // arrow down
  2502. event.preventDefault();
  2503. if (vm.active === -1) {
  2504. vm.active = vm.getSelectedIndexInFiltered();
  2505. }
  2506. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2507. return;
  2508. }
  2509. vm.active++;
  2510. vm.scrollToActive();
  2511. }
  2512. if (event.keyCode === 38) {
  2513. // arrow up
  2514. event.preventDefault();
  2515. if (vm.active === -1) {
  2516. vm.active = vm.getSelectedIndexInFiltered();
  2517. }
  2518. if (vm.active <= 0) {
  2519. return;
  2520. }
  2521. vm.active--;
  2522. vm.scrollToActive();
  2523. }
  2524. if (event.keyCode == 13) {
  2525. // enter
  2526. event.preventDefault();
  2527. if (vm.active >= vm.filteredItems.length) {
  2528. vm.createNewBranch();
  2529. } else if (vm.active >= 0) {
  2530. vm.selectItem(vm.filteredItems[vm.active]);
  2531. }
  2532. }
  2533. if (event.keyCode == 27) {
  2534. // escape
  2535. event.preventDefault();
  2536. vm.menuVisible = false;
  2537. }
  2538. }
  2539. }
  2540. });
  2541. });
  2542. }
  2543. $(".commit-button").click(function() {
  2544. $(this).parent().find('.commit-body').toggle();
  2545. });
  2546. function initNavbarContentToggle() {
  2547. const content = $('#navbar');
  2548. const toggle = $('#navbar-expand-toggle');
  2549. let isExpanded = false;
  2550. toggle.click(function() {
  2551. isExpanded = !isExpanded;
  2552. if (isExpanded) {
  2553. content.addClass('shown');
  2554. toggle.addClass('active');
  2555. }
  2556. else {
  2557. content.removeClass('shown');
  2558. toggle.removeClass('active');
  2559. }
  2560. });
  2561. }
  2562. function initTopicbar() {
  2563. const mgrBtn = $("#manage_topic");
  2564. const editDiv = $("#topic_edit");
  2565. const viewDiv = $("#repo-topics");
  2566. const saveBtn = $("#save_topic");
  2567. const topicDropdown = $('#topic_edit .dropdown');
  2568. const topicForm = $('#topic_edit.ui.form');
  2569. const topicPrompts = getPrompts();
  2570. mgrBtn.click(function() {
  2571. viewDiv.hide();
  2572. editDiv.css('display', ''); // show Semantic UI Grid
  2573. });
  2574. function getPrompts() {
  2575. const hidePrompt = $("div.hide#validate_prompt"),
  2576. prompts = {
  2577. countPrompt: hidePrompt.children('#count_prompt').text(),
  2578. formatPrompt: hidePrompt.children('#format_prompt').text()
  2579. };
  2580. hidePrompt.remove();
  2581. return prompts;
  2582. }
  2583. saveBtn.click(function() {
  2584. const topics = $("input[name=topics]").val();
  2585. $.post(saveBtn.data('link'), {
  2586. "_csrf": csrf,
  2587. "topics": topics
  2588. }, function(_data, _textStatus, xhr){
  2589. if (xhr.responseJSON.status === 'ok') {
  2590. viewDiv.children(".topic").remove();
  2591. if (topics.length) {
  2592. const topicArray = topics.split(",");
  2593. const last = viewDiv.children("a").last();
  2594. for (let i=0; i < topicArray.length; i++) {
  2595. $('<div class="ui small label topic" style="cursor:pointer;">'+topicArray[i]+'</div>').insertBefore(last)
  2596. }
  2597. }
  2598. editDiv.css('display', 'none');
  2599. viewDiv.show();
  2600. }
  2601. }).fail(function(xhr){
  2602. if (xhr.status === 422) {
  2603. if (xhr.responseJSON.invalidTopics.length > 0) {
  2604. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2605. const invalidTopics = xhr.responseJSON.invalidTopics,
  2606. topicLables = topicDropdown.children('a.ui.label');
  2607. topics.split(',').forEach(function(value, index) {
  2608. for (let i=0; i < invalidTopics.length; i++) {
  2609. if (invalidTopics[i] === value) {
  2610. topicLables.eq(index).removeClass("green").addClass("red");
  2611. }
  2612. }
  2613. });
  2614. } else {
  2615. topicPrompts.countPrompt = xhr.responseJSON.message;
  2616. }
  2617. }
  2618. }).always(function() {
  2619. topicForm.form('validate form');
  2620. });
  2621. });
  2622. topicDropdown.dropdown({
  2623. allowAdditions: true,
  2624. forceSelection: false,
  2625. fields: { name: "description", value: "data-value" },
  2626. saveRemoteData: false,
  2627. label: {
  2628. transition : 'horizontal flip',
  2629. duration : 200,
  2630. variation : false,
  2631. blue : true,
  2632. basic: true,
  2633. },
  2634. className: {
  2635. label: 'ui small label'
  2636. },
  2637. apiSettings: {
  2638. url: suburl + '/api/v1/topics/search?q={query}',
  2639. throttle: 500,
  2640. cache: false,
  2641. onResponse: function(res) {
  2642. const formattedResponse = {
  2643. success: false,
  2644. results: [],
  2645. };
  2646. const stripTags = function (text) {
  2647. return text.replace(/<[^>]*>?/gm, "");
  2648. };
  2649. const query = stripTags(this.urlData.query.trim());
  2650. let found_query = false;
  2651. const current_topics = [];
  2652. topicDropdown.find('div.label.visible.topic,a.label.visible').each(function(_,e){ current_topics.push(e.dataset.value); });
  2653. if (res.topics) {
  2654. let found = false;
  2655. for (let i=0;i < res.topics.length;i++) {
  2656. // skip currently added tags
  2657. if (current_topics.indexOf(res.topics[i].Name) != -1){
  2658. continue;
  2659. }
  2660. if (res.topics[i].Name.toLowerCase() === query.toLowerCase()){
  2661. found_query = true;
  2662. }
  2663. formattedResponse.results.push({"description": res.topics[i].Name, "data-value": res.topics[i].Name});
  2664. found = true;
  2665. }
  2666. formattedResponse.success = found;
  2667. }
  2668. if (query.length > 0 && !found_query){
  2669. formattedResponse.success = true;
  2670. formattedResponse.results.unshift({"description": query, "data-value": query});
  2671. } else if (query.length > 0 && found_query) {
  2672. formattedResponse.results.sort(function(a, b){
  2673. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  2674. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  2675. if (a.description > b.description) return -1;
  2676. if (a.description < b.description) return 1;
  2677. return 0;
  2678. });
  2679. }
  2680. return formattedResponse;
  2681. },
  2682. },
  2683. onLabelCreate: function(value) {
  2684. value = value.toLowerCase().trim();
  2685. this.attr("data-value", value).contents().first().replaceWith(value);
  2686. return $(this);
  2687. },
  2688. onAdd: function(addedValue, _addedText, $addedChoice) {
  2689. addedValue = addedValue.toLowerCase().trim();
  2690. $($addedChoice).attr('data-value', addedValue);
  2691. $($addedChoice).attr('data-text', addedValue);
  2692. }
  2693. });
  2694. $.fn.form.settings.rules.validateTopic = function(_values, regExp) {
  2695. const topics = topicDropdown.children('a.ui.label'),
  2696. status = topics.length === 0 || topics.last().attr("data-value").match(regExp);
  2697. if (!status) {
  2698. topics.last().removeClass("green").addClass("red");
  2699. }
  2700. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2701. };
  2702. topicForm.form({
  2703. on: 'change',
  2704. inline : true,
  2705. fields: {
  2706. topics: {
  2707. identifier: 'topics',
  2708. rules: [
  2709. {
  2710. type: 'validateTopic',
  2711. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2712. prompt: topicPrompts.formatPrompt
  2713. },
  2714. {
  2715. type: 'maxCount[25]',
  2716. prompt: topicPrompts.countPrompt
  2717. }
  2718. ]
  2719. },
  2720. }
  2721. });
  2722. }
  2723. function toggleDeadlineForm() {
  2724. $('#deadlineForm').fadeToggle(150);
  2725. }
  2726. function setDeadline() {
  2727. const deadline = $('#deadlineDate').val();
  2728. updateDeadline(deadline);
  2729. }
  2730. function updateDeadline(deadlineString) {
  2731. $('#deadline-err-invalid-date').hide();
  2732. $('#deadline-loader').addClass('loading');
  2733. let realDeadline = null;
  2734. if (deadlineString !== '') {
  2735. const newDate = Date.parse(deadlineString)
  2736. if (isNaN(newDate)) {
  2737. $('#deadline-loader').removeClass('loading');
  2738. $('#deadline-err-invalid-date').show();
  2739. return false;
  2740. }
  2741. realDeadline = new Date(newDate);
  2742. }
  2743. $.ajax($('#update-issue-deadline-form').attr('action') + '/deadline', {
  2744. data: JSON.stringify({
  2745. 'due_date': realDeadline,
  2746. }),
  2747. headers: {
  2748. 'X-Csrf-Token': csrf,
  2749. 'X-Remote': true,
  2750. },
  2751. contentType: 'application/json',
  2752. type: 'POST',
  2753. success: function () {
  2754. reload();
  2755. },
  2756. error: function () {
  2757. $('#deadline-loader').removeClass('loading');
  2758. $('#deadline-err-invalid-date').show();
  2759. }
  2760. });
  2761. }
  2762. function deleteDependencyModal(id, type) {
  2763. $('.remove-dependency')
  2764. .modal({
  2765. closable: false,
  2766. duration: 200,
  2767. onApprove: function () {
  2768. $('#removeDependencyID').val(id);
  2769. $('#dependencyType').val(type);
  2770. $('#removeDependencyForm').submit();
  2771. }
  2772. }).modal('show')
  2773. ;
  2774. }
  2775. function initIssueList() {
  2776. const repolink = $('#repolink').val();
  2777. $('#new-dependency-drop-list')
  2778. .dropdown({
  2779. apiSettings: {
  2780. url: suburl + '/api/v1/repos/' + repolink + '/issues?q={query}',
  2781. onResponse: function(response) {
  2782. const filteredResponse = {'success': true, 'results': []};
  2783. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  2784. // Parse the response from the api to work with our dropdown
  2785. $.each(response, function(_i, issue) {
  2786. // Don't list current issue in the dependency list.
  2787. if(issue.id === currIssueId) {
  2788. return;
  2789. }
  2790. filteredResponse.results.push({
  2791. 'name' : '#' + issue.number + '&nbsp;' + htmlEncode(issue.title),
  2792. 'value' : issue.id
  2793. });
  2794. });
  2795. return filteredResponse;
  2796. },
  2797. cache: false,
  2798. },
  2799. fullTextSearch: true
  2800. })
  2801. ;
  2802. }
  2803. function cancelCodeComment(btn) {
  2804. const form = $(btn).closest("form");
  2805. if(form.length > 0 && form.hasClass('comment-form')) {
  2806. form.addClass('hide');
  2807. form.parent().find('button.comment-form-reply').show();
  2808. } else {
  2809. form.closest('.comment-code-cloud').remove()
  2810. }
  2811. }
  2812. function onOAuthLoginClick() {
  2813. const oauthLoader = $('#oauth2-login-loader');
  2814. const oauthNav = $('#oauth2-login-navigator');
  2815. oauthNav.hide();
  2816. oauthLoader.removeClass('disabled');
  2817. setTimeout(function(){
  2818. // recover previous content to let user try again
  2819. // usually redirection will be performed before this action
  2820. oauthLoader.addClass('disabled');
  2821. oauthNav.show();
  2822. },5000);
  2823. }