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