import config from '@automattic/calypso-config';
import { Button, Card, Dialog, FormInputValidation, FormLabel } from '@automattic/components';
import { canBeTranslated, getLanguage, isLocaleVariant } from '@automattic/i18n-utils';
import languages from '@automattic/languages';
import { ExternalLink } from '@wordpress/components';
import debugFactory from 'debug';
import { fixMe, localize } from 'i18n-calypso';
import { debounce, flowRight as compose, get, map, size } from 'lodash';
import { Component } from 'react';
import { connect } from 'react-redux';
import CSSTransition from 'react-transition-group/CSSTransition';
import TransitionGroup from 'react-transition-group/TransitionGroup';
import QueryUserSettings from 'calypso/components/data/query-user-settings';
import FormButton from 'calypso/components/forms/form-button';
import FormButtonsBar from 'calypso/components/forms/form-buttons-bar';
import FormFieldset from 'calypso/components/forms/form-fieldset';
import FormRadio from 'calypso/components/forms/form-radio';
import FormSettingExplanation from 'calypso/components/forms/form-setting-explanation';
import FormTextInput from 'calypso/components/forms/form-text-input';
import InlineSupportLink from 'calypso/components/inline-support-link';
import LanguagePicker from 'calypso/components/language-picker';
import { withLocalizedMoment } from 'calypso/components/localized-moment';
import Main from 'calypso/components/main';
import NavigationHeader from 'calypso/components/navigation-header';
import SectionHeader from 'calypso/components/section-header';
import SitesDropdown from 'calypso/components/sites-dropdown';
import { withGeoLocation } from 'calypso/data/geo/with-geolocation';
import PageViewTracker from 'calypso/lib/analytics/page-view-tracker';
import { onboardingUrl } from 'calypso/lib/paths';
import { protectForm } from 'calypso/lib/protect-form';
import twoStepAuthorization from 'calypso/lib/two-step-authorization';
import { clearStore } from 'calypso/lib/user/store';
import wpcom from 'calypso/lib/wp';
import AccountEmailField from 'calypso/me/account/account-email-field';
import { withDefaultInterface } from 'calypso/me/account/with-default-interface';
import { EmailVerificationBannerV2 } from 'calypso/me/email-verification-banner';
import ReauthRequired from 'calypso/me/reauth-required';
import { recordGoogleEvent, recordTracksEvent } from 'calypso/state/analytics/actions';
import {
isCurrentUserEmailVerified,
getCurrentUserDate,
getCurrentUserDisplayName,
getCurrentUserName,
getCurrentUserVisibleSiteCount,
} from 'calypso/state/current-user/selectors';
import { errorNotice, removeNotice, successNotice } from 'calypso/state/notices/actions';
import canDisplayCommunityTranslator from 'calypso/state/selectors/can-display-community-translator';
import getUnsavedUserSettings from 'calypso/state/selectors/get-unsaved-user-settings';
import getUserSettings from 'calypso/state/selectors/get-user-settings';
import isRequestingMissingSites from 'calypso/state/selectors/is-requesting-missing-sites';
import { isA8cTeamMember } from 'calypso/state/teams/selectors';
import {
clearUnsavedUserSettings,
removeUnsavedUserSetting,
setUserSetting,
} from 'calypso/state/user-settings/actions';
import { isFetchingUserSettings } from 'calypso/state/user-settings/selectors';
import { saveUnsavedUserSettings } from 'calypso/state/user-settings/thunks';
import AccountSettingsCloseLink from './close-link';
import ToggleLandingPageSettings from './toggle-landing-page';
import ToggleUseCommunityTranslator from './toggle-use-community-translator';
import './style.scss';
export const noticeId = 'me-settings-notice';
const noticeOptions = {
id: noticeId,
};
/**
* Debug instance
*/
const debug = debugFactory( 'calypso:me:account' );
const ALLOWED_USERNAME_CHARACTERS_REGEX = /^[a-z0-9]+$/;
const USERNAME_MIN_LENGTH = 4;
const ACCOUNT_FORM_NAME = 'account';
const INTERFACE_FORM_NAME = 'interface';
const ACCOUNT_FIELDS = [ 'user_login', 'user_email', 'user_URL', 'primary_site_ID' ];
const INTERFACE_FIELDS = [
'locale_variant',
'language',
'i18n_empathy_mode',
'use_fallback_for_incomplete_languages',
'enable_translator',
'calypso_preferences',
];
class Account extends Component {
constructor( props ) {
super( props );
this.props.removeUnsavedUserSetting( 'user_login' );
}
state = {
redirect: false,
showConfirmUsernameForm: false,
submittingForm: false,
formsSubmitting: {},
usernameAction: 'new',
validationResult: false,
accountSubmitDisable: false,
};
componentDidUpdate() {
if ( ! this.hasUnsavedUserSettings( ACCOUNT_FIELDS.concat( INTERFACE_FIELDS ) ) ) {
this.props.markSaved();
}
}
componentDidMount() {
const params = new URLSearchParams( window.location.search );
if ( params.get( 'usernameChangeSuccess' ) === 'true' ) {
this.props.successNotice( this.props.translate( 'Username changed successfully!' ), {
duration: 5000,
} );
const currentUrl = new URL( window.location.href );
currentUrl.searchParams.delete( 'usernameChangeSuccess' );
window.history.replaceState( {}, '', currentUrl.toString() );
}
}
componentWillUnmount() {
debug( this.constructor.displayName + ' component is unmounting.' );
// Silently clean up unsavedSettings before unmounting
this.props.clearUnsavedUserSettings();
}
getDisabledState( formName ) {
return formName ? this.state.formsSubmitting[ formName ] : this.state.submittingForm;
}
getUserSetting( settingName ) {
return (
get( this.props.unsavedUserSettings, settingName ) ??
this.getUserOriginalSetting( settingName )
);
}
getUserOriginalSetting( settingName ) {
return get( this.props.userSettings, settingName );
}
hasUnsavedUserSetting( settingName ) {
return this.props.unsavedUserSettings.hasOwnProperty( settingName );
}
hasUnsavedUserSettings( settingNames ) {
return settingNames.reduce(
( acc, settingName ) => this.hasUnsavedUserSetting( settingName ) || acc,
false
);
}
updateUserSetting( settingName, value ) {
this.props.setUserSetting( settingName, value );
}
updateUserSettingInput = ( event ) => {
this.updateUserSetting( event.target.name, event.target.value );
};
updateUserSettingCheckbox = ( event ) => {
this.updateUserSetting( event.target.name, event.target.checked );
};
updateCommunityTranslatorSetting = ( event ) => {
const { name, checked } = event.target;
this.updateUserSetting( name, checked );
const redirect = '/me/account';
this.setState( { redirect } );
this.saveInterfaceSettings( event );
};
updateLanguage = ( event ) => {
const { value, empathyMode, useFallbackForIncompleteLanguages } = event.target;
this.updateUserSetting( 'language', value );
if ( typeof empathyMode !== 'undefined' ) {
this.updateUserSetting( 'i18n_empathy_mode', empathyMode );
}
if ( typeof useFallbackForIncompleteLanguages !== 'undefined' ) {
this.updateUserSetting(
'use_fallback_for_incomplete_languages',
useFallbackForIncompleteLanguages
);
}
const localeVariantSelected = isLocaleVariant( value ) ? value : '';
const originalSlug =
this.getUserSetting( 'locale_variant' ) || this.getUserSetting( 'language' ) || '';
const languageHasChanged = originalSlug !== value;
const formHasChanged = languageHasChanged;
if ( formHasChanged ) {
this.props.markChanged();
}
const redirect = formHasChanged ? '/me/account' : false;
// store any selected locale variant so we can test it against those with no GP translation sets
this.setState( { redirect, localeVariantSelected } );
if ( formHasChanged ) {
this.props.recordTracksEvent( 'calypso_user_language_switch', {
new_language: value,
previous_language:
this.getUserOriginalSetting( 'locale_variant' ) ||
this.getUserOriginalSetting( 'language' ),
country_code: this.props.geo?.country_short,
} );
this.saveInterfaceSettings( event );
}
};
updateUserLoginConfirm = ( event ) => {
this.setState( { userLoginConfirm: event.target.value } );
};
validateUsername = debounce( async () => {
const { currentUserName, translate } = this.props;
const username = this.getUserSetting( 'user_login' );
debug( 'Validating username ' + username );
if ( username === currentUserName ) {
this.setState( { validationResult: false } );
return;
}
if ( username.length < USERNAME_MIN_LENGTH ) {
this.setState( {
validationResult: {
error: 'invalid_input',
message: translate( 'Usernames must be at least 4 characters.' ),
},
} );
return;
}
if ( ! ALLOWED_USERNAME_CHARACTERS_REGEX.test( username ) ) {
this.setState( {
validationResult: {
error: 'invalid_input',
message: translate( 'Usernames can only contain lowercase letters (a-z) and numbers.' ),
},
} );
return;
}
try {
const { success, allowed_actions } = await wpcom.req.get(
`/me/username/validate/${ username }`
);
this.setState( {
validationResult: { success, allowed_actions, validatedUsername: username },
} );
} catch ( error ) {
this.setState( { validationResult: error } );
}
}, 600 );
hasEmailValidationError() {
return !! this.state.emailValidationError;
}
shouldDisplayCommunityTranslator() {
const locale = this.getUserSetting( 'language' );
// disable for locales
if ( ! locale || ! canBeTranslated( locale ) ) {
return false;
}
// disable for locale variants with no official GP translation sets
if (
this.state.localeVariantSelected &&
! canBeTranslated( this.state.localeVariantSelected )
) {
return false;
}
// if the user hasn't yet selected a language, and the locale variants has no official GP translation set
if (
typeof this.state.localeVariantSelected !== 'string' &&
! canBeTranslated( this.getUserSetting( 'locale_variant' ) )
) {
return false;
}
return true;
}
thankTranslationContributors() {
if ( ! this.shouldDisplayCommunityTranslator() ) {
return;
}
const locale = this.getUserSetting( 'language' );
const language = getLanguage( locale );
if ( ! language ) {
return;
}
const { translate } = this.props;
const url = 'https://translate.wordpress.com/translators/?contributor_locale=' + locale;
const thanksLabel = fixMe( {
text: 'Thanks to {{a}}all our community members who helped translate to {{language/}}{{/a}}',
newCopy: translate(
'Thanks to {{a}}all our community members who helped translate to {{language/}}{{/a}}',
{
components: {
a:
,
},
}
);
} else if ( newEmail ) {
// Only email changed.
successMessage = this.props.translate(
'We sent an email to %(email)s. Please check your inbox to verify your email.',
{
args: {
email: newEmail || '',
},
}
);
}
this.setState(
{
submittingForm: false,
formsSubmitting: {
...this.state.formsSubmitting,
...( formName && { [ formName ]: false } ),
},
},
() => {
this.props.successNotice( successMessage, noticeOptions );
}
);
debug( 'Settings saved successfully ' + JSON.stringify( response ) );
}
async submitForm( event, fields, formName = '' ) {
event?.preventDefault && event.preventDefault();
debug( 'Submitting form' );
this.setState( {
submittingForm: true,
formsSubmitting: {
...this.state.formsSubmitting,
...( formName && { [ formName ]: true } ),
},
} );
try {
const response = await this.props.saveUnsavedUserSettings( fields );
this.handleSubmitSuccess( response, formName );
} catch ( error ) {
this.handleSubmitError( error, formName );
}
}
/*
* These form fields are displayed when there is not a username change in progress.
*/
renderAccountFields() {
const { translate } = this.props;
return (