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

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