Component: App.jsx
Relevant source files
The following files were used as context for generating this wiki page:
The App.jsx component is the main application component for the QR Generator Pro tool. It serves as the central orchestrator, managing the application's entire state, user interface, and business logic. It integrates various child components, custom hooks, and utility functions to provide a comprehensive QR code generation experience, from data input and validation to real-time preview and final export.
The component is responsible for handling user inputs for different QR code types, managing advanced customization options like colors, logos, and error correction levels, and persisting user preferences to localStorage. It dynamically generates the QR code content, validates user data, and passes the necessary properties to the QrPreview and ExportPanel components for rendering and downloading.
Architecture and Component Structure
App.jsx is a large, functional React component that utilizes hooks for state management and side effects. It composes the entire application UI by rendering a header, a main content area with two columns (controls and preview), and a toast container for notifications.
The diagram below illustrates the high-level component hierarchy rooted at App.jsx.
This diagram shows that App.jsx is the parent component that uses QrPreview and ExportPanel for its UI. It also relies on custom hooks and utility modules for its logic.
Sources: src/App.jsx:3, 4, 5, 6, README.md:92-103
State Management
State is managed within App.jsx using a combination of React.useState and a custom useLocalStorage hook. This allows the application to maintain a reactive UI while persisting user settings across sessions.
Persisted State
The useLocalStorage hook is used to store UI preferences and QR code settings. This hook reads from localStorage on initial render and saves any changes back to it.
| State Variable | Hook Usage | Initial Value | Description |
|---|---|---|---|
qrType | useLocalStorage('qr_type', ...) | 'url' | The selected type of QR code (e.g., URL, Text, Wi-Fi). |
uiMode | useLocalStorage('ui_mode', ...) | 'quick' | The user interface mode ('quick' or 'pro'). |
size | useLocalStorage('qr_size', ...) | 360 | The pixel size of the QR code. |
selectedPreset | useLocalStorage('qr_size_preset', ...) | 'web' | The ID of the selected size preset. |
eccMode | useLocalStorage('qr_ecc_mode', ...) | 'AUTO' | The Error Correction Code (ECC) level mode. |
includeMargin | useLocalStorage('qr_margin', ...) | true | Whether to include the quiet zone (white border). |
transparentBg | useLocalStorage('qr_transparent_bg', ...) | false | Whether to use a transparent background for PNGs. |
fgColor | useLocalStorage('qr_fg', ...) | '#000000' | The foreground (QR code) color. |
bgColor | useLocalStorage('qr_bg', ...) | '#FFFFFF' | The background color. |
format | useLocalStorage('qr_fmt', ...) | 'canvas' | The export format ('canvas' for PNG/JPG, 'svg' for SVG). |
logoMode | useLocalStorage('qr_logo_mode', ...) | 'auto' | The mode for scaling the logo. |
customLogoScale | useLocalStorage('qr_logo_custom', ...) | 0.2 | The custom scale factor for the logo. |
Sources: src/App.jsx:245-259, src/App.jsx:274-288
Local Component State
Standard React.useState is used for transient state that doesn't need to be persisted.
qrData: An object holding the user-provided data for the selectedqrType.validationErrors: An object storing validation error messages for user inputs.logoUrl: A blob URL for the user-uploaded logo image.scanResult: The result from the automatic QR code scan validation.
Sources: src/App.jsx:260-272, src/App.jsx:291, src/App.jsx:292
Data Flow and QR Generation
The process of generating a QR code is a reactive flow triggered by user input.
This flowchart shows the data flow from user interaction to the final rendered QR code.
- User Input: The user interacts with form elements (inputs, selects, checkboxes).
- State Update:
onChangehandlers call state setters (e.g.,updateQrData,setSize) to update the component's state. - Input Validation: A
useEffecthook depends onqrTypeandqrData. It runs validation functions (e.g.,isValidURL,isValidEmail) and updates thevalidationErrorsstate. - Content Generation: A
useMemohook callsgenerateQRContent(qrType, qrData)to create the raw string to be encoded. This function formats the data according to the QR code type specification. - Debouncing: The generated
qrContentis passed to theuseDebouncedhook to prevent rapid re-renders of the QR code while the user is typing. - Props Aggregation: Another
useMemohook assembles theqrPropsobject. This object contains all properties for theqrcode.reactcomponent, including the debounced text, size, colors, ECC level, and logo settings. - Rendering: The
qrPropsobject is passed to theQrPreviewcomponent, which renders either<QRCodeCanvas>or<QRCodeSVG>based on the selected format. - Automatic Scanning: A
useEffecthook observes changes toqrPropsand, after a short delay, callstestQRScanfromqr-scanner.json the rendered canvas to verify its scannability. The result is stored inscanResultand displayed to the user.
Sources: src/App.jsx:295-300, src/App.jsx:437-455, src/App.jsx:457-474
Key Features and Logic
QR Code Content Generation
The generateQRContent function is the core of the data formatting logic. It takes the qrType and qrData object and returns a formatted string.
| QR Type | Format | Example Output |
|---|---|---|
URL | Plain URL string | https://example.com |
TEXT | Plain text string | Hello World |
WIFI | WIFI:T:<enc>;S:<ssid>;P:<pass>;H:<hidden>;; | WIFI:T:WPA;S:MyWiFi;P:password123;; |
VCARD | vCard 3.0 format | BEGIN:VCARD\r\nVERSION:3.0\r\n... |
EMAIL | mailto: URI scheme | mailto:a@b.com?subject=Hi&body=Test |
SMS | sms: URI scheme | sms:+12345?body=Hello |
TEL | tel: URI scheme | tel:+12345 |
GEO | geo: URI scheme | geo:0,0?q=21.02,105.85(Hanoi) |
Special characters in Wi-Fi and vCard data are escaped using helper functions (escWiFi, escVCARD) to ensure the format is valid.
Sources: src/App.jsx:51-137, src/App.test.js:20-83
Input Validation
The application performs client-side validation for several input types to guide the user and prevent the generation of invalid QR codes.
- URL: Checks for a valid URL structure using
new URL()and warns if the protocol is nothttp:orhttps:. - Email: Uses a regex to validate the email format.
- Phone: Uses a regex to ensure the input contains only valid characters for a phone number.
- Geo-coordinates: Ensures latitude is between -90 and 90, and longitude is between -180 and 180.
- Hex Color: Validates that color inputs are valid 3 or 6-digit hex codes.
These validation checks are consolidated in a useEffect hook that updates the validationErrors state, which in turn displays error messages in the UI.
Sources: src/App.jsx:295-321, src/utils/qr-helpers.js:27-81, SECURITY_AUDIT_REPORT.md:68-91
Logo Upload and Handling
The component supports adding a logo to the center of the QR code.
The sequence diagram below shows the logo upload process.
The onPickLogo function handles file selection. It performs security checks by validating the file's size (max 4MB) and MIME type. If the file is valid, it creates a blob URL using URL.createObjectURL() and stores it in the logoUrl state. The component also includes cleanup logic to revoke the blob URL when the component unmounts or a new logo is chosen, preventing memory leaks.
Sources: src/App.jsx:476-507
Automatic ECC Level Selection
The Error Correction Capability (ECC) level determines how much of the QR code can be damaged or obscured while remaining scannable. The application can automatically select the best ECC level.
This logic is encapsulated in the pickECC helper function.
This diagram shows the decision logic for automatic ECC level selection.
- If a manual ECC level (
L,M,Q,H) is chosen, it is always used. - If set to
AUTO:- It defaults to
M(Medium). - If a logo is added (
logoRatio >= 0.1), it upgrades toQ(Quartile). - If the logo is large (
logoRatio >= 0.22) or the color contrast is poor, it upgrades toH(High) for maximum resilience.
- It defaults to
Sources: src/App.jsx:420-423, src/utils/qr-helpers.js:215-223
Export Functionality
App.jsx passes all necessary data and references (canvasRef, svgRef) to the ExportPanel component. The ExportPanel handles the logic for downloading the QR code as a PNG, JPG, or SVG file. It uses helper functions from qr-helpers.js (buildDataURL, buildSVGBlob) to prepare the file, including adding padding if the "Quiet Zone" was disabled, and then triggers a download.
Sources: src/App.jsx:1062-1072, src/components/ExportPanel.jsx
Conclusion
App.jsx is the heart of the QR-Tool application. It demonstrates a well-structured, single-component architecture for a client-side tool, effectively using React hooks for state management, reactivity, and side effects. By centralizing the application's logic, state, and UI composition, it provides a robust and maintainable foundation for all features, from basic QR code generation to advanced customizations and security-conscious file handling. The component's design ensures a smooth and interactive user experience by providing real-time feedback, validation, and previews.