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