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

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