Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

8.7 KB
Raw Blame
import { BRANDING_NAME } from '@lobechat/business-const';
import {
  Alert,
  Badge,
  Button,
  createStaticStyles,
  Divider,
  Flexbox,
  Icon,
  Input,
  Text,
} from '@lobehub/ui';
import { Form, type FormInstance } from '@lobehub/ui/form';
import { Mail } from 'lucide-react';
import { type CSSProperties, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';

import AuthIcons from '@/components/AuthIcons';
import InlineErrorText from '@/components/InlineErrorText';
import AuthCard from '@/features/AuthCard';
import AuthAgreement from '@/features/AuthShell/AuthAgreement';

const styles = createStaticStyles(({ css, cssVar }) => ({
  inlineLink: css`
    cursor: pointer;
    color: ${cssVar.colorPrimary};
    text-decoration: underline;
  `,
}));

export const EMAIL_REGEX = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
export const USERNAME_REGEX = /^\w+$/;

// Pin both the provider logo and the loading spinner to the same spot so the
// spinner doesn't jump when a social button enters its loading state.
const PROVIDER_ICON_STYLE: CSSProperties = {
  insetInlineStart: 12,
  position: 'absolute',
  top: '50%',
  transform: 'translateY(-50%)',
};

// Turn a provider id into a display name, e.g. "google" -> "Google".
const getProviderName = (provider: string) =>
  provider.toLowerCase().replaceAll(/(^|[_-])([a-z])/g, (_, __, c) => c.toUpperCase());

export interface SignInEmailStepProps {
  agreementChecked: boolean;
  continueWithAgreement: (continueAction: () => void) => void;
  disableEmailPassword?: boolean;
  form: FormInstance<{ email: string }>;
  isSocialOnly: boolean;
  lastAuthProvider?: string | null;
  loading: boolean;
  oAuthSSOProviders: string[];
  onGoToSignup: () => void;
  onResetEmail: () => void;
  onSetPassword: () => void;
  onSocialSignIn: (provider: string) => void;
  /** Why sending the "set a password" email failed, shown under the social-only hint */
  sendError?: string;
  serverConfigInit: boolean;
  sessionExpired?: boolean;
  setAgreementChecked: (checked: boolean) => void;
  /** Provider whose sign-in just failed; explained under the provider buttons */
  socialErrorProvider?: string | null;
  socialLoading: string | null;
}

export const SignInEmailStep = ({
  agreementChecked,
  continueWithAgreement,
  disableEmailPassword,
  form,
  isSocialOnly,
  lastAuthProvider,
  loading,
  oAuthSSOProviders,
  sendError,
  serverConfigInit,
  sessionExpired,
  setAgreementChecked,
  socialErrorProvider,
  socialLoading,
  onGoToSignup,
  onResetEmail,
  onSetPassword,
  onSocialSignIn,
}: SignInEmailStepProps) => {
  const { t } = useTranslation('auth');
  const emailInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    emailInputRef.current?.focus();
  }, []);

  const divider = (
    <Divider style={{ marginBlock: 16 }}>
      <Text fontSize={12} type={'secondary'}>
        {t('betterAuth.signin.orContinueWith')}
      </Text>
    </Divider>
  );

  const getProviderLabel = (provider: string) => {
    const normalized = getProviderName(provider);
    const normalizedKey = normalized.replaceAll(/[^\da-z]/gi, '');
    const key = `betterAuth.signin.continueWith${normalizedKey}`;
    return t(key, { defaultValue: `Continue with ${normalized}` });
  };

  // Config is injected synchronously via window.__SERVER_CONFIG__, so the email
  // form is the primary path unless the account is social-only.
  const showEmailForm = !disableEmailPassword && !isSocialOnly;

  return (
    <AuthCard title={t('signin.subtitle', { appName: BRANDING_NAME })}>
      {sessionExpired && (
        <Alert
          showIcon
          message={t('betterAuth.signin.sessionExpired')}
          style={{ marginBlockEnd: 12 }}
          type="warning"
          variant="filled"
        />
      )}
      {serverConfigInit && oAuthSSOProviders.length > 0 && (
        <Flexbox gap={12}>
          {oAuthSSOProviders.map((provider) => {
            const button = (
              <Button
                block
                htmlType="button"
                icon={<Icon icon={AuthIcons(provider, 18)} />}
                key={provider}
                loading={socialLoading === provider}
                size="large"
                styles={{ icon: PROVIDER_ICON_STYLE }}
                type="fill"
                onClick={() =>
                  continueWithAgreement(() => {
                    onSocialSignIn(provider);
                  })
                }
              >
                {getProviderLabel(provider)}
              </Button>
            );
            const showLastUsed =
              provider === lastAuthProvider &&
              (oAuthSSOProviders.length > 1 ||
                (oAuthSSOProviders.length === 1 && !disableEmailPassword));
            return showLastUsed ? (
              <Badge
                color="var(--lobe-color-info)"
                count={t('betterAuth.signin.lastUsed')}
                key={provider}
                style={{ display: 'block', width: '100%' }}
              >
                {button}
              </Badge>
            ) : (
              button
            );
          })}
          {socialErrorProvider && (
            <InlineErrorText>
              {t('betterAuth.signin.socialFailed', {
                provider: getProviderName(socialErrorProvider),
              })}
            </InlineErrorText>
          )}
          {showEmailForm && divider}
        </Flexbox>
      )}
      {serverConfigInit && disableEmailPassword && oAuthSSOProviders.length === 0 && (
        <Alert showIcon description={t('betterAuth.signin.ssoOnlyNoProviders')} type="warning" />
      )}
      {showEmailForm && (
        <Form form={form} gap={0} layout="vertical">
          <Form.Field
            name="email"
            style={{ gap: 0, paddingBlock: '0 24px' }}
            validateOn="submit"
            validate={(value: string) => {
              if (!value) return t('betterAuth.errors.emailRequired');
              const trimmedValue = value.trim();
              if (EMAIL_REGEX.test(trimmedValue) || USERNAME_REGEX.test(trimmedValue)) return;
              return t('betterAuth.errors.emailInvalid');
            }}
          >
            <Input
              autoComplete="username"
              inputMode="email"
              placeholder={t('betterAuth.signin.emailPlaceholder')}
              prefix={<Icon icon={Mail} style={{ marginInline: 6 }} />}
              ref={emailInputRef}
              size="large"
              style={{ padding: 6 }}
            />
          </Form.Field>
          <AuthAgreement checked={agreementChecked} onChange={setAgreementChecked} />
          <Button block htmlType="submit" loading={loading} size="large" type="primary">
            {t('betterAuth.signin.nextStep')}
          </Button>
        </Form>
      )}
      {isSocialOnly && (
        <Alert
          showIcon
          style={{ marginTop: 12 }}
          type="info"
          description={
            <>
              {t('betterAuth.signin.socialOnlyHint')}{' '}
              <a
                className={styles.inlineLink}
                role="button"
                tabIndex={0}
                onClick={onSetPassword}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    onSetPassword();
                  }
                }}
              >
                {t('betterAuth.signin.setPassword')}
              </a>
            </>
          }
        />
      )}
      {isSocialOnly && sendError && (
        <InlineErrorText style={{ marginTop: 12 }}>{sendError}</InlineErrorText>
      )}
      {isSocialOnly && (
        <Text align={'center'} fontSize={13} style={{ marginTop: 12 }} type={'secondary'}>
          <a
            className={styles.inlineLink}
            role="button"
            tabIndex={0}
            onClick={onResetEmail}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                onResetEmail();
              }
            }}
          >
            {t('betterAuth.signin.emailSent.changeEmail')}
          </a>
        </Text>
      )}
      {!showEmailForm && <AuthAgreement />}
      {showEmailForm && (
        <Text align={'center'} fontSize={13} style={{ marginTop: 16 }} type={'secondary'}>
          {t('betterAuth.signin.noAccount')}{' '}
          <a
            className={styles.inlineLink}
            role="button"
            tabIndex={0}
            onClick={onGoToSignup}
            onKeyDown={(e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                onGoToSignup();
              }
            }}
          >
            {t('betterAuth.signin.signupLink')}
          </a>
        </Text>
      )}
    </AuthCard>
  );
};