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