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

index.js 105 kB

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