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