Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(app): rebuild the setup wizard gate around step drafts

Hampusfff6ff4487dd
diff --git a/fluxer_app/src/features/app/components/setup/SelfHostedSetupWizardGate.tsx b/fluxer_app/src/features/app/components/setup/SelfHostedSetupWizardGate.tsx
index ad134834a..c4112fa1d 100644
--- a/fluxer_app/src/features/app/components/setup/SelfHostedSetupWizardGate.tsx
+++ b/fluxer_app/src/features/app/components/setup/SelfHostedSetupWizardGate.tsx
@@ -1,135 +1,165 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {Routes} from '@app/app/Routes';
-import * as Modal from '@app/features/app/components/dialogs/Modal';
+import {AuthShell, resolveLayoutAuthBrand, useAuthLayoutVariant} from '@app/features/app/components/layout/AuthShell';
import styles from '@app/features/app/components/setup/SelfHostedSetupWizardGate.module.css';
+import {
+ AccountStep,
+ CREATE_ACCOUNT_DESCRIPTOR,
+ SetupAccountDraft,
+ type SetupAccountValues,
+} from '@app/features/app/components/setup/SetupAccountStep';
+import {
+ AttachmentsStep,
+ SetupAttachmentsDraftProvider,
+ useSetupAttachmentsDraft,
+} from '@app/features/app/components/setup/SetupAttachmentsStep';
+import {SetupBrandingDraftProvider, useSetupBrandingDraft} from '@app/features/app/components/setup/SetupBrandingDraft';
+import {BrandingStep} from '@app/features/app/components/setup/SetupBrandingStep';
+import {
+ EmailSenderStep,
+ EmailServiceStep,
+ parseSmtpPort,
+ SetupEmailDraftProvider,
+ useSetupEmailDraft,
+} from '@app/features/app/components/setup/SetupEmailSteps';
+import {
+ isEmailAnswer,
+ SetupIdentityDraft,
+ type SetupIdentityValues,
+} from '@app/features/app/components/setup/SetupIdentityDraft';
+import {
+ EmailDeliveryStep,
+ SharedUsernamesStep,
+ SignInMethodStep,
+} from '@app/features/app/components/setup/SetupIdentitySteps';
+import {NameStep} from '@app/features/app/components/setup/SetupNameStep';
+import {
+ CommunitiesStep,
+ DirectMessagesStep,
+ type FinishDraft,
+ PushRelayStep,
+ RegistrationStep,
+ SetupPolicyDraftProvider,
+ useSetupPolicyDraft,
+} from '@app/features/app/components/setup/SetupPolicySteps';
+import {RecoveryKitStep, SetupRecoveryKitDraft} from '@app/features/app/components/setup/SetupRecoveryKitStep';
+import {ReviewStep} from '@app/features/app/components/setup/SetupReviewStep';
+import {type ServiceKeyDraft, ServicesStep} from '@app/features/app/components/setup/SetupServicesStep';
+import {
+ SetupTokenDraftProvider,
+ SetupTokenStep,
+ useSetupTokenDraft,
+} from '@app/features/app/components/setup/SetupTokenStep';
import {
classifySetupUnauthorized,
fetchInstanceConfig,
- type SetupBrandingAssetKind,
- setSetupAccountIdentity,
- testSmtpConfig,
updateInstanceConfig,
- uploadBrandingAsset,
} from '@app/features/app/components/setup/SetupWizardClient';
import {
- createSetupWizardSnapshot,
- selectSetupWizardModel,
- transitionSetupWizardSnapshot,
+ countedStepsBeforeAccount,
+ type EmailDeliveryAnswer,
+ firstStepAfterAccount,
+ isBeforeAccountStep,
+ isWizardStep,
+ nextStep,
+ previousStep,
+ resolveStep,
+ visibleSteps,
+ type WizardConditions,
type WizardStep,
+ wizardProgress,
} from '@app/features/app/components/setup/SetupWizardStateMachine';
import {
- AdminAccountStep,
- AdminIntroStep,
- AdminRecoveryKitStep,
- type BrandingAssetState,
- BrandingStep,
- CommunityStep,
- FinishStep,
- IntegrationStep,
- type IntegrationStepKind,
- LoadingStep,
- type MediaExpiryDraft,
- MediaExpiryStep,
- type PremiumMode,
- PremiumStep,
- PushRelayConsentStep,
- type RegistrationMode,
- RegistrationStep,
- type ServiceAvailability,
- type ServiceIntegrationDraft,
- type ServiceSelection,
- ServicesStep,
- SetupTokenStep,
- SignInMethodStep,
- ThemeStep,
- toSmtpTlsMode,
+ DoneStep,
+ SignInLockedStep,
+ SignInToFinishStep,
+ TextButton,
WelcomeStep,
} from '@app/features/app/components/setup/SetupWizardSteps';
-import {resolveAppShellBranding} from '@app/features/app/state/AppShellBranding';
import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
+import {AuthCardContainer} from '@app/features/auth/flow/AuthCardContainer';
+import {type MissingField, SubmitTooltip} from '@app/features/auth/flow/SubmitTooltip';
import Authentication from '@app/features/auth/state/Authentication';
-import {AuthRegisterDraftContext, type AuthRegisterFormDraft} from '@app/features/auth/state/AuthRegisterDraftContext';
-import {BACK_DESCRIPTOR, SIGN_OUT_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
-import {openFilePicker} from '@app/features/messaging/utils/FilePickerUtils';
+import {AuthRegisterDraftContext} from '@app/features/auth/state/AuthRegisterDraftContext';
+import {
+ BACK_DESCRIPTOR,
+ CONTINUE_DESCRIPTOR,
+ SIGN_IN_DESCRIPTOR,
+ SIGN_OUT_DESCRIPTOR,
+} from '@app/features/i18n/utils/CommonMessageDescriptors';
import * as RouterUtils from '@app/features/navigation/utils/RouterUtils';
import {AccountScopedWork} from '@app/features/platform/state/AccountScopedWork';
import {isAccountTransitionAbortError} from '@app/features/platform/state/AccountTransitionAbort';
import SessionManager from '@app/features/platform/state/AuthSession';
+import {getProtectedSessionStorage} from '@app/features/platform/state/ProtectedWebStorage';
import {HttpError} from '@app/features/platform/types/EndpointError';
import {Logger} from '@app/features/platform/utils/AppLogger';
-import {readBlobAsDataUrl as fileToBase64} from '@app/features/platform/utils/BlobDataUrl';
-import {failureCode, failureValidationErrors} from '@app/features/platform/utils/ResponseInspection';
-import Theme from '@app/features/theme/state/Theme';
import {Button} from '@app/features/ui/button/Button';
+import {Scroller} from '@app/features/ui/components/Scroller';
+import {Spinner} from '@app/features/ui/components/Spinner';
import FocusRingManager from '@app/features/ui/focus_ring/FocusRingManager';
-import {PortalHostContext} from '@app/features/ui/overlay/PortalHostContext';
+import {ArrowLeftIcon} from '@app/features/ui/icons/DirectionalIcons';
import KeyboardMode from '@app/features/ui/state/KeyboardMode';
-import ModalState from '@app/features/ui/state/Modal';
import {SteppedCarousel} from '@app/features/ui/stepped_carousel/SteppedCarousel';
-import {
- ModalStackContext,
- type ModalStackContextValue,
- UNSTACKED_MODAL_CONTEXT,
-} from '@app/features/ui/utils/ModalStackContext';
+import {isMobileExperienceEnabled} from '@app/features/ui/utils/MobileExperience';
import * as RecoveryKitCommands from '@app/features/user/commands/RecoveryKitCommands';
-import {confirmNewRecoveryKit} from '@app/features/user/components/modals/tabs/account_security_tab/RecoveryKitSettings';
import RecoveryKitStatus from '@app/features/user/state/RecoveryKitStatus';
import * as FormUtils from '@app/lib/forms';
+import {RegistrationModes} from '@fluxer/constants/src/AccountConfigConstants';
import {
+ AccountIdentityLockReasons,
type AccountIdentityMode,
AccountIdentityModes,
- type TagStyle,
- TagStyles,
} from '@fluxer/constants/src/AccountIdentityConstants';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {getAcceptString} from '@fluxer/constants/src/AssetFormatPolicy';
-import type {SmtpTlsMode} from '@fluxer/constants/src/SmtpConstants';
-import {type ThemeType, ThemeTypes} from '@fluxer/constants/src/UserConstants';
+import {ThemeTypes} from '@fluxer/constants/src/UserConstants';
+import {isRecord} from '@fluxer/record_utils/src/RecordGuards';
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import type {MessageDescriptor} from '@lingui/core';
import {msg} from '@lingui/core/macro';
import {useLingui} from '@lingui/react/macro';
-import {ArrowLeftIcon, ArrowRightIcon, CheckIcon, WrenchIcon} from '@phosphor-icons/react';
-import {AnimatePresence, motion, type Transition, useReducedMotion} from 'framer-motion';
+import {clsx} from 'clsx';
import {observer} from 'mobx-react-lite';
-import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
+import type React from 'react';
+import {useCallback, useEffect, useEffectEvent, useId, useMemo, useRef, useState} from 'react';
+import {createPortal} from 'react-dom';
const logger = new Logger('SelfHostedSetupWizardGate');
-const BEHIND_STACKED_MODAL_PLACEMENT: ModalStackContextValue = {...UNSTACKED_MODAL_CONTEXT, isTopmost: false};
+const DRAFT_STORAGE_KEY = 'fluxer.setup.draft';
+const userStorageKey = (userId: string) => `fluxer.setup.${userId}`;
const SETUP_WIZARD_DESCRIPTOR = msg({
- message: 'Self-host setup',
- comment: 'Accessible label for the self-host setup wizard carousel.',
+ message: 'Instance setup',
+ comment: 'Accessible label for the group that holds the setup wizard screens.',
});
-const HEADER_DESCRIPTOR = msg({
- message: 'Set up {productName}',
- comment: 'Title for the self-host setup wizard modal.',
+const PROGRESS_LABEL_DESCRIPTOR = msg({
+ message: 'Setup progress',
+ comment: 'Accessible label for the progress bar at the top of the setup wizard.',
});
-const NEXT_DESCRIPTOR = msg({
- message: 'Next',
- comment: 'Button that moves to the next setup wizard step.',
+const STEP_COUNT_DESCRIPTOR = msg({
+ message: 'Step {current} of {total}',
+ comment: 'Setup wizard progress next to the Back button. current and total are numbers.',
+});
+const GET_STARTED_DESCRIPTOR = msg({
+ message: 'Get started',
+ comment: 'Button on the first setup wizard screen.',
});
const FINISH_DESCRIPTOR = msg({
message: 'Finish setup',
- comment: 'Button that saves the configuration and completes the setup wizard.',
-});
-const SIGN_IN_METHOD_LOCKED_USERNAME_DESCRIPTOR = msg({
- message: 'This instance already uses usernames to sign in. This can no longer change.',
- comment: 'Setup wizard error when the operator picks email sign-in but the instance is already fixed to usernames.',
+ comment: 'Button on the review screen that saves every choice and finishes setup.',
});
-const USERNAME_STYLE_LOCKED_DESCRIPTOR = msg({
- message: 'The username tags on this instance are already set. They can no longer change.',
- comment: 'Setup wizard error when the username style was already fixed because an account exists.',
-});
-const SIGN_IN_METHOD_LOCKED_EMAIL_DESCRIPTOR = msg({
- message: 'This instance already uses email to sign in. This can no longer change.',
- comment: 'Setup wizard error when the operator picks username sign-in but the instance is already fixed to email.',
+const BACK_TO_REVIEW_DESCRIPTOR = msg({
+ message: 'Back to review',
+ comment: 'Button that saves an answer and returns to the setup wizard review screen.',
});
const LOADING_DESCRIPTOR = msg({
- message: 'Loading instance configuration',
- comment: 'Accessible status while the setup wizard loads the instance configuration.',
+ message: 'Loading your setup',
+ comment: 'Accessible status while the setup wizard loads the saved answers.',
+});
+const SETUP_TOKEN_REJECTED_DESCRIPTOR = msg({
+ message: 'Your setup token stopped working. Enter it again.',
+ comment: 'Alert on the setup token screen when the token was refused while creating the account.',
});
const LOAD_ERROR_DESCRIPTOR = msg({
message: 'Could not load the instance configuration. Try reloading the page.',
@@ -145,417 +175,193 @@ const ORIGIN_MISMATCH_DESCRIPTOR = msg({
'The API is on a different origin than this page, so setup requests are sent without your session. Check the public origin and port this instance is configured with, then reload.',
comment: 'Error shown when the setup wizard cannot load because the API origin differs from the page origin.',
});
-const ASSET_UPLOAD_ERROR_DESCRIPTOR = msg({
- message: 'That image could not be used. Try a different file.',
- comment: 'Error shown when a branding image fails to upload in the setup wizard.',
-});
-
-const footerRevealTransition: Transition = {
- type: 'spring',
- stiffness: 460,
- damping: 40,
- mass: 0.7,
-};
-const footerButtonTransition: Transition = {
- type: 'spring',
- stiffness: 520,
- damping: 42,
- mass: 0.7,
-};
-const instantTransition: Transition = {
- duration: 0,
-};
-const STEP_NAVIGATION_LOCK_MS = 320;
-const BRANDING_ASSET_KINDS: ReadonlyArray<SetupBrandingAssetKind> = ['icon', 'symbol', 'logo', 'wordmark', 'favicon'];
-
-function hexToNumber(value: string | null): number | null {
- if (!value) return null;
- const match = /^#?([0-9a-fA-F]{6})$/.exec(value.trim());
- if (!match) return null;
- return parseInt(match[1], 16) >>> 0;
+interface PreAccountDraft extends SetupIdentityValues, SetupAccountValues {
+ stepId: WizardStep;
}
-function numberToHexColor(value: number): string {
- return `#${(value >>> 0).toString(16).padStart(6, '0').slice(-6)}`;
+interface PostAccountDraft {
+ stepId: WizardStep;
+ finishDraft: FinishDraft;
+ emailAnswer: EmailDeliveryAnswer;
+ stepsBeforeAccount: number;
}
-function brandingAssetUrl(config: InstanceConfigResponse, kind: SetupBrandingAssetKind): string | null {
- const branding = config.app_public.branding;
- switch (kind) {
- case 'icon':
- return branding.icon_url;
- case 'symbol':
- return branding.symbol_url;
- case 'logo':
- return branding.logo_url;
- case 'wordmark':
- return branding.wordmark_url;
- case 'favicon':
- return branding.favicon_url;
+function readStored(key: string): Record<string, unknown> | null {
+ try {
+ const raw = getProtectedSessionStorage()?.getItem(key);
+ if (!raw) return null;
+ const value: unknown = JSON.parse(raw);
+ return isRecord(value) ? value : null;
+ } catch (error) {
+ logger.warn('Failed to read saved setup progress', error);
+ return null;
}
}
-const DEFAULT_INTEGRATION_DRAFT: ServiceIntegrationDraft = {
- gifMode: 'later',
- klipyApiKey: '',
- youtubeMode: 'later',
- youtubeApiKey: '',
- emailMode: 'later',
- emailEnabled: true,
- emailFromEmail: '',
- emailFromName: '',
- smtpHost: '',
- smtpPort: '587',
- smtpUsername: '',
- smtpPassword: '',
- smtpTlsMode: 'auto',
- blueskyMode: 'later',
- blueskyEnabled: true,
- blueskyClientName: '',
- blueskyClientUri: '',
- blueskyLogoUri: '',
- blueskyTosUri: '',
- blueskyPolicyUri: '',
- blueskyKeyId: '',
- blueskyPrivateKey: '',
-};
-
-const DEFAULT_MEDIA_EXPIRY_DRAFT: MediaExpiryDraft = {
- enabled: false,
- minSizeMb: '5',
- maxSizeMb: '500',
- maxEligibleSizeMb: '500',
- minLifetimeDays: '14',
- maxLifetimeDays: '1095',
- curve: '0.5',
- renewThresholdDays: '30',
- renewWindowDays: '30',
-};
-
-function wizardStepToIntegrationKind(step: WizardStep): IntegrationStepKind | null {
- switch (step) {
- case 'integration_gif':
- return 'gif';
- case 'integration_youtube':
- return 'youtube';
- case 'integration_email':
- return 'email';
- case 'integration_bluesky':
- return 'bluesky';
- default:
- return null;
+function writeStored(key: string, value: unknown): void {
+ try {
+ getProtectedSessionStorage()?.setItem(key, JSON.stringify(value));
+ } catch (error) {
+ logger.warn('Failed to save setup progress', error);
}
}
-function parsePort(value: string): number | null {
- const parsed = Number.parseInt(value, 10);
- return Number.isInteger(parsed) && parsed >= 1 && parsed <= 65535 ? parsed : null;
-}
-
-function parsePositiveNumber(value: string): number | null {
- const parsed = Number.parseFloat(value);
- return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
-}
-
-function parsePositiveInteger(value: string): number | null {
- const parsed = Number.parseInt(value, 10);
- return Number.isInteger(parsed) && parsed >= 1 ? parsed : null;
-}
-
-function parseDecayCurve(value: string): number | null {
- const parsed = Number.parseFloat(value);
- return Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : null;
+function removeStored(key: string): void {
+ try {
+ getProtectedSessionStorage()?.removeItem(key);
+ } catch (error) {
+ logger.warn('Failed to remove saved setup progress', error);
+ }
}
-function parseMediaExpiryDraft(draft: MediaExpiryDraft) {
- const minSizeMb = parsePositiveNumber(draft.minSizeMb);
- const maxSizeMb = parsePositiveNumber(draft.maxSizeMb);
- const maxEligibleSizeMb = parsePositiveNumber(draft.maxEligibleSizeMb);
- const minLifetimeDays = parsePositiveInteger(draft.minLifetimeDays);
- const maxLifetimeDays = parsePositiveInteger(draft.maxLifetimeDays);
- const curve = parseDecayCurve(draft.curve);
- const renewThresholdDays = parsePositiveInteger(draft.renewThresholdDays);
- const renewWindowDays = parsePositiveInteger(draft.renewWindowDays);
+function finishDraftFromConfig(config: InstanceConfigResponse, stored: unknown): FinishDraft {
+ const draft: FinishDraft = {
+ registrationMode: config.registration.mode,
+ singleCommunityEnabled: config.policy.single_community_enabled,
+ singleCommunityName: config.app_public.branding.product_name,
+ directMessagesDisabled: config.policy.direct_messages_disabled,
+ pushRelayConsentAccepted: config.push_relay.relay_consent_accepted,
+ };
+ if (!isRecord(stored)) return draft;
if (
- minSizeMb === null ||
- maxSizeMb === null ||
- maxEligibleSizeMb === null ||
- minLifetimeDays === null ||
- maxLifetimeDays === null ||
- curve === null ||
- renewThresholdDays === null ||
- renewWindowDays === null ||
- maxSizeMb <= minSizeMb ||
- maxEligibleSizeMb < maxSizeMb ||
- maxLifetimeDays < minLifetimeDays
+ stored.registrationMode === RegistrationModes.OPEN ||
+ stored.registrationMode === RegistrationModes.APPROVAL ||
+ stored.registrationMode === RegistrationModes.CLOSED
) {
- return null;
+ draft.registrationMode = stored.registrationMode;
}
- return {
- minSizeMb,
- maxSizeMb,
- maxEligibleSizeMb,
- minLifetimeDays,
- maxLifetimeDays,
- curve,
- renewThresholdDays,
- renewWindowDays,
- };
-}
-
-function isMediaExpiryStepValid(draft: MediaExpiryDraft): boolean {
- return !draft.enabled || parseMediaExpiryDraft(draft) !== null;
-}
-
-function isIntegrationStepValid(kind: IntegrationStepKind, draft: ServiceIntegrationDraft): boolean {
- switch (kind) {
- case 'gif':
- if (draft.gifMode === 'later') return true;
- return draft.klipyApiKey.trim().length > 0;
- case 'youtube':
- return draft.youtubeMode === 'later' || draft.youtubeApiKey.trim().length > 0;
- case 'email':
- if (draft.emailMode === 'later' || !draft.emailEnabled) return true;
- return (
- draft.emailFromEmail.trim().length > 0 &&
- draft.emailFromName.trim().length > 0 &&
- draft.smtpHost.trim().length > 0 &&
- parsePort(draft.smtpPort) !== null &&
- draft.smtpUsername.trim().length > 0 &&
- draft.smtpPassword.trim().length > 0
- );
- case 'bluesky':
- if (draft.blueskyMode === 'later' || !draft.blueskyEnabled) return true;
- return (
- draft.blueskyClientName.trim().length > 0 &&
- draft.blueskyClientUri.trim().length > 0 &&
- draft.blueskyKeyId.trim().length > 0 &&
- draft.blueskyPrivateKey.trim().length > 0
- );
+ if (typeof stored.singleCommunityEnabled === 'boolean') {
+ draft.singleCommunityEnabled = stored.singleCommunityEnabled;
}
-}
-
-function buildIntegrationsPatch(draft: ServiceIntegrationDraft, accountIdentity: AccountIdentityMode) {
- const integrations: {
- gif?: {
- provider: 'klipy';
- klipy_api_key?: string;
- };
- youtube?: {
- api_key: string;
- };
- email?: {
- enabled: boolean;
- provider: 'smtp';
- from_email: string;
- from_name: string;
- smtp: {
- host: string;
- port: number;
- username: string;
- password: string;
- tls_mode: SmtpTlsMode;
- };
- };
- bluesky?: {
- enabled: boolean;
- client_name: string;
- client_uri: string;
- logo_uri?: string;
- tos_uri?: string;
- policy_uri?: string;
- keys?: Array<{kid: string; private_key: string}>;
- };
- } = {};
- if (draft.gifMode === 'configure') {
- integrations.gif = {provider: 'klipy', klipy_api_key: draft.klipyApiKey.trim()};
+ if (typeof stored.singleCommunityName === 'string') {
+ draft.singleCommunityName = stored.singleCommunityName;
}
- if (draft.youtubeMode === 'configure') {
- integrations.youtube = {api_key: draft.youtubeApiKey.trim()};
+ if (typeof stored.directMessagesDisabled === 'boolean') {
+ draft.directMessagesDisabled = stored.directMessagesDisabled;
}
- if (draft.emailMode === 'configure' && accountIdentity === AccountIdentityModes.EMAIL) {
- const smtpPort = parsePort(draft.smtpPort) ?? 587;
- integrations.email = {
- enabled: draft.emailEnabled,
- provider: 'smtp',
- from_email: draft.emailFromEmail.trim(),
- from_name: draft.emailFromName.trim(),
- smtp: {
- host: draft.smtpHost.trim(),
- port: smtpPort,
- username: draft.smtpUsername.trim(),
- password: draft.smtpPassword.trim(),
- tls_mode: toSmtpTlsMode(draft.smtpTlsMode, smtpPort),
- },
- };
+ if (typeof stored.pushRelayConsentAccepted === 'boolean') {
+ draft.pushRelayConsentAccepted = stored.pushRelayConsentAccepted;
}
- if (draft.blueskyMode === 'configure') {
- integrations.bluesky = {
- enabled: draft.blueskyEnabled,
- client_name: draft.blueskyClientName.trim(),
- client_uri: draft.blueskyClientUri.trim(),
- logo_uri: draft.blueskyLogoUri.trim() || undefined,
- tos_uri: draft.blueskyTosUri.trim() || undefined,
- policy_uri: draft.blueskyPolicyUri.trim() || undefined,
- keys:
- draft.blueskyKeyId.trim() && draft.blueskyPrivateKey.trim()
- ? [{kid: draft.blueskyKeyId.trim(), private_key: draft.blueskyPrivateKey.trim()}]
- : undefined,
- };
- }
- return Object.keys(integrations).length > 0 ? integrations : undefined;
-}
-
-function buildMediaPatch(draft: MediaExpiryDraft) {
- if (!draft.enabled) {
- return {
- attachment_decay: {
- enabled: false,
- },
- };
- }
- const parsed = parseMediaExpiryDraft(draft);
- return {
- attachment_decay: {
- enabled: true,
- min_size_mb: parsed?.minSizeMb ?? Number.parseFloat(DEFAULT_MEDIA_EXPIRY_DRAFT.minSizeMb),
- max_size_mb: parsed?.maxSizeMb ?? Number.parseFloat(DEFAULT_MEDIA_EXPIRY_DRAFT.maxSizeMb),
- max_eligible_size_mb:
- parsed?.maxEligibleSizeMb ?? Number.parseFloat(DEFAULT_MEDIA_EXPIRY_DRAFT.maxEligibleSizeMb),
- min_lifetime_days: parsed?.minLifetimeDays ?? Number.parseInt(DEFAULT_MEDIA_EXPIRY_DRAFT.minLifetimeDays, 10),
- max_lifetime_days: parsed?.maxLifetimeDays ?? Number.parseInt(DEFAULT_MEDIA_EXPIRY_DRAFT.maxLifetimeDays, 10),
- curve: parsed?.curve ?? Number.parseFloat(DEFAULT_MEDIA_EXPIRY_DRAFT.curve),
- renew_threshold_days:
- parsed?.renewThresholdDays ?? Number.parseInt(DEFAULT_MEDIA_EXPIRY_DRAFT.renewThresholdDays, 10),
- renew_window_days: parsed?.renewWindowDays ?? Number.parseInt(DEFAULT_MEDIA_EXPIRY_DRAFT.renewWindowDays, 10),
- },
- };
+ return draft;
}
-export const SelfHostedSetupWizardGate = observer(() => {
+const SetupWizardController = observer(() => {
const {i18n} = useLingui();
- const shouldReduceMotion = useReducedMotion();
const authStoreAuthenticated = Authentication.isAuthenticated;
const accountWorkAdmitted = !AccountScopedWork.isSuspended;
- const themeHydrated = Theme.isHydrated;
- const fallbackProductName = resolveAppShellBranding(RuntimeConfig.getSnapshotOrNull()).productName;
- const welcomeInitialFocusRef = useRef<HTMLElement | null>(null);
- const registerFormDraftsRef = useRef<Map<string, AuthRegisterFormDraft>>(new Map());
- const stepNavigationLockedRef = useRef(false);
- const stepNavigationUnlockTimerRef = useRef<number | null>(null);
- const [layerHost, setLayerHost] = useState<HTMLDivElement | null>(null);
- const modalStackPlacement = ModalState.hasModalOpen() ? BEHIND_STACKED_MODAL_PLACEMENT : UNSTACKED_MODAL_CONTEXT;
+ const currentUserId = Authentication.currentUserId;
+ const accountFormId = useId();
+ const restoredDraft = useMemo(() => readStored(DRAFT_STORAGE_KEY), []);
- const [config, setConfig] = useState<InstanceConfigResponse | null>(null);
- const accountIdentity = config?.account_identity.mode ?? RuntimeConfig.accountIdentity;
- const [loadError, setLoadError] = useState<MessageDescriptor | null>(null);
- const [submitting, setSubmitting] = useState(false);
- const [submitError, setSubmitError] = useState<string | null>(null);
- const [stepNavigationLocked, setStepNavigationLocked] = useState(false);
- const [wizardSnapshot, setWizardSnapshot] = useState(createSetupWizardSnapshot);
- const [setupTheme, setSetupTheme] = useState<ThemeType>(ThemeTypes.DARK);
const [forceUnauthenticatedSetup, setForceUnauthenticatedSetup] = useState(false);
- const [integrationDraft, setIntegrationDraft] = useState<ServiceIntegrationDraft>(() => ({
- ...DEFAULT_INTEGRATION_DRAFT,
- }));
- const [mediaExpiryDraft, setMediaExpiryDraft] = useState<MediaExpiryDraft>(() => ({
- ...DEFAULT_MEDIA_EXPIRY_DRAFT,
- }));
- const [smtpTesting, setSmtpTesting] = useState(false);
- const [smtpTestResult, setSmtpTestResult] = useState<string | null>(null);
- const [signInMethod, setSignInMethod] = useState<AccountIdentityMode>(() => RuntimeConfig.accountIdentity);
- const [tagStyleChoice, setTagStyleChoice] = useState<TagStyle>(() => RuntimeConfig.tagStyle);
- const [savingSignInMethod, setSavingSignInMethod] = useState(false);
- const [signInMethodError, setSignInMethodError] = useState<string | null>(null);
- const [setupToken, setSetupToken] = useState('');
- const [setupTokenError, setSetupTokenError] = useState<string | null>(null);
- const [creatingRecoveryKit, setCreatingRecoveryKit] = useState(false);
+ const isAuthenticated = authStoreAuthenticated && !forceUnauthenticatedSetup;
- const [productName, setProductName] = useState('');
- const [themeColor, setThemeColor] = useState<number | null>(null);
- const [registrationMode, setRegistrationMode] = useState<RegistrationMode>('open');
- const [singleCommunityEnabled, setSingleCommunityEnabled] = useState(false);
- const [singleCommunityName, setSingleCommunityName] = useState('');
- const [directMessagesDisabled, setDirectMessagesDisabled] = useState(false);
- const [serviceSelection, setServiceSelection] = useState<ServiceSelection>({
- gif: false,
- youtube: false,
- bluesky: false,
+ const [step, setStep] = useState<WizardStep>(() => {
+ const stored = restoredDraft?.stepId;
+ if (!isWizardStep(stored) || !isBeforeAccountStep(stored)) return 'welcome';
+ const tokenNeeded = RuntimeConfig.appPublic.setup.setup_token_required === true;
+ return tokenNeeded && stored !== 'welcome' ? 'setup_token' : stored;
});
- const [pushRelayConsentAccepted, setPushRelayConsentAccepted] = useState(false);
- const [premiumMode, setPremiumMode] = useState<PremiumMode>('mirror');
- const [assets, setAssets] = useState<ReadonlyArray<BrandingAssetState>>(() =>
- BRANDING_ASSET_KINDS.map((kind) => ({kind, url: null, preview: null})),
- );
-
- const getRegisterFormDraft = useCallback((draftKey: string): AuthRegisterFormDraft | undefined => {
- const draft = registerFormDraftsRef.current.get(draftKey);
- if (!draft) {
- return undefined;
- }
- return {
- ...draft,
- formValues: {...draft.formValues},
- };
- }, []);
+ const [direction, setDirection] = useState(0);
+ const [returnToReview, setReturnToReview] = useState(false);
+ const [finished, setFinished] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [stepError, setStepError] = useState<string | null>(null);
+ const [showErrors, setShowErrors] = useState(false);
- const setRegisterFormDraft = useCallback((draftKey: string, draft: AuthRegisterFormDraft) => {
- registerFormDraftsRef.current.set(draftKey, {
- ...draft,
- formValues: {...draft.formValues},
- });
- }, []);
+ const [config, setConfig] = useState<InstanceConfigResponse | null>(null);
+ const [loadError, setLoadError] = useState<MessageDescriptor | null>(null);
- const clearRegisterFormDraft = useCallback((draftKey: string) => {
- registerFormDraftsRef.current.delete(draftKey);
- }, []);
+ const {value: setupToken, setValue: setSetupToken, setError: setSetupTokenError} = useSetupTokenDraft();
+ const setupTokenFormRef = useRef<HTMLFormElement | null>(null);
+ const [setupTokenRejected, setSetupTokenRejected] = useState(false);
+ const [identityDraft] = useState(() => new SetupIdentityDraft(restoredDraft));
+ const {signInMethod, tagStyle, emailAnswer, setEmailAnswer} = identityDraft;
+ const signInMethodFormRef = useRef<HTMLFormElement | null>(null);
+ const sharedUsernamesFormRef = useRef<HTMLFormElement | null>(null);
+ const [accountDraft] = useState(() => new SetupAccountDraft(restoredDraft));
+ const {values: accountValues} = accountDraft;
+ const [stepsBeforeAccount, setStepsBeforeAccount] = useState<number | null>(null);
+ const [submitSlot, setSubmitSlot] = useState<HTMLElement | null>(null);
+ const wizardRef = useRef<HTMLDivElement | null>(null);
+ const communitiesFormRef = useRef<HTMLFormElement | null>(null);
- const authRegisterDraftContextValue = useMemo(
- () => ({
- getRegisterFormDraft,
- setRegisterFormDraft,
- clearRegisterFormDraft,
- }),
- [clearRegisterFormDraft, getRegisterFormDraft, setRegisterFormDraft],
- );
+ const [recoveryKitDraft] = useState(() => new SetupRecoveryKitDraft());
+ const {draft: smtpDraft, hydrate: hydrateEmailDraft, setFailure: setSmtpFailure} = useSetupEmailDraft();
+ const emailServiceFormRef = useRef<HTMLFormElement | null>(null);
+ const emailSenderFormRef = useRef<HTMLFormElement | null>(null);
+ const {productName, themeColor, assets, hydrate: hydrateBrandingDraft} = useSetupBrandingDraft();
+ const nameFormRef = useRef<HTMLFormElement | null>(null);
+ const brandingFormRef = useRef<HTMLFormElement | null>(null);
+ const {draft: finishDraft, setDraft: setFinishDraft} = useSetupPolicyDraft();
+ const serviceDraftCache = useRef<ServiceKeyDraft | null>(null);
+ const servicesFormRef = useRef<HTMLFormElement | null>(null);
+ const {enabled: attachmentsEnabled, setEnabled: setAttachmentsEnabled} = useSetupAttachmentsDraft();
+ const attachmentsFormRef = useRef<HTMLFormElement | null>(null);
- const isAuthenticated = authStoreAuthenticated && !forceUnauthenticatedSetup;
+ const identityLocked = RuntimeConfig.appPublic.setup.account_identity_locked === true;
+ const accountIdentity: AccountIdentityMode =
+ config?.account_identity.mode ?? (identityLocked ? RuntimeConfig.accountIdentity : signInMethod);
+ const conditions: WizardConditions = {
+ isAuthenticated,
+ accountIdentity,
+ identityLocked,
+ adminExists:
+ identityLocked &&
+ RuntimeConfig.appPublic.setup.account_identity_lock_reason === AccountIdentityLockReasons.ADMIN_EXISTS,
+ setupTokenRequired: RuntimeConfig.appPublic.setup.setup_token_required === true,
+ setupTokenRejected,
+ emailsEnabled: RuntimeConfig.emailsEnabled,
+ emailAnswer,
+ finished,
+ };
+ const awaitingConfig = isAuthenticated && config === null && !finished;
+ const shownStep = awaitingConfig ? step : resolveStep(step, conditions);
+ if (shownStep !== step) {
+ setStep(shownStep);
+ }
- const clearStepNavigationLock = useCallback(() => {
- if (stepNavigationUnlockTimerRef.current !== null) {
- window.clearTimeout(stepNavigationUnlockTimerRef.current);
- stepNavigationUnlockTimerRef.current = null;
+ useEffect(() => {
+ if (finished) {
+ removeStored(DRAFT_STORAGE_KEY);
+ if (currentUserId) removeStored(userStorageKey(currentUserId));
+ return;
}
- stepNavigationLockedRef.current = false;
- setStepNavigationLocked(false);
- }, []);
-
- const beginStepNavigation = useCallback(() => {
- if (stepNavigationLockedRef.current) return false;
- stepNavigationLockedRef.current = true;
- setStepNavigationLocked(true);
- if (stepNavigationUnlockTimerRef.current !== null) {
- window.clearTimeout(stepNavigationUnlockTimerRef.current);
+ if (!isAuthenticated) {
+ const draft: PreAccountDraft = {
+ stepId: step,
+ signInMethod,
+ tagStyle,
+ emailAnswer,
+ username: accountValues.username,
+ email: accountValues.email,
+ };
+ writeStored(DRAFT_STORAGE_KEY, draft);
+ return;
}
- stepNavigationUnlockTimerRef.current = window.setTimeout(() => {
- stepNavigationUnlockTimerRef.current = null;
- stepNavigationLockedRef.current = false;
- setStepNavigationLocked(false);
- }, STEP_NAVIGATION_LOCK_MS);
- return true;
- }, []);
-
- useEffect(
- () => () => {
- if (stepNavigationUnlockTimerRef.current !== null) {
- window.clearTimeout(stepNavigationUnlockTimerRef.current);
- stepNavigationUnlockTimerRef.current = null;
- }
- stepNavigationLockedRef.current = false;
- },
- [],
- );
+ if (!config || !currentUserId) return;
+ const draft: PostAccountDraft = {
+ stepId: step,
+ finishDraft,
+ emailAnswer,
+ stepsBeforeAccount: stepsBeforeAccount ?? 0,
+ };
+ writeStored(userStorageKey(currentUserId), draft);
+ removeStored(DRAFT_STORAGE_KEY);
+ }, [
+ finished,
+ isAuthenticated,
+ config,
+ currentUserId,
+ step,
+ signInMethod,
+ tagStyle,
+ emailAnswer,
+ accountValues,
+ finishDraft,
+ stepsBeforeAccount,
+ ]);
useEffect(() => {
if (authStoreAuthenticated || !forceUnauthenticatedSetup) return;
@@ -564,23 +370,13 @@ export const SelfHostedSetupWizardGate = observer(() => {
const resetSetupSession = useCallback(async () => {
setForceUnauthenticatedSetup(true);
- registerFormDraftsRef.current.clear();
+ accountDraft.resetSession();
setConfig(null);
setLoadError(null);
- setSubmitError(null);
- setSubmitting(false);
- setWizardSnapshot(createSetupWizardSnapshot());
- clearStepNavigationLock();
- setIntegrationDraft({...DEFAULT_INTEGRATION_DRAFT});
- setMediaExpiryDraft({...DEFAULT_MEDIA_EXPIRY_DRAFT});
- setPushRelayConsentAccepted(false);
- setSmtpTesting(false);
- setSmtpTestResult(null);
- setSignInMethodError(null);
- setSavingSignInMethod(false);
- setSetupToken('');
- setSetupTokenError(null);
- setCreatingRecoveryKit(false);
+ setStepError(null);
+ setBusy(false);
+ setStep('welcome');
+ setDirection(0);
try {
await SessionManager.logout();
} catch (error) {
@@ -589,70 +385,70 @@ export const SelfHostedSetupWizardGate = observer(() => {
SessionManager.setUserId(null);
}
Authentication.handleLogout({skipRedirect: true});
- }, [clearStepNavigationLock]);
+ }, [accountDraft]);
const signOutOfSetup = useCallback(async () => {
await resetSetupSession();
if (RuntimeConfig.appPublic.setup.setup_token_required !== true) RouterUtils.replaceWith(Routes.LOGIN);
}, [resetSetupSession]);
- const hydrateFromConfig = useCallback((next: InstanceConfigResponse) => {
- setConfig(next);
- setProductName(next.app_public.branding.product_name);
- setThemeColor(hexToNumber(next.app_public.branding.theme_color));
- setRegistrationMode(next.registration.mode);
- setSingleCommunityEnabled(next.policy.single_community_enabled);
- setDirectMessagesDisabled(next.policy.direct_messages_disabled);
- setPremiumMode(next.policy.premium_mode);
- setPushRelayConsentAccepted(next.push_relay.relay_consent_accepted);
- setServiceSelection({
- gif: next.policy.services_resolved.gif_enabled,
- youtube: next.policy.services_resolved.youtube_enabled,
- bluesky: next.policy.services_resolved.bluesky_enabled,
- });
- setIntegrationDraft((current) => ({
- ...current,
- emailEnabled: next.integrations.email.effective_enabled || next.integrations.email.enabled !== false,
- emailFromEmail: next.integrations.email.from_email ?? current.emailFromEmail,
- emailFromName: next.integrations.email.from_name ?? current.emailFromName,
- smtpHost: next.integrations.email.smtp.host ?? current.smtpHost,
- smtpPort: next.integrations.email.smtp.port ? String(next.integrations.email.smtp.port) : current.smtpPort,
- smtpUsername: next.integrations.email.smtp.username ?? current.smtpUsername,
- smtpTlsMode: next.integrations.email.smtp.tls_mode ?? current.smtpTlsMode,
- blueskyEnabled: next.integrations.bluesky.effective_enabled || next.integrations.bluesky.enabled !== false,
- blueskyClientName: next.integrations.bluesky.client_name ?? current.blueskyClientName,
- blueskyClientUri: next.integrations.bluesky.client_uri ?? current.blueskyClientUri,
- blueskyLogoUri: next.integrations.bluesky.logo_uri ?? current.blueskyLogoUri,
- blueskyTosUri: next.integrations.bluesky.tos_uri ?? current.blueskyTosUri,
- blueskyPolicyUri: next.integrations.bluesky.policy_uri ?? current.blueskyPolicyUri,
- }));
- setMediaExpiryDraft(() => {
- const attachmentDecay = next.media.attachment_decay;
- const effective = attachmentDecay.effective;
- return {
- enabled: attachmentDecay.enabled ?? false,
- minSizeMb: String(attachmentDecay.min_size_mb ?? effective.min_size_mb),
- maxSizeMb: String(attachmentDecay.max_size_mb ?? effective.max_size_mb),
- maxEligibleSizeMb: String(attachmentDecay.max_eligible_size_mb ?? effective.max_eligible_size_mb),
- minLifetimeDays: String(attachmentDecay.min_lifetime_days ?? effective.min_lifetime_days),
- maxLifetimeDays: String(attachmentDecay.max_lifetime_days ?? effective.max_lifetime_days),
- curve: String(attachmentDecay.curve ?? effective.curve),
- renewThresholdDays: String(attachmentDecay.renew_threshold_days ?? effective.renew_threshold_days),
- renewWindowDays: String(attachmentDecay.renew_window_days ?? effective.renew_window_days),
+ const conditionsRef = useRef(conditions);
+ conditionsRef.current = conditions;
+
+ const hydrateFromConfig = useCallback(
+ (next: InstanceConfigResponse, userId: string | null) => {
+ const stored = userId ? readStored(userStorageKey(userId)) : null;
+ const storedAnswer = isEmailAnswer(stored?.emailAnswer) ? stored.emailAnswer : null;
+ const answer = storedAnswer ?? emailAnswer;
+ setConfig(next);
+ hydrateBrandingDraft(next);
+ hydrateEmailDraft(next);
+ setAttachmentsEnabled(next.media.attachment_decay.enabled ?? next.media.attachment_decay.effective.enabled);
+ setFinishDraft(finishDraftFromConfig(next, stored?.finishDraft));
+ setEmailAnswer(answer);
+ const after: WizardConditions = {
+ ...conditionsRef.current,
+ isAuthenticated: true,
+ finished: false,
+ accountIdentity: next.account_identity.mode,
+ emailAnswer: answer,
};
- });
- setAssets(BRANDING_ASSET_KINDS.map((kind) => ({kind, url: brandingAssetUrl(next, kind), preview: null})));
- }, []);
+ setStepsBeforeAccount((current) => {
+ if (typeof stored?.stepsBeforeAccount === 'number' && stored.stepsBeforeAccount > 0) {
+ return stored.stepsBeforeAccount;
+ }
+ return (
+ current ??
+ countedStepsBeforeAccount({
+ ...after,
+ setupTokenRequired: true,
+ identityLocked: false,
+ emailsEnabled: false,
+ })
+ );
+ });
+ const storedStep =
+ isWizardStep(stored?.stepId) && visibleSteps(after).includes(stored.stepId)
+ ? stored.stepId
+ : firstStepAfterAccount(after);
+ const resumeStep =
+ storedStep === 'email_sender' && !next.integrations.email.smtp.host?.trim() ? 'email_service' : storedStep;
+ setStep(resumeStep);
+ setDirection(1);
+ setBusy(false);
+ },
+ [emailAnswer, hydrateBrandingDraft, hydrateEmailDraft, setAttachmentsEnabled, setEmailAnswer, setFinishDraft],
+ );
useEffect(() => {
- if (!isAuthenticated || config || !accountWorkAdmitted) return;
+ if (!isAuthenticated || config || !accountWorkAdmitted || finished) return;
let cancelled = false;
setLoadError(null);
void (async () => {
try {
const next = await fetchInstanceConfig();
if (cancelled) return;
- hydrateFromConfig(next);
+ hydrateFromConfig(next, Authentication.currentUserId);
} catch (error) {
if (cancelled || isAccountTransitionAbortError(error)) return;
const cause =
@@ -674,341 +470,220 @@ export const SelfHostedSetupWizardGate = observer(() => {
return () => {
cancelled = true;
};
- }, [isAuthenticated, config, accountWorkAdmitted, hydrateFromConfig, resetSetupSession]);
-
- const serviceAvailability: ServiceAvailability = useMemo(
- () => ({
- gif:
- (config?.policy.services_available.gif ?? false) ||
- (integrationDraft.gifMode === 'configure' && integrationDraft.klipyApiKey.trim().length > 0),
- youtube:
- (config?.policy.services_available.youtube ?? false) ||
- (integrationDraft.youtubeMode === 'configure' && integrationDraft.youtubeApiKey.trim().length > 0),
- bluesky:
- (config?.policy.services_available.bluesky ?? false) ||
- (integrationDraft.blueskyMode === 'configure' &&
- integrationDraft.blueskyEnabled &&
- integrationDraft.blueskyKeyId.trim().length > 0 &&
- integrationDraft.blueskyPrivateKey.trim().length > 0),
- }),
- [config, integrationDraft],
- );
+ }, [isAuthenticated, config, accountWorkAdmitted, finished, hydrateFromConfig, resetSetupSession]);
- const hasConfig = Boolean(config);
- const identityLocked = RuntimeConfig.appPublic.setup.account_identity_locked === true;
- const setupTokenRequired = RuntimeConfig.appPublic.setup.setup_token_required === true;
- const syncedSnapshot =
- wizardSnapshot.context.isAuthenticated !== isAuthenticated ||
- wizardSnapshot.context.hasConfig !== hasConfig ||
- wizardSnapshot.context.accountIdentity !== accountIdentity ||
- wizardSnapshot.context.identityLocked !== identityLocked ||
- wizardSnapshot.context.setupTokenRequired !== setupTokenRequired
- ? transitionSetupWizardSnapshot(wizardSnapshot, {
- type: 'wizard.sync',
- isAuthenticated,
- hasConfig,
- accountIdentity,
- identityLocked,
- setupTokenRequired,
- })
- : wizardSnapshot;
- if (syncedSnapshot !== wizardSnapshot) {
- setWizardSnapshot(syncedSnapshot);
- }
- const wizardModel = selectSetupWizardModel(syncedSnapshot);
- const {step, steps, direction} = wizardModel;
- const currentUserId = Authentication.currentUserId;
const hasRecoveryKit = currentUserId ? (RecoveryKitStatus.get(currentUserId)?.hasRecoveryKit ?? false) : false;
useEffect(() => {
- if (step !== 'admin_recovery_kit') return;
+ if (step !== 'recovery_kit' || !isAuthenticated) return;
void RecoveryKitCommands.fetchRecoveryKitStatus().catch((error) => {
logger.warn('Failed to load recovery kit status', error);
});
- }, [step]);
-
- const productNameTrimmed = productName.trim();
- const productNameError = productNameTrimmed.length < 1 || productNameTrimmed.length > 80;
- const singleCommunityNameTrimmed = singleCommunityName.trim();
- const singleCommunityNameError =
- singleCommunityEnabled && (singleCommunityNameTrimmed.length < 1 || singleCommunityNameTrimmed.length > 100);
+ }, [step, isAuthenticated]);
- const canAdvance = useMemo(() => {
- if (step === 'welcome') return !isAuthenticated || Boolean(config);
- if (step === 'admin_account' || step === 'loading') return false;
- if (step === 'setup_token') return setupToken.trim().length > 0;
- if (step === 'sign_in_method') return !savingSignInMethod;
- if (step === 'admin_recovery_kit') return hasRecoveryKit;
- if (step === 'branding') return !productNameError;
- if (step === 'community') return !singleCommunityNameError;
- if (step === 'media_expiry') return isMediaExpiryStepValid(mediaExpiryDraft);
- if (step === 'push_relay_consent') return true;
- const integrationKind = wizardStepToIntegrationKind(step);
- if (integrationKind) return isIntegrationStepValid(integrationKind, integrationDraft);
- return true;
- }, [
- step,
- isAuthenticated,
- config,
- productNameError,
- singleCommunityNameError,
- mediaExpiryDraft,
- integrationDraft,
- savingSignInMethod,
- hasRecoveryKit,
- setupToken,
- ]);
+ const goTo = useCallback((target: WizardStep, nextDirection: number) => {
+ setStep(target);
+ setDirection(nextDirection);
+ setStepError(null);
+ setShowErrors(false);
+ }, []);
- const goNext = useCallback(() => {
- if (!beginStepNavigation()) return;
- setSubmitError(null);
- setWizardSnapshot((current) => transitionSetupWizardSnapshot(current, {type: 'wizard.next'}));
- }, [beginStepNavigation]);
+ const advance = useCallback(() => {
+ if (returnToReview && step !== 'email_service') {
+ setReturnToReview(false);
+ goTo('review', 1);
+ return;
+ }
+ goTo(nextStep(step, conditionsRef.current), 1);
+ }, [goTo, returnToReview, step]);
+ const back = previousStep(step, conditions);
const goBack = useCallback(() => {
- if (!beginStepNavigation()) return;
- setSubmitError(null);
- setWizardSnapshot((current) => transitionSetupWizardSnapshot(current, {type: 'wizard.back'}));
- }, [beginStepNavigation]);
+ if (back === null) return;
+ setReturnToReview(false);
+ goTo(back, -1);
+ }, [back, goTo]);
- const handleSetupTokenChange = useCallback((value: string) => {
- setSetupToken(value);
+ const handleSetupTokenRejected = useCallback(() => {
+ setSetupTokenRejected(true);
+ setSetupToken('');
setSetupTokenError(null);
- }, []);
+ setStepError(i18n._(SETUP_TOKEN_REJECTED_DESCRIPTOR));
+ setStep('setup_token');
+ setDirection(-1);
+ }, [i18n, setSetupToken, setSetupTokenError]);
- const submittedSetupToken = setupToken.trim() || undefined;
-
- const handleSetupTokenRejected = useCallback((message: string) => {
- setSetupTokenError(message);
- setWizardSnapshot((current) => transitionSetupWizardSnapshot(current, {type: 'wizard.setupTokenRejected'}));
- }, []);
+ const describeError = useCallback((error: unknown) => FormUtils.extractErrorMessage(i18n, error), [i18n]);
- const submitSignInMethod = useCallback(async () => {
- if (savingSignInMethod) return;
- setSavingSignInMethod(true);
- setSignInMethodError(null);
- let locked = false;
- const effectiveTagStyle = signInMethod === AccountIdentityModes.USERNAME ? TagStyles.NONE : tagStyleChoice;
+ const saveConfig = async (patch: Parameters<typeof updateInstanceConfig>[0]): Promise<boolean> => {
try {
- let saved: Awaited<ReturnType<typeof setSetupAccountIdentity>> | null = null;
- try {
- saved = await setSetupAccountIdentity(signInMethod, effectiveTagStyle, submittedSetupToken);
- } catch (error) {
- const setupTokenViolation = failureValidationErrors(error)?.find(
- (violation) => violation.path === 'setup_token',
- );
- if (setupTokenViolation) {
- handleSetupTokenRejected(setupTokenViolation.message);
- setSavingSignInMethod(false);
- return;
- }
- if (failureCode(error) !== APIErrorCodes.ACCOUNT_IDENTITY_LOCKED) {
- throw error;
- }
- locked = true;
- logger.info('The sign-in method is already locked');
- }
- await RuntimeConfig.refreshDiscovery();
- if (saved) {
- RuntimeConfig.applyAccountIdentity(saved.mode, saved.tag_style);
- }
+ setConfig(await updateInstanceConfig(patch));
+ return true;
} catch (error) {
- logger.error('Failed to save the sign-in method', error);
- setSignInMethodError(FormUtils.extractErrorMessage(i18n, error));
- setSavingSignInMethod(false);
- return;
- }
- const lockedMode = RuntimeConfig.accountIdentity;
- const lockedTagStyle = RuntimeConfig.tagStyle;
- const modeDiffers = lockedMode !== signInMethod;
- if (locked && (modeDiffers || lockedTagStyle !== effectiveTagStyle)) {
- setSignInMethod(lockedMode);
- setTagStyleChoice(lockedTagStyle);
- setSignInMethodError(
- i18n._(
- !modeDiffers
- ? USERNAME_STYLE_LOCKED_DESCRIPTOR
- : lockedMode === AccountIdentityModes.USERNAME
- ? SIGN_IN_METHOD_LOCKED_USERNAME_DESCRIPTOR
- : SIGN_IN_METHOD_LOCKED_EMAIL_DESCRIPTOR,
- ),
- );
- setSavingSignInMethod(false);
- return;
+ logger.error('Failed to save a setup step', error);
+ setStepError(describeError(error));
+ return false;
}
- setSavingSignInMethod(false);
- goNext();
- }, [savingSignInMethod, signInMethod, tagStyleChoice, submittedSetupToken, handleSetupTokenRejected, i18n, goNext]);
+ };
- const handleSignInMethodChange = useCallback((mode: AccountIdentityMode) => {
- setSignInMethod(mode);
- setSignInMethodError(null);
- }, []);
+ const smtpPort = parseSmtpPort(smtpDraft.port);
- const createRecoveryKit = useCallback(async () => {
- setCreatingRecoveryKit(true);
+ const finish = async () => {
+ if (!config) return;
+ setStepError(null);
try {
- await RecoveryKitCommands.createAndShowRecoveryKit();
+ const next = await updateInstanceConfig({
+ registration: {mode: finishDraft.registrationMode},
+ policy: {
+ single_community_enabled: finishDraft.singleCommunityEnabled,
+ ...(finishDraft.singleCommunityEnabled
+ ? {single_community_name: finishDraft.singleCommunityName.trim()}
+ : {}),
+ ...(finishDraft.directMessagesDisabled === config.policy.direct_messages_disabled
+ ? {}
+ : {direct_messages_disabled: finishDraft.directMessagesDisabled}),
+ },
+ ...(finishDraft.pushRelayConsentAccepted === config.push_relay.relay_consent_accepted
+ ? {}
+ : {push_relay: {relay_consent_accepted: finishDraft.pushRelayConsentAccepted}}),
+ app_public: {setup: {configured: true}},
+ });
+ setConfig(next);
+ setFinished(true);
+ goTo('done', 1);
} catch (error) {
- logger.error('Failed to create the administrator recovery kit', error);
- FormUtils.pushApiErrorModal(i18n, error);
+ logger.error('Failed to complete instance setup', error);
+ setStepError(describeError(error));
+ }
+ };
+
+ let primaryDisabled: boolean;
+ switch (step) {
+ case 'setup_token':
+ primaryDisabled = setupToken.trim().length === 0;
+ break;
+ case 'recovery_kit':
+ primaryDisabled = !recoveryKitDraft.stored;
+ break;
+ case 'email_service':
+ case 'email_sender':
+ primaryDisabled = !smtpDraft.host.trim() || smtpPort === null;
+ break;
+ default:
+ primaryDisabled = false;
+ break;
+ }
+
+ const runStep = async (submit: () => Promise<void> | void) => {
+ if (busy || primaryDisabled) return;
+ setBusy(true);
+ setStepError(null);
+ try {
+ const pending = submit();
+ if (pending !== undefined) await pending;
} finally {
- setCreatingRecoveryKit(false);
+ setBusy(false);
}
- }, [i18n]);
+ };
- const knownWithoutRecoveryKit = currentUserId
- ? RecoveryKitStatus.get(currentUserId)?.hasRecoveryKit === false
- : false;
- const handleCreateRecoveryKit = useCallback(() => {
- if (knownWithoutRecoveryKit) {
- void createRecoveryKit();
+ const runPrimary = async () => {
+ if (step === 'sign_in_method') {
+ signInMethodFormRef.current?.requestSubmit();
return;
}
- confirmNewRecoveryKit(i18n, createRecoveryKit);
- }, [knownWithoutRecoveryKit, i18n, createRecoveryKit]);
-
- const handleUploadAsset = useCallback(
- async (kind: SetupBrandingAssetKind) => {
- try {
- const [file] = await openFilePicker({accept: getAcceptString('guild_icon')});
- if (!file) return;
- const dataUrl = await fileToBase64(file);
- setAssets((current) => current.map((asset) => (asset.kind === kind ? {...asset, preview: dataUrl} : asset)));
- } catch (error) {
- logger.error('Failed to read branding asset file', error);
- setSubmitError(i18n._(ASSET_UPLOAD_ERROR_DESCRIPTOR));
+ if (step === 'shared_usernames') {
+ sharedUsernamesFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'setup_token') {
+ setupTokenFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'name') {
+ nameFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'gif_youtube') {
+ servicesFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'attachments') {
+ attachmentsFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'email_service') {
+ emailServiceFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'email_sender') {
+ emailSenderFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'communities') {
+ communitiesFormRef.current?.requestSubmit();
+ return;
+ }
+ if (step === 'look') {
+ brandingFormRef.current?.requestSubmit();
+ return;
+ }
+ await runStep(() => {
+ switch (step) {
+ case 'review':
+ return finish();
+ case 'sign_in_to_finish':
+ RouterUtils.replaceWith(Routes.LOGIN);
+ return;
+ default:
+ advance();
+ return;
}
- },
- [i18n],
- );
-
- const handleClearAsset = useCallback((kind: SetupBrandingAssetKind) => {
- setAssets((current) =>
- current.map((asset) => (asset.kind === kind ? {...asset, preview: null, url: null} : asset)),
- );
- }, []);
-
- const handleToggleService = useCallback((service: keyof ServiceSelection, value: boolean) => {
- setServiceSelection((current) => ({...current, [service]: value}));
- }, []);
+ });
+ };
- const handleIntegrationDraftChange = useCallback((patch: Partial<ServiceIntegrationDraft>) => {
- setIntegrationDraft((current) => ({...current, ...patch}));
- setSmtpTestResult(null);
- }, []);
+ const switchEmailToLater = () => {
+ setEmailAnswer('later');
+ setSmtpFailure(null);
+ setReturnToReview(false);
+ goTo(returnToReview ? 'review' : 'name', 1);
+ };
- const handleMediaExpiryDraftChange = useCallback((patch: Partial<MediaExpiryDraft>) => {
- setMediaExpiryDraft((current) => ({...current, ...patch}));
- }, []);
+ const reviewChange = (target: WizardStep) => {
+ setReturnToReview(true);
+ goTo(target, -1);
+ };
- const handleTestSmtp = useCallback(async () => {
- const port = parsePort(integrationDraft.smtpPort);
- if (port === null) return;
- setSmtpTesting(true);
- setSmtpTestResult(null);
- try {
- const result = await testSmtpConfig({
- host: integrationDraft.smtpHost.trim(),
- port,
- username: integrationDraft.smtpUsername.trim(),
- password: integrationDraft.smtpPassword,
- tls_mode: toSmtpTlsMode(integrationDraft.smtpTlsMode, port),
- });
- setSmtpTestResult(result.ok ? 'ok' : (result.error ?? 'failed'));
- } catch (error) {
- logger.error('Failed to validate SMTP configuration', error);
- setSmtpTestResult(FormUtils.extractErrorMessage(i18n, error));
- } finally {
- setSmtpTesting(false);
- }
- }, [integrationDraft, i18n]);
+ const renderAccountSubmit = (state: {disabled: boolean; submitting: boolean; missingFields: Array<MissingField>}) => {
+ if (!submitSlot) return null;
+ const submitting = state.submitting || awaitingConfig;
+ return createPortal(
+ <SubmitTooltip
+ missingFields={submitting ? [] : state.missingFields}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-account-submit.submit-tooltip"
+ >
+ <Button
+ type="submit"
+ form={accountFormId}
+ disabled={state.disabled && !submitting}
+ submitting={submitting}
+ className={styles.primaryButton}
+ data-flx="app.self-hosted-setup-wizard-gate.create-account-button"
+ >
+ {i18n._(CREATE_ACCOUNT_DESCRIPTOR)}
+ </Button>
+ </SubmitTooltip>,
+ submitSlot,
+ );
+ };
- const submit = useCallback(async () => {
+ const openInstance = () => {
if (!config) return;
- setSubmitting(true);
- setSubmitError(null);
- try {
- for (const asset of assets) {
- const original = brandingAssetUrl(config, asset.kind);
- if (asset.preview) {
- await uploadBrandingAsset(asset.kind, asset.preview);
- } else if (asset.url === null && original !== null) {
- await uploadBrandingAsset(asset.kind, null);
- }
- }
- const nextConfig = await updateInstanceConfig({
- integrations: buildIntegrationsPatch(integrationDraft, accountIdentity),
- media: buildMediaPatch(mediaExpiryDraft),
- push_relay:
- config.push_relay.relay_consent_accepted === pushRelayConsentAccepted
- ? undefined
- : {relay_consent_accepted: pushRelayConsentAccepted},
- registration: {mode: registrationMode},
- app_public: {
- branding: {
- product_name: productNameTrimmed,
- theme_color: themeColor === null ? null : numberToHexColor(themeColor),
- },
- setup: {configured: true},
- },
- policy: {
- single_community_enabled: singleCommunityEnabled,
- single_community_name: singleCommunityEnabled ? singleCommunityNameTrimmed : undefined,
- direct_messages_disabled: directMessagesDisabled,
- premium_mode: premiumMode,
- services: {
- gif_enabled: serviceAvailability.gif ? serviceSelection.gif : undefined,
- youtube_enabled: serviceAvailability.youtube ? serviceSelection.youtube : undefined,
- bluesky_enabled: serviceAvailability.bluesky ? serviceSelection.bluesky : undefined,
- },
- },
- });
- hydrateFromConfig(nextConfig);
- RuntimeConfig.applyAdminInstanceConfig(nextConfig);
- } catch (error) {
- logger.error('Failed to complete instance setup', error);
- setSubmitError(FormUtils.extractErrorMessage(i18n, error));
- setSubmitting(false);
- }
- }, [
- config,
- assets,
- accountIdentity,
- registrationMode,
- integrationDraft,
- mediaExpiryDraft,
- productNameTrimmed,
- themeColor,
- singleCommunityEnabled,
- singleCommunityNameTrimmed,
- directMessagesDisabled,
- pushRelayConsentAccepted,
- premiumMode,
- serviceAvailability,
- serviceSelection,
- hydrateFromConfig,
- i18n,
- ]);
-
- const isLoading = isAuthenticated && !config && !loadError;
- const canGoBack = wizardModel.stepIndex > 0 && !submitting && step !== 'loading';
- const isFinish = step === 'finish';
- const showBackButton = canGoBack;
- const showPrimaryButton = !loadError && step !== 'admin_account' && step !== 'loading';
- const showFooter = !loadError && (showBackButton || showPrimaryButton);
- const primaryButtonLabel = isLoading ? i18n._(LOADING_DESCRIPTOR) : i18n._(NEXT_DESCRIPTOR);
- const primaryButtonDisabled = !canAdvance || stepNavigationLocked;
- const primaryButtonSubmitting = isLoading || savingSignInMethod;
- const handlePrimaryButton = step === 'sign_in_method' ? submitSignInMethod : goNext;
- const footerButtonInitial = shouldReduceMotion ? {opacity: 0} : {opacity: 0, y: 4, scale: 0.98};
- const footerButtonAnimate = shouldReduceMotion ? {opacity: 1} : {opacity: 1, y: 0, scale: 1};
- const footerButtonExit = shouldReduceMotion ? {opacity: 0} : {opacity: 0, y: -4, scale: 0.98};
+ removeStored(DRAFT_STORAGE_KEY);
+ if (currentUserId) removeStored(userStorageKey(currentUserId));
+ RuntimeConfig.applyAdminInstanceConfig(config);
+ };
- useEffect(() => {
- if (isAuthenticated) return;
- Theme.setTheme(setupTheme);
- }, [isAuthenticated, setupTheme, themeHydrated]);
+ useAuthLayoutVariant();
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
@@ -1030,338 +705,464 @@ export const SelfHostedSetupWizardGate = observer(() => {
};
}, []);
- return (
- <AuthRegisterDraftContext.Provider value={authRegisterDraftContextValue}>
- <div ref={setLayerHost} className={styles.backdrop} data-flx="app.self-hosted-setup-wizard-gate.backdrop">
- {layerHost && (
- <PortalHostContext.Provider value={layerHost}>
- <ModalStackContext.Provider value={modalStackPlacement}>
- <Modal.Root
- size="medium"
- centered
- disableHistoryManagement
- className={styles.modal}
- initialFocusRef={welcomeInitialFocusRef}
- backdropSlot={
- <div className={styles.backdropVisual} data-flx="app.self-hosted-setup-wizard-gate.backdrop-visual" />
- }
- data-flx="app.self-hosted-setup-wizard-gate.modal"
- >
- <Modal.Header
- title={i18n._(HEADER_DESCRIPTOR, {productName: fallbackProductName})}
- icon={<WrenchIcon size={22} weight="bold" data-flx="app.self-hosted-setup-wizard-gate.header-icon" />}
- hideCloseButton
- data-flx="app.self-hosted-setup-wizard-gate.header"
- />
- <Modal.Content
- className={styles.contentScroller}
- contentClassName={styles.contentFrame}
- data-flx="app.self-hosted-setup-wizard-gate.content"
+ const isAccountStep = step === 'account';
+ const isDone = step === 'done';
+ const loadingSession = awaitingConfig && !isAccountStep && !loadError;
+ const progress = loadingSession ? null : wizardProgress(step, conditions, stepsBeforeAccount ?? 0);
+ let primaryLabel: string;
+ if (step === 'welcome') {
+ primaryLabel = i18n._(GET_STARTED_DESCRIPTOR);
+ } else if (step === 'review') {
+ primaryLabel = i18n._(FINISH_DESCRIPTOR);
+ } else if (step === 'sign_in_to_finish') {
+ primaryLabel = i18n._(SIGN_IN_DESCRIPTOR);
+ } else if (returnToReview && step !== 'email_service') {
+ primaryLabel = i18n._(BACK_TO_REVIEW_DESCRIPTOR);
+ } else {
+ primaryLabel = i18n._(CONTINUE_DESCRIPTOR);
+ }
+ const showBack = back !== null && !isDone && !awaitingConfig;
+ const showFooter = !loadError && !isDone && !loadingSession;
+
+ const handleEnter = useEffectEvent((event: KeyboardEvent) => {
+ if (event.key !== 'Enter' || event.shiftKey || event.isComposing || event.defaultPrevented) return;
+ if (isAccountStep || isDone || !showFooter) return;
+ const target = event.target;
+ if (!(target instanceof HTMLElement) || !wizardRef.current?.contains(target)) return;
+ if (target.closest('textarea, a, [role="combobox"], [aria-expanded="true"]')) return;
+ if (target.tagName === 'BUTTON' && target.getAttribute('role') !== 'radio') return;
+ event.preventDefault();
+ void runPrimary();
+ });
+ useEffect(() => {
+ window.addEventListener('keydown', handleEnter);
+ return () => window.removeEventListener('keydown', handleEnter);
+ }, []);
+
+ const renderStep = (): React.ReactNode => {
+ switch (step) {
+ case 'welcome':
+ return <WelcomeStep data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.welcome-step" />;
+ case 'setup_token':
+ return (
+ <SetupTokenStep
+ formRef={setupTokenFormRef}
+ notice={setupTokenRejected ? stepError : null}
+ onSubmit={runStep}
+ onAdvance={advance}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.setup-token-step.set-setup-token"
+ />
+ );
+ case 'sign_in_method':
+ return (
+ <SignInMethodStep
+ draft={identityDraft}
+ formRef={signInMethodFormRef}
+ setupToken={setupToken}
+ onSubmit={runStep}
+ onAdvance={advance}
+ onError={setStepError}
+ onSetupTokenRejected={handleSetupTokenRejected}
+ disabled={busy}
+ error={stepError}
+ onClearError={() => setStepError(null)}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.sign-in-method-step.set-sign-in-method"
+ />
+ );
+ case 'sign_in_locked':
+ return (
+ <SignInLockedStep
+ mode={RuntimeConfig.accountIdentity}
+ reason={RuntimeConfig.appPublic.setup.account_identity_lock_reason}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.sign-in-locked-step"
+ />
+ );
+ case 'sign_in_to_finish':
+ return (
+ <SignInToFinishStep data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.sign-in-to-finish-step" />
+ );
+ case 'shared_usernames':
+ return (
+ <SharedUsernamesStep
+ draft={identityDraft}
+ formRef={sharedUsernamesFormRef}
+ setupToken={setupToken}
+ onSubmit={runStep}
+ onAdvance={advance}
+ onError={setStepError}
+ onSetupTokenRejected={handleSetupTokenRejected}
+ disabled={busy}
+ error={stepError}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.shared-usernames-step.set-tag-style"
+ />
+ );
+ case 'email_delivery':
+ return (
+ <EmailDeliveryStep
+ draft={identityDraft}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.email-delivery-step.set-email-answer"
+ />
+ );
+ case 'account':
+ return (
+ <AccountStep
+ usernameSignIn={accountIdentity === AccountIdentityModes.USERNAME}
+ emailLater={
+ accountIdentity === AccountIdentityModes.EMAIL && !RuntimeConfig.emailsEnabled && emailAnswer === 'later'
+ }
+ theme={ThemeTypes.DARK}
+ setupToken={setupToken.trim() || undefined}
+ formId={accountFormId}
+ renderSubmit={renderAccountSubmit}
+ onSetupTokenRejected={handleSetupTokenRejected}
+ onPasswordRegistered={(password) => {
+ accountDraft.passwordRef.current = password;
+ setStepsBeforeAccount(countedStepsBeforeAccount(conditionsRef.current));
+ }}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.account-step"
+ />
+ );
+ case 'recovery_kit':
+ return (
+ <RecoveryKitStep
+ draft={recoveryKitDraft}
+ currentUserId={currentUserId}
+ hasRecoveryKit={hasRecoveryKit}
+ adminPasswordRef={accountDraft.passwordRef}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.recovery-kit-step"
+ />
+ );
+ case 'email_service':
+ return (
+ <EmailServiceStep
+ formRef={emailServiceFormRef}
+ error={stepError}
+ disabled={busy}
+ onSubmit={runStep}
+ onAdvance={advance}
+ onError={setStepError}
+ onLater={switchEmailToLater}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.email-service-step.set-smtp-draft"
+ />
+ );
+ case 'email_sender':
+ return (
+ <EmailSenderStep
+ formRef={emailSenderFormRef}
+ showErrors={showErrors}
+ disabled={busy}
+ error={stepError}
+ onSubmit={runStep}
+ onSave={saveConfig}
+ onAdvance={advance}
+ onShowErrors={setShowErrors}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.email-sender-step.set-smtp-draft"
+ />
+ );
+ case 'name':
+ return (
+ <NameStep
+ config={config}
+ formRef={nameFormRef}
+ showErrors={showErrors}
+ disabled={busy}
+ error={stepError}
+ onSubmit={runStep}
+ onSave={saveConfig}
+ onAdvance={advance}
+ onShowErrors={setShowErrors}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.name-step.set-product-name"
+ />
+ );
+ case 'look':
+ return (
+ <BrandingStep
+ config={config}
+ formRef={brandingFormRef}
+ disabled={busy}
+ error={stepError}
+ onSubmit={runStep}
+ onSave={saveConfig}
+ onConfigUpdate={setConfig}
+ onAdvance={advance}
+ onError={setStepError}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.branding-step"
+ />
+ );
+ case 'communities':
+ return (
+ <CommunitiesStep
+ formRef={communitiesFormRef}
+ showErrors={showErrors}
+ onShowErrors={setShowErrors}
+ onSubmit={runStep}
+ onAdvance={advance}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.communities-step"
+ />
+ );
+ case 'direct_messages':
+ return (
+ <DirectMessagesStep data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.direct-messages-step.set-finish-draft" />
+ );
+ case 'registration':
+ return (
+ <RegistrationStep data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.registration-step.set-finish-draft" />
+ );
+ case 'push_relay':
+ return (
+ <PushRelayStep data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.push-relay-step.set-finish-draft" />
+ );
+ case 'gif_youtube':
+ return (
+ <ServicesStep
+ draftCache={serviceDraftCache}
+ formRef={servicesFormRef}
+ klipyStored={config?.integrations.gif.klipy_api_key_set ?? false}
+ youtubeStored={config?.integrations.youtube.api_key_set ?? false}
+ disabled={busy}
+ error={stepError}
+ onSubmit={runStep}
+ onSave={saveConfig}
+ onAdvance={advance}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.services-step.set-service-keys"
+ />
+ );
+ case 'attachments':
+ return (
+ <AttachmentsStep
+ formRef={attachmentsFormRef}
+ error={stepError}
+ onSubmit={runStep}
+ onSave={saveConfig}
+ onAdvance={advance}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.attachments-step.set-attachments-enabled"
+ />
+ );
+ case 'review':
+ return (
+ <ReviewStep
+ config={config}
+ finishDraft={finishDraft}
+ productName={productName}
+ themeColor={themeColor}
+ assets={assets}
+ attachmentsEnabled={attachmentsEnabled}
+ accountUsername={accountValues.username}
+ onChange={reviewChange}
+ onEmailChange={() => {
+ setEmailAnswer('now');
+ reviewChange('email_service');
+ }}
+ error={stepError}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.review-step"
+ />
+ );
+ case 'done':
+ return (
+ <DoneStep
+ name={productName.trim() || RuntimeConfig.productName}
+ registrationMode={finishDraft.registrationMode}
+ origin={window.location.origin}
+ adminUrl={RuntimeConfig.appPublic.setup.admin_url}
+ onOpen={openInstance}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.render-step.done-step"
+ />
+ );
+ }
+ };
+
+ const isMobile = isMobileExperienceEnabled();
+ const backdropUrl = resolveLayoutAuthBrand(RuntimeConfig.getSnapshotOrNull())?.backdropUrl ?? null;
+ const isWideStep = step === 'look';
+ const progressPercent = progress ? Math.round((progress.current / progress.total) * 100) : 0;
+ const stepCountText = progress
+ ? i18n._(STEP_COUNT_DESCRIPTOR, {current: progress.current, total: progress.total})
+ : '';
+
+ const progressBar = (
+ <div
+ className={styles.progressTrack}
+ role="progressbar"
+ aria-label={i18n._(PROGRESS_LABEL_DESCRIPTOR)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={isDone ? 100 : progressPercent}
+ aria-valuetext={stepCountText || undefined}
+ data-flx="app.self-hosted-setup-wizard-gate.progress"
+ >
+ <div
+ className={styles.progressFill}
+ style={{width: `${isDone ? 100 : progressPercent}%`}}
+ data-flx="app.self-hosted-setup-wizard-gate.progress-fill"
+ />
+ </div>
+ );
+
+ let stepContent: React.ReactNode;
+ if (loadError) {
+ stepContent = (
+ <div className={styles.centeredStep} data-flx="app.self-hosted-setup-wizard-gate.load-error-wrap">
+ <p className={styles.alert} role="alert" data-flx="app.self-hosted-setup-wizard-gate.load-error">
+ {i18n._(loadError)}
+ </p>
+ {loadError === NOT_ADMIN_DESCRIPTOR && (
+ <Button
+ variant="secondary"
+ onClick={signOutOfSetup}
+ data-flx="app.self-hosted-setup-wizard-gate.load-error-sign-out"
+ >
+ {i18n._(SIGN_OUT_DESCRIPTOR)}
+ </Button>
+ )}
+ </div>
+ );
+ } else if (loadingSession) {
+ stepContent = (
+ <div className={styles.centeredStep} role="status" data-flx="app.self-hosted-setup-wizard-gate.loading">
+ <Spinner size="large" data-flx="app.self-hosted-setup-wizard-gate.loading-spinner" />
+ <span className={styles.visuallyHidden} data-flx="app.setup.self-hosted-setup-wizard-gate.visually-hidden">
+ {i18n._(LOADING_DESCRIPTOR)}
+ </span>
+ </div>
+ );
+ } else {
+ stepContent = (
+ <SteppedCarousel
+ step={step}
+ steps={visibleSteps(conditions).includes(step) ? visibleSteps(conditions) : [step]}
+ direction={direction}
+ focusOnStepChange
+ ariaLabel={i18n._(SETUP_WIZARD_DESCRIPTOR)}
+ data-flx="app.self-hosted-setup-wizard-gate.carousel"
+ >
+ {renderStep()}
+ </SteppedCarousel>
+ );
+ }
+ const content = (
+ <div className={styles.content} data-flx="app.self-hosted-setup-wizard-gate.content-inner">
+ {stepContent}
+ </div>
+ );
+
+ let footer: React.ReactNode = null;
+ if (showFooter) {
+ footer = (
+ <div className={styles.footer} data-flx="app.self-hosted-setup-wizard-gate.footer">
+ <div className={styles.footerStart} data-flx="app.self-hosted-setup-wizard-gate.footer-start">
+ {showBack && (
+ <>
+ <span className={styles.backWide} data-flx="app.setup.self-hosted-setup-wizard-gate.back-wide">
+ <Button
+ variant="secondary"
+ disabled={busy}
+ leftIcon={
+ <ArrowLeftIcon
+ size={18}
+ weight="bold"
+ data-flx="app.setup.self-hosted-setup-wizard-gate.arrow-left-icon"
+ />
+ }
+ onClick={goBack}
+ data-flx="app.self-hosted-setup-wizard-gate.back-button"
>
- <div className={styles.content} data-flx="app.self-hosted-setup-wizard-gate.content-inner">
- {loadError ? (
- <div className={styles.centeredStep} data-flx="app.self-hosted-setup-wizard-gate.load-error-wrap">
- <p
- className={styles.submitError}
- role="alert"
- data-flx="app.self-hosted-setup-wizard-gate.load-error"
- >
- {i18n._(loadError)}
- </p>
- {loadError === NOT_ADMIN_DESCRIPTOR && (
- <Button
- variant="secondary"
- onClick={signOutOfSetup}
- data-flx="app.self-hosted-setup-wizard-gate.load-error-sign-out"
- >
- {i18n._(SIGN_OUT_DESCRIPTOR)}
- </Button>
- )}
- </div>
- ) : (
- <SteppedCarousel
- step={step}
- steps={steps}
- direction={direction}
- focusOnStepChange
- ariaLabel={i18n._(SETUP_WIZARD_DESCRIPTOR)}
- data-flx="app.self-hosted-setup-wizard-gate.carousel"
- >
- {step === 'welcome' && (
- <WelcomeStep
- productName={fallbackProductName}
- isAuthenticated={isAuthenticated}
- initialFocusRef={welcomeInitialFocusRef}
- data-flx="app.setup.self-hosted-setup-wizard-gate.welcome-step"
- />
- )}
- {step === 'setup_token' && (
- <SetupTokenStep
- value={setupToken}
- onChange={handleSetupTokenChange}
- error={setupTokenError}
- data-flx="app.setup.self-hosted-setup-wizard-gate.setup-token-step"
- />
- )}
- {step === 'theme' && (
- <ThemeStep
- theme={setupTheme}
- onThemeChange={setSetupTheme}
- data-flx="app.setup.self-hosted-setup-wizard-gate.theme-step"
- />
- )}
- {step === 'sign_in_method' && (
- <SignInMethodStep
- mode={signInMethod}
- tagStyle={tagStyleChoice}
- onTagStyleChange={(value) => {
- setTagStyleChoice(value);
- setSignInMethodError(null);
- }}
- disabled={savingSignInMethod}
- error={signInMethodError}
- onChange={handleSignInMethodChange}
- data-flx="app.setup.self-hosted-setup-wizard-gate.sign-in-method-step"
- />
- )}
- {step === 'admin_intro' && (
- <AdminIntroStep data-flx="app.setup.self-hosted-setup-wizard-gate.admin-intro-step" />
- )}
- {step === 'admin_account' && (
- <AdminAccountStep
- theme={setupTheme}
- usernameSignIn={accountIdentity === AccountIdentityModes.USERNAME}
- setupToken={submittedSetupToken}
- onSetupTokenRejected={handleSetupTokenRejected}
- data-flx="app.setup.self-hosted-setup-wizard-gate.admin-account-step"
- />
- )}
- {step === 'admin_recovery_kit' && (
- <AdminRecoveryKitStep
- hasRecoveryKit={hasRecoveryKit}
- creating={creatingRecoveryKit}
- onCreate={handleCreateRecoveryKit}
- data-flx="app.setup.self-hosted-setup-wizard-gate.admin-recovery-kit-step"
- />
- )}
- {step === 'loading' && (
- <LoadingStep data-flx="app.setup.self-hosted-setup-wizard-gate.loading-step" />
- )}
- {step === 'branding' && (
- <BrandingStep
- productName={productName}
- productNameError={productNameError}
- themeColor={themeColor}
- assets={assets}
- disabled={submitting}
- onProductNameChange={setProductName}
- onThemeColorChange={setThemeColor}
- onUploadAsset={handleUploadAsset}
- onClearAsset={handleClearAsset}
- data-flx="app.setup.self-hosted-setup-wizard-gate.branding-step"
- />
- )}
- {step === 'registration' && (
- <RegistrationStep
- mode={registrationMode}
- disabled={submitting}
- onChange={setRegistrationMode}
- data-flx="app.setup.self-hosted-setup-wizard-gate.registration-step.set-registration-mode"
- />
- )}
- {step === 'community' && (
- <CommunityStep
- singleCommunityEnabled={singleCommunityEnabled}
- singleCommunityName={singleCommunityName}
- singleCommunityNameError={singleCommunityNameError}
- directMessagesDisabled={directMessagesDisabled}
- disabled={submitting}
- onToggleSingleCommunity={setSingleCommunityEnabled}
- onSingleCommunityNameChange={setSingleCommunityName}
- onToggleDirectMessages={setDirectMessagesDisabled}
- data-flx="app.setup.self-hosted-setup-wizard-gate.community-step"
- />
- )}
- {step === 'media_expiry' && (
- <MediaExpiryStep
- draft={mediaExpiryDraft}
- disabled={submitting}
- onDraftChange={handleMediaExpiryDraftChange}
- data-flx="app.setup.self-hosted-setup-wizard-gate.media-expiry-step"
- />
- )}
- {wizardStepToIntegrationKind(step) && (
- <IntegrationStep
- kind={wizardStepToIntegrationKind(step)!}
- draft={integrationDraft}
- disabled={submitting}
- smtpTesting={smtpTesting}
- smtpTestResult={smtpTestResult}
- onDraftChange={handleIntegrationDraftChange}
- onTestSmtp={handleTestSmtp}
- data-flx="app.setup.self-hosted-setup-wizard-gate.integration-step"
- />
- )}
- {step === 'push_relay_consent' && (
- <PushRelayConsentStep
- accepted={pushRelayConsentAccepted}
- disabled={submitting}
- onChange={setPushRelayConsentAccepted}
- data-flx="app.setup.self-hosted-setup-wizard-gate.push-relay-consent-step"
- />
- )}
- {step === 'services' && (
- <ServicesStep
- available={serviceAvailability}
- selection={serviceSelection}
- disabled={submitting}
- onToggle={handleToggleService}
- data-flx="app.setup.self-hosted-setup-wizard-gate.services-step"
- />
- )}
- {step === 'premium' && (
- <PremiumStep
- mode={premiumMode}
- disabled={submitting}
- onChange={setPremiumMode}
- data-flx="app.setup.self-hosted-setup-wizard-gate.premium-step.set-premium-mode"
- />
- )}
- {step === 'finish' && (
- <FinishStep
- productName={productNameTrimmed}
- accountIdentity={accountIdentity}
- tagStyle={config?.account_identity.tag_style ?? RuntimeConfig.tagStyle}
- registrationMode={registrationMode}
- singleCommunityEnabled={singleCommunityEnabled}
- directMessagesDisabled={directMessagesDisabled}
- attachmentExpiryEnabled={mediaExpiryDraft.enabled}
- pushRelayConsentAccepted={pushRelayConsentAccepted}
- premiumMode={premiumMode}
- submitError={submitError}
- data-flx="app.setup.self-hosted-setup-wizard-gate.finish-step"
- />
- )}
- </SteppedCarousel>
- )}
- </div>
- </Modal.Content>
- <AnimatePresence initial={false} data-flx="app.self-hosted-setup-wizard-gate.footer-presence">
- {showFooter && (
- <motion.div
- key="footer"
- className={styles.footerReveal}
- initial={{height: 0, opacity: 0}}
- animate={{height: 'auto', opacity: 1}}
- exit={{height: 0, opacity: 0}}
- transition={shouldReduceMotion ? instantTransition : footerRevealTransition}
- data-flx="app.self-hosted-setup-wizard-gate.footer-reveal"
- >
- <Modal.Footer className={styles.footer} data-flx="app.self-hosted-setup-wizard-gate.footer">
- <div
- className={styles.footerActions}
- data-flx="app.self-hosted-setup-wizard-gate.footer-actions"
- >
- <AnimatePresence initial={false} data-flx="app.self-hosted-setup-wizard-gate.back-presence">
- {showBackButton && (
- <motion.div
- key="back"
- initial={footerButtonInitial}
- animate={footerButtonAnimate}
- exit={footerButtonExit}
- transition={shouldReduceMotion ? instantTransition : footerButtonTransition}
- data-flx="app.self-hosted-setup-wizard-gate.back-button-wrap"
- >
- <Button
- variant="secondary"
- disabled={stepNavigationLocked}
- leftIcon={
- <ArrowLeftIcon
- size={18}
- weight="bold"
- data-flx="app.setup.self-hosted-setup-wizard-gate.arrow-left-icon"
- />
- }
- onClick={goBack}
- data-flx="app.self-hosted-setup-wizard-gate.back-button"
- >
- {i18n._(BACK_DESCRIPTOR)}
- </Button>
- </motion.div>
- )}
- </AnimatePresence>
- <div
- className={styles.footerPrimary}
- data-flx="app.self-hosted-setup-wizard-gate.footer-primary"
- >
- <AnimatePresence
- mode="wait"
- initial={false}
- data-flx="app.self-hosted-setup-wizard-gate.primary-presence"
- >
- {showPrimaryButton && isFinish && (
- <motion.div
- key="finish"
- initial={footerButtonInitial}
- animate={footerButtonAnimate}
- exit={footerButtonExit}
- transition={shouldReduceMotion ? instantTransition : footerButtonTransition}
- data-flx="app.self-hosted-setup-wizard-gate.finish-button-wrap"
- >
- <Button
- submitting={submitting}
- rightIcon={
- <CheckIcon
- size={18}
- weight="bold"
- data-flx="app.setup.self-hosted-setup-wizard-gate.check-icon"
- />
- }
- onClick={submit}
- data-flx="app.self-hosted-setup-wizard-gate.finish-button"
- >
- {i18n._(FINISH_DESCRIPTOR)}
- </Button>
- </motion.div>
- )}
- {showPrimaryButton && !isFinish && (
- <motion.div
- key="next"
- initial={footerButtonInitial}
- animate={footerButtonAnimate}
- exit={footerButtonExit}
- transition={shouldReduceMotion ? instantTransition : footerButtonTransition}
- data-flx="app.self-hosted-setup-wizard-gate.next-button-wrap"
- >
- <Button
- disabled={primaryButtonDisabled}
- submitting={primaryButtonSubmitting}
- rightIcon={
- <ArrowRightIcon
- size={18}
- weight="bold"
- data-flx="app.setup.self-hosted-setup-wizard-gate.arrow-right-icon"
- />
- }
- onClick={handlePrimaryButton}
- data-flx="app.self-hosted-setup-wizard-gate.next-button"
- >
- {primaryButtonLabel}
- </Button>
- </motion.div>
- )}
- </AnimatePresence>
- </div>
- </div>
- </Modal.Footer>
- </motion.div>
- )}
- </AnimatePresence>
- </Modal.Root>
- </ModalStackContext.Provider>
- </PortalHostContext.Provider>
+ {i18n._(BACK_DESCRIPTOR)}
+ </Button>
+ </span>
+ <span className={styles.backNarrow} data-flx="app.setup.self-hosted-setup-wizard-gate.back-narrow">
+ <TextButton
+ onClick={goBack}
+ disabled={busy}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.text-button.go-back"
+ >
+ {i18n._(BACK_DESCRIPTOR)}
+ </TextButton>
+ </span>
+ </>
+ )}
+ <span className={styles.stepCount} aria-live="polite" data-flx="app.self-hosted-setup-wizard-gate.step-count">
+ {stepCountText}
+ </span>
+ </div>
+ <div className={styles.footerPrimary} data-flx="app.self-hosted-setup-wizard-gate.footer-primary">
+ {isAccountStep ? (
+ <span
+ ref={setSubmitSlot}
+ className={styles.submitSlot}
+ data-flx="app.setup.self-hosted-setup-wizard-gate.submit-slot"
+ />
+ ) : (
+ <Button
+ disabled={primaryDisabled}
+ submitting={busy}
+ onClick={() => void runPrimary()}
+ className={styles.primaryButton}
+ data-flx="app.self-hosted-setup-wizard-gate.next-button"
+ >
+ {primaryLabel}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ }
+
+ let wizardBody: React.ReactNode;
+ if (isMobile) {
+ wizardBody = (
+ <div ref={wizardRef} className={styles.mobileWizard} data-flx="app.self-hosted-setup-wizard-gate.mobile-wizard">
+ {progressBar}
+ <div className={styles.mobileBody} data-flx="app.self-hosted-setup-wizard-gate.mobile-body">
+ {content}
+ </div>
+ {footer && (
+ <div className={styles.mobileFooter} data-flx="app.self-hosted-setup-wizard-gate.mobile-footer">
+ {footer}
+ </div>
)}
</div>
+ );
+ } else {
+ wizardBody = (
+ <AuthCardContainer
+ cardClassName={clsx(styles.card, isWideStep && styles.cardWide)}
+ contentClassName={styles.cardBody}
+ data-flx="app.self-hosted-setup-wizard-gate.card"
+ >
+ <div ref={wizardRef} className={styles.cardInner} data-flx="app.setup.self-hosted-setup-wizard-gate.card-inner">
+ {progressBar}
+ <Scroller
+ className={clsx(styles.contentScroller, isWideStep && styles.wideScroller)}
+ contentClassName={isWideStep ? styles.wideFrame : styles.contentFrame}
+ key="setup-wizard-content-scroller"
+ data-flx="app.self-hosted-setup-wizard-gate.content"
+ >
+ {content}
+ </Scroller>
+ {footer}
+ </div>
+ </AuthCardContainer>
+ );
+ }
+ return (
+ <AuthRegisterDraftContext.Provider value={accountDraft}>
+ <AuthShell mobile={isMobile} backdropUrl={backdropUrl} data-flx="app.self-hosted-setup-wizard-gate.auth-shell">
+ {wizardBody}
+ </AuthShell>
</AuthRegisterDraftContext.Provider>
);
});
+
+export const SelfHostedSetupWizardGate = () => (
+ <SetupBrandingDraftProvider data-flx="app.setup.self-hosted-setup-wizard-gate.setup-branding-draft-provider">
+ <SetupPolicyDraftProvider data-flx="app.setup.self-hosted-setup-wizard-gate.setup-policy-draft-provider">
+ <SetupEmailDraftProvider data-flx="app.setup.self-hosted-setup-wizard-gate.setup-email-draft-provider">
+ <SetupAttachmentsDraftProvider data-flx="app.setup.self-hosted-setup-wizard-gate.setup-attachments-draft-provider">
+ <SetupTokenDraftProvider data-flx="app.setup.self-hosted-setup-wizard-gate.setup-token-draft-provider">
+ <SetupWizardController data-flx="app.setup.self-hosted-setup-wizard-gate.setup-wizard-controller" />
+ </SetupTokenDraftProvider>
+ </SetupAttachmentsDraftProvider>
+ </SetupEmailDraftProvider>
+ </SetupPolicyDraftProvider>
+ </SetupBrandingDraftProvider>
+);