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

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