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

index.js 108 kB

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