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 101KB

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