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 108 kB

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