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.

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