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

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