You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 101KB

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