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

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