Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

index.js 105KB

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