A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): create instant accounts from invite pages
Hampusc7316964d298
diff --git a/fluxer_app/src/features/auth/flow/InstantAccountForm.tsx b/fluxer_app/src/features/auth/flow/InstantAccountForm.tsxnew file mode 100644index 000000000..56b62678c--- /dev/null+++ b/fluxer_app/src/features/auth/flow/InstantAccountForm.tsx@@ -0,0 +1,143 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import FormField from '@app/features/auth/flow/AuthFormField';+import styles from '@app/features/auth/flow/identifier_first/AuthIdentifierFirstStep.module.css';+import {+ type RegistrationLegalConsentConfig,+ RegistrationLegalNotice,+} from '@app/features/auth/flow/RegistrationLegalNotice';+import {type MissingField, SubmitTooltip, shouldDisableSubmit} from '@app/features/auth/flow/SubmitTooltip';+import {getAuthErrorMessage} from '@app/features/auth/hooks/useAuthForm';+import {+ CREATE_ACCOUNT_DESCRIPTOR,+ DISPLAY_NAME_OPTIONAL_DESCRIPTOR,+} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {failureCode, failureValidationErrors} from '@app/features/platform/utils/ResponseInspection';+import {Button} from '@app/features/ui/button/Button';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';+import type {I18n} from '@lingui/core';+import {msg} from '@lingui/core/macro';+import {useLingui} from '@lingui/react/macro';+import {clsx} from 'clsx';+import {type FormEvent, useId, useState} from 'react';++const DISPLAY_NAME_DESCRIPTOR = msg({+ message: 'Display name',+ comment: 'Label of the name field when creating an account. It is the name other people see.',+});+const NAME_LENGTH_DESCRIPTOR = msg({+ message: 'Use 1 to 32 characters.',+ comment: 'Calm error under the display name field on account creation when the name is empty or too long.',+});+const NAME_NOT_ALLOWED_DESCRIPTOR = msg({+ message: 'Try a different name.',+ comment: 'Calm error under the display name field on account creation when the name is reserved or not allowed.',+});++export interface InstantAccountFormErrors {+ readonly name: string | null;+ readonly other: string | null;+}++export const NO_INSTANT_ACCOUNT_ERRORS: InstantAccountFormErrors = {name: null, other: null};++export function instantAccountErrors(error: unknown, i18n: I18n): InstantAccountFormErrors {+ const faults = failureValidationErrors(error) ?? [];+ const nameFault = faults.find((fault) => fault.path === 'global_name');+ if (nameFault !== undefined) {+ const tooLong = nameFault.code === ValidationErrorCodes.GLOBAL_NAME_LENGTH_INVALID;+ return {...NO_INSTANT_ACCOUNT_ERRORS, name: i18n._(tooLong ? NAME_LENGTH_DESCRIPTOR : NAME_NOT_ALLOWED_DESCRIPTOR)};+ }+ if (failureCode(error) === APIErrorCodes.CONTENT_BLOCKED) {+ return {...NO_INSTANT_ACCOUNT_ERRORS, name: i18n._(NAME_NOT_ALLOWED_DESCRIPTOR)};+ }+ return {...NO_INSTANT_ACCOUNT_ERRORS, other: getAuthErrorMessage(error, i18n)};+}++interface InstantAccountFormProps {+ readonly initialName: string;+ readonly consentConfig: RegistrationLegalConsentConfig;+ readonly submitting: boolean;+ readonly errors: InstantAccountFormErrors;+ readonly onEdit: () => void;+ readonly onSubmit: (globalName: string) => void;+ readonly optionalName?: boolean;+ readonly afterHeader?: boolean;+ readonly submitLabel?: string;+ readonly 'data-flx'?: string;+}++export function InstantAccountForm({+ initialName,+ consentConfig,+ submitting,+ errors,+ onEdit,+ onSubmit,+ optionalName = false,+ afterHeader = false,+ submitLabel,+ 'data-flx': dataFlx = 'auth.flow.instant-account-form',+}: InstantAccountFormProps) {+ const {i18n} = useLingui();+ const fieldId = useId();+ const [name, setName] = useState(initialName);+ const globalName = name.trim();+ const missingFields: Array<MissingField> = [];+ if (!optionalName && globalName.length === 0)+ missingFields.push({key: 'global_name', label: i18n._(DISPLAY_NAME_DESCRIPTOR)});+ return (+ <form+ className={clsx(styles.form, afterHeader && styles.formAfterHeader)}+ onSubmit={(event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ if (submitting || missingFields.length > 0) return;+ onSubmit(globalName);+ }}+ data-flx={dataFlx}+ >+ <FormField+ id={`${fieldId}-global-name`}+ name="global_name"+ type="text"+ autoComplete="nickname"+ autoCapitalize="words"+ spellCheck={false}+ enterKeyHint="go"+ autoFocus+ data-step-focus="true"+ required={!optionalName}+ dir="auto"+ label={i18n._(optionalName ? DISPLAY_NAME_OPTIONAL_DESCRIPTOR : DISPLAY_NAME_DESCRIPTOR)}+ value={name}+ onChange={(value: string) => {+ onEdit();+ setName(value);+ }}+ error={errors.name ?? undefined}+ data-flx={`${dataFlx}.global-name`}+ />+ <RegistrationLegalNotice+ config={consentConfig}+ data-flx="auth.flow.instant-account-form.registration-legal-notice"+ />+ {errors.other === null ? null : (+ <p className={clsx(styles.hint, styles.hintError)} role="alert" dir="auto" data-flx={`${dataFlx}.error`}>+ {errors.other}+ </p>+ )}+ <SubmitTooltip missingFields={missingFields} data-flx={`${dataFlx}.submit-tooltip`}>+ <Button+ type="submit"+ fitContainer+ submitting={submitting}+ disabled={shouldDisableSubmit(missingFields)}+ data-flx={`${dataFlx}.button.create`}+ >+ {submitLabel ?? i18n._(CREATE_ACCOUNT_DESCRIPTOR)}+ </Button>+ </SubmitTooltip>+ </form>+ );+}diff --git a/fluxer_app/src/features/invite/components/pages/InviteRegisterPage.tsx b/fluxer_app/src/features/invite/components/pages/InviteRegisterPage.tsxindex 189b17bda..1b66b57f7 100644--- a/fluxer_app/src/features/invite/components/pages/InviteRegisterPage.tsx+++ b/fluxer_app/src/features/invite/components/pages/InviteRegisterPage.tsx@@ -3,19 +3,30 @@import {Routes} from '@app/app/Routes';import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';import {usesUsernameSignIn} from '@app/features/app/utils/AccountIdentityFeatures';+import * as AccountEntryCommands from '@app/features/auth/commands/AccountEntryCommands';+import * as AuthenticationCommands from '@app/features/auth/commands/AuthenticationCommands';import {AuthBottomLink} from '@app/features/auth/flow/AuthBottomLink';import sharedStyles from '@app/features/auth/flow/AuthPageStyles.module.css';import {AuthRegisterFormCore} from '@app/features/auth/flow/AuthRegisterFormCore';import {AuthRuntimeTargetGate} from '@app/features/auth/flow/AuthRuntimeTargetGate';import {AuthSsoPanel, resolveAuthPanelSso} from '@app/features/auth/flow/AuthSsoPanel';import {DesktopDeepLinkPrompt} from '@app/features/auth/flow/DesktopDeepLinkPrompt';+import {+ InstantAccountForm,+ instantAccountErrors,+ NO_INSTANT_ACCOUNT_ERRORS,+} from '@app/features/auth/flow/InstantAccountForm';import {InviteHeader} from '@app/features/auth/flow/InviteHeader';+import {PENDING_APPROVAL_DESCRIPTOR} from '@app/features/auth/flow/identifier_first/AuthIdentifierFirstStep';+import {offersInstantAccount} from '@app/features/auth/flow/identifier_first/IdentifierFirstState';import {linkRegisterFields, readRegistrationUrlCode} from '@app/features/auth/flow/RegisterFormFields';+import {getRegistrationLegalConsentConfig} from '@app/features/auth/flow/RegistrationLegalNotice';import {useAuthPresentation} from '@app/features/auth/flow/useAuthPresentation';+import {isAgeBlocked} from '@app/features/auth/state/AccountEntryStorage';import {AuthCardVariant} from '@app/features/auth/state/AuthLayoutContext';import {useAuthRuntimeTarget} from '@app/features/auth/state/AuthRuntimeTarget';import {safeRedirectTarget} from '@app/features/auth/utils/SafeRedirect';-import {CREATE_ACCOUNT_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';+import {CREATE_ACCOUNT_DESCRIPTOR, JOIN_COMMUNITY_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';import {InviteAuthPageState,InvitesPausedPanel,@@ -25,12 +36,72 @@ import {setPathQueryParams} from '@app/features/messaging/utils/MessagingUrlUtilimport {useLocation, useParams} from '@app/features/platform/components/router/RouterReact';import {useLingui} from '@lingui/react/macro';import {observer} from 'mobx-react-lite';-import {useMemo} from 'react';+import {useMemo, useState} from 'react';interface InviteRegisterPageContentProps {readonly runtimeSnapshot: RuntimeConfigSnapshot;}+interface InviteInstantAccountFormProps {+ readonly code: string;+ readonly registrationUrlCode: string | null;+ readonly runtimeSnapshot: RuntimeConfigSnapshot;+ readonly onAuthenticated: () => void;+}++function InviteInstantAccountForm({+ code,+ registrationUrlCode,+ runtimeSnapshot,+ onAuthenticated,+}: InviteInstantAccountFormProps) {+ const {i18n} = useLingui();+ const consentConfig = useMemo(() => getRegistrationLegalConsentConfig(runtimeSnapshot), [runtimeSnapshot]);+ const [submitting, setSubmitting] = useState(false);+ const [errors, setErrors] = useState(NO_INSTANT_ACCOUNT_ERRORS);+ const join = async (globalName: string) => {+ if (submitting) return;+ setSubmitting(true);+ setErrors(NO_INSTANT_ACCOUNT_ERRORS);+ try {+ const result = await AccountEntryCommands.createInstantAccount({+ globalName,+ consent: true,+ inviteCode: code,+ registrationUrlCode,+ snapshot: runtimeSnapshot,+ });+ if (result.type !== 'success') {+ setErrors({...NO_INSTANT_ACCOUNT_ERRORS, other: i18n._(PENDING_APPROVAL_DESCRIPTOR)});+ return;+ }+ await AuthenticationCommands.completeLogin(+ {...result.payload, runtimeSnapshot},+ {redirectPath: result.entry === null ? '/' : Routes.guildChannel(result.entry.guild_id)},+ );+ onAuthenticated();+ } catch (caught) {+ setErrors(instantAccountErrors(caught, i18n));+ } finally {+ setSubmitting(false);+ }+ };+ return (+ <InstantAccountForm+ initialName=""+ optionalName+ afterHeader+ consentConfig={consentConfig}+ submitting={submitting}+ errors={errors}+ submitLabel={i18n._(JOIN_COMMUNITY_DESCRIPTOR)}+ onEdit={() => setErrors(NO_INSTANT_ACCOUNT_ERRORS)}+ onSubmit={(globalName) => void join(globalName)}+ data-flx="invite.invite-register-page.instant-account-form"+ />+ );+}+const InviteRegisterPageContent = observer(function InviteRegisterPageContent({runtimeSnapshot,}: InviteRegisterPageContentProps) {@@ -95,6 +166,9 @@ const InviteRegisterPageContent = observer(function InviteRegisterPageContent({);}const usernameSignIn = usesUsernameSignIn(runtimeSnapshot.features);+ const registrationUrlCode = readRegistrationUrlCode(params);+ const instantAccount =+ guildInvite !== null && offersInstantAccount(runtimeSnapshot.features, null) && !isAgeBlocked();return (<><DesktopDeepLinkPrompt@@ -104,16 +178,26 @@ const InviteRegisterPageContent = observer(function InviteRegisterPageContent({/><InviteHeader invite={invite} data-flx="invite.invite-register-page.invite-header" /><div className={sharedStyles.container} data-flx="invite.invite-register-page.div--4">- <AuthRegisterFormCore- fields={linkRegisterFields(runtimeSnapshot, readRegistrationUrlCode(params))}- submitLabel={i18n._(CREATE_ACCOUNT_DESCRIPTOR)}- redirectPath="/"- offerRecoveryKit={usernameSignIn}- inviteCode={code}- runtimeSnapshot={runtimeSnapshot}- onAuthenticated={runtimeTarget.reset}- data-flx="invite.invite-register-page.auth-minimal-register-form-core"- />+ {instantAccount ? (+ <InviteInstantAccountForm+ code={code}+ registrationUrlCode={registrationUrlCode ?? null}+ runtimeSnapshot={runtimeSnapshot}+ onAuthenticated={runtimeTarget.reset}+ data-flx="invite.invite-register-page.invite-instant-account-form"+ />+ ) : (+ <AuthRegisterFormCore+ fields={linkRegisterFields(runtimeSnapshot, registrationUrlCode)}+ submitLabel={i18n._(CREATE_ACCOUNT_DESCRIPTOR)}+ redirectPath="/"+ offerRecoveryKit={usernameSignIn}+ inviteCode={code}+ runtimeSnapshot={runtimeSnapshot}+ onAuthenticated={runtimeTarget.reset}+ data-flx="invite.invite-register-page.auth-minimal-register-form-core"+ />+ )}<AuthBottomLink variant="login" to={loginPath} data-flx="invite.invite-register-page.auth-bottom-link" /></div></>