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

index.js 107KB

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