index.tsx
Overview
index.tsx implements a User Profile Settings page as a React functional component using TypeScript. The page allows users to:
View and edit their profile details: username, avatar, time zone, and email.
Optionally update their password via a dedicated password change section.
Upload and preview a new avatar image with client-side image conversion to base64.
Validate user input dynamically with schema-based form validation.
Submit updated profile information to the backend via async save operations.
The component leverages modern React hooks, form management (react-hook-form), schema validation (zod), and UI component abstractions to provide a user-friendly and responsive profile editing experience.
Detailed Explanation
Imports and Dependencies
UI Components: Avatar, Button, Form controls, Input, Select, PasswordInput from project's UI libraries.
Hooks:
useTranslate(i18n),useFetchUserInfo(load user data),useSaveSetting(submit changes).Utilities:
rsaPswfor password encryption,transformFile2Base64for image processing.Validation:
zodandzodResolverintegrated withreact-hook-form.Icons: Loader animation, Pencil icon, Upload icon from
lucide-react.React:
useState,useEffect, useForm from react-hook-form.
defineSchema Function
function defineSchema(
t: TFunction<'translation', string>,
showPasswordForm = false,
)
Purpose: Defines the validation schema for the profile form fields using
zod.Parameters:
t: Translation function for localized validation messages.showPasswordForm: Boolean to include or exclude password fields in the schema.
Returns: A
zodschema object for form validation.
Validation Rules:
userName: required, non-empty trimmed string.avatarUrl: string (no explicit validation beyond trimming).timeZone: required, non-empty string.email: required, valid email format using regex.Password fields (conditionally):
currPasswd,newPasswd,confirmPasswd: required, min length 8.newPasswdmust matchconfirmPasswd.
Usage Example
const schemaWithoutPassword = defineSchema(t, false);
const schemaWithPassword = defineSchema(t, true);
Profile Component
export default function Profile()
Purpose
Main React functional component rendering the user profile settings UI and managing form state and submission.
State Variables
avatarFile: File | null: Stores the uploaded avatar file.avatarBase64Str: string: Stores the base64 string of the avatar image for preview.showPasswordForm: boolean: Toggles visibility of password change form.userInfo: Fetched user data fromuseFetchUserInfo.submitLoading: Loading state during save operation.saveUserData: Response data from save operation.
Form Initialization
Uses
react-hook-formwithzodResolverfor schema validation.Default values initialized empty, set to user info on load.
Effects
Initialize form with fetched user info: Sets username, email, timezone, avatar.
Reset password fields on successful save: Hides password form and resets fields.
Convert uploaded avatar file to base64 string for preview.
Register/unregister password fields dynamically based on
showPasswordForm.
Methods
onSubmit(data)
Handles form submission:
Constructs a partial payload with:
nicknamefromuserNameavataras base64 stringtimezone
If password form visible:
Encrypts current and new password with
rsaPsw.
Calls
saveSetting(payload)to persist changes.
JSX Structure and UI Elements
Section: Contains entire profile form with padding.
Header: Title and description localized with
t.Form: Wraps all input fields and controls via
react-hook-form.
Form Fields
Username
Required input field.
Validation error messages shown below.
Avatar
Displays current or placeholder upload icon.
File input accepts image files only.
On file select, updates avatar preview with compressed base64.
Tooltip text explaining avatar requirements.
Time Zone
Required dropdown select with values from
TimezoneList.Validation messages displayed.
Email
Display-only field (no editing).
Descriptive text below.
Password Section
Title with toggle button to show/hide password change form.
Description text.
When shown, includes three password inputs:
Current password
New password
Confirm password (with validation check on blur and change)
Buttons
Cancel (reset form)
Save (submit form, disabled during saving)
Save button shows spinner icon when loading.
Important Implementation Details and Algorithms
Schema-driven validation: Using
zodensures strong, declarative validation rules with localization support.Dynamic form fields: Password fields dynamically registered/unregistered depending on user choice, optimizing validation and form state.
Image upload with base64 conversion:
transformFile2Base64asynchronously compresses and converts avatar image for immediate preview and upload.Password encryption: Passwords are encrypted client-side before sending to backend using RSA via
rsaPsw.Form reset on successful save: Password fields cleared and hidden after successful update to prevent stale data.
Controlled form components: All inputs integrated with
react-hook-formfor consistent state management.
Interaction with Other Parts of the System
Hooks
useFetchUserInfo: Fetches user's current profile info from backend or global state.useSaveSetting: Handles save API call for profile updates.useTranslate: Provides i18n translation strings for UI text and validation messages.
Utilities
rsaPsw: Encrypts passwords for secure transmission.transformFile2Base64: Processes uploaded avatar images to base64 strings.
Constants
TimezoneList: Array of timezone strings used in the select dropdown.
UI Components
Reusable components like
Form,Input,Select,Button, andAvatarprovide consistent UI/UX and styling.
This component acts as a client-side user interface that interacts with backend services through hooks to fetch and save user data securely.
Usage Example
This file exports a default React component and is typically used as a page or route component in the application:
import Profile from './index';
function App() {
return (
<div>
<Profile />
</div>
);
}
Visual Diagram
componentDiagram
component Profile {
+avatarFile: File | null
+avatarBase64Str: string
+showPasswordForm: boolean
+form: react-hook-form instance
+onSubmit(data)
}
component defineSchema {
+t: TFunction
+showPasswordForm: boolean
+returns: zod schema
}
Profile --> defineSchema : uses to define form validation
Profile --> useFetchUserInfo : fetch user data
Profile --> useSaveSetting : save profile data
Profile --> transformFile2Base64 : convert avatar file to base64
Profile --> rsaPsw : encrypt passwords
Profile --> UIComponents : Form, Input, Select, Button, Avatar...
Summary
This file provides a comprehensive user profile settings component featuring:
Form input for username, avatar upload, timezone selection, and email display.
Optional password update with validation and encryption.
Image processing for avatar upload.
Integration with backend via custom hooks.
Well-structured validation and error handling.
Modern React hooks and reusable UI components for consistency and maintainability.
It is a key part of user account management workflows in the application.