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

index.js 106KB

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