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

index.js 106KB

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