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