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