diff --git a/public/locales/en/image.json b/public/locales/en/image.json index e99cb111..f300425c 100644 --- a/public/locales/en/image.json +++ b/public/locales/en/image.json @@ -96,7 +96,131 @@ }, "resultOutput": "Generated QR code", "shortDescription": "Create customized QR codes for various data formats.", - "title": "QR Code Generator" + "longDescription": "Generate QR codes for different data types: URL, Text, Email, Phone, SMS, WiFi, vCard, and more. Customize the size and colors to create the perfect QR code for your needs.", + "title": "QR Code Generator", + "result": { + "title": "Generated QR code" + }, + "groups": { + "type": { + "title": "QR Code Type", + "label": "Select QR Code Type", + "options": { + "url": "URL", + "text": "Text", + "email": "Email", + "phone": "Phone", + "sms": "SMS", + "wifi": "WiFi", + "vcard": "vCard (Contact)" + } + }, + "settings": { + "title": "QR Code Settings", + "size": { + "description": "Size in pixels (100-1000)" + }, + "correctionLevel": { + "label": "Error Correction Level", + "helperText": "Higher levels survive more damage but encode less data", + "options": { + "l": "L (~7%)", + "m": "M (~15%)", + "q": "Q (~25%)", + "h": "H (~30%)" + } + }, + "bgColor": "Background Color", + "fgColor": "Foreground Color" + }, + "details": { + "title": "{{type}} Details", + "url": { + "description": "Enter the URL", + "placeholder": "https://example.com" + }, + "text": { + "description": "Enter the text", + "placeholder": "Enter your text here" + }, + "email": { + "address": { + "description": "Email Address", + "placeholder": "example@example.com" + }, + "subject": { + "description": "Email Subject (optional)", + "placeholder": "Subject line" + }, + "body": { + "description": "Email Body (optional)", + "placeholder": "Body text" + } + }, + "phone": { + "description": "Phone Number", + "placeholder": "+1234567890" + }, + "sms": { + "number": { + "description": "Phone Number", + "placeholder": "+1234567890" + }, + "message": { + "description": "Message (optional)", + "placeholder": "Your message here" + } + }, + "wifi": { + "ssid": { + "description": "Network Name (SSID)", + "placeholder": "Network name" + }, + "password": { + "description": "Password", + "placeholder": "Password" + }, + "encryption": { + "label": "Encryption Type", + "options": { + "wpa": "WPA", + "wep": "WEP", + "none": "None" + } + } + }, + "vcard": { + "name": { + "description": "Full Name", + "placeholder": "John Doe" + }, + "email": { + "description": "Email", + "placeholder": "john@example.com" + }, + "phone": { + "description": "Phone", + "placeholder": "+1234567890" + }, + "address": { + "description": "Address", + "placeholder": "123 Main St, City, Country" + }, + "company": { + "description": "Company (optional)", + "placeholder": "Company name" + }, + "title": { + "description": "Job Title (optional)", + "placeholder": "Software Developer" + }, + "website": { + "description": "Website (optional)", + "placeholder": "https://example.com" + } + } + } + } }, "removeBackground": { "description": "Remove the background from an image to isolate the main subject with transparency.", diff --git a/src/pages/tools/image/generic/qr-code/index.tsx b/src/pages/tools/image/generic/qr-code/index.tsx index 5d6a0213..4cc5804f 100644 --- a/src/pages/tools/image/generic/qr-code/index.tsx +++ b/src/pages/tools/image/generic/qr-code/index.tsx @@ -1,17 +1,15 @@ import React, { useCallback, useState } from 'react'; -import { Box } from '@mui/material'; -import * as Yup from 'yup'; +import { Box, MenuItem, TextField } from '@mui/material'; +import { useTranslation } from 'react-i18next'; import ToolContent from '@components/ToolContent'; import { ToolComponentProps } from '@tools/defineTool'; import { GetGroupsType } from '@components/options/ToolOptions'; import TextFieldWithDesc from '@components/options/TextFieldWithDesc'; -import SelectWithDesc from '@components/options/SelectWithDesc'; import { InitialValuesType, QRCodeType, WifiEncryptionType } from './types'; import ColorSelector from '@components/options/ColorSelector'; import ToolFileResult from '@components/result/ToolFileResult'; -import { useTranslation } from 'react-i18next'; -import * as QRCode from 'qrcode'; import { debounce } from 'lodash'; +import { generateQrCodeFile } from './service'; const initialValues: InitialValuesType = { qrCodeType: 'URL', @@ -20,6 +18,7 @@ const initialValues: InitialValuesType = { size: '200', bgColor: '#FFFFFF', fgColor: '#000000', + correctionLevel: 'M', // URL url: 'https://example.com', @@ -53,172 +52,104 @@ const initialValues: InitialValuesType = { vCardTitle: '', vCardWebsite: '' }; - -// Function to format the QR code data based on the type -const formatQRCodeData = (values: InitialValuesType): string => { - switch (values.qrCodeType) { - case 'URL': - return values.url; - - case 'Text': - return values.text; - - case 'Email': { - let emailData = `mailto:${values.emailAddress}`; - if (values.emailSubject || values.emailBody) { - emailData += '?'; - if (values.emailSubject) { - emailData += `subject=${encodeURIComponent(values.emailSubject)}`; - } - if (values.emailBody) { - emailData += `${ - values.emailSubject ? '&' : '' - }body=${encodeURIComponent(values.emailBody)}`; - } - } - return emailData; - } - case 'Phone': - return `tel:${values.phoneNumber}`; - - case 'SMS': - return `sms:${values.smsNumber}${ - values.smsMessage - ? `?body=${encodeURIComponent(values.smsMessage)}` - : '' - }`; - - case 'WiFi': { - const encryption = - values.wifiEncryption === 'None' ? 'nopass' : values.wifiEncryption; - return `WIFI:T:${encryption};S:${values.wifiSsid};P:${values.wifiPassword};;`; - } - case 'vCard': - return `BEGIN:VCARD -VERSION:3.0 -N:${values.vCardName} -FN:${values.vCardName} -ORG:${values.vCardCompany} -TITLE:${values.vCardTitle} -TEL:${values.vCardPhone} -EMAIL:${values.vCardEmail} -ADR:${values.vCardAddress} -URL:${values.vCardWebsite} -END:VCARD`; - - default: - return ''; - } -}; - -const validationSchema = Yup.object().shape({ - qrCodeType: Yup.string().required('QR code type is required'), - size: Yup.number() - .min(100, 'Size must be at least 100px') - .max(1000, 'Size must be at most 1000px') - .required('Size is required'), - bgColor: Yup.string().required('Background color is required'), - fgColor: Yup.string().required('Foreground color is required'), - - // URL - url: Yup.string().when('qrCodeType', { - is: 'URL', - then: (schema) => - schema.url('Please enter a valid URL').required('URL is required') - }), - - // Text - text: Yup.string().when('qrCodeType', { - is: 'Text', - then: (schema) => schema.required('Text is required') - }), - - // Email - emailAddress: Yup.string().when('qrCodeType', { - is: 'Email', - then: (schema) => - schema - .email('Please enter a valid email address') - .required('Email address is required') - }), - - // Phone - phoneNumber: Yup.string().when('qrCodeType', { - is: 'Phone', - then: (schema) => schema.required('Phone number is required') - }), - - // SMS - smsNumber: Yup.string().when('qrCodeType', { - is: 'SMS', - then: (schema) => schema.required('Phone number is required') - }), - - // WiFi - wifiSsid: Yup.string().when('qrCodeType', { - is: 'WiFi', - then: (schema) => schema.required('SSID is required') - }), - - // vCard - vCardName: Yup.string().when('qrCodeType', { - is: 'vCard', - then: (schema) => schema.required('Name is required') - }) -}); - export default function QRCodeGenerator({ title }: ToolComponentProps) { const { t } = useTranslation('image'); const [result, setResult] = useState(null); + const getGroups: GetGroupsType = ({ values, updateField }) => { return [ { - title: 'QR Code Type', + title: t('qrCode.groups.type.title'), component: ( - - updateField('qrCodeType', value as QRCodeType) + + updateField('qrCodeType', e.target.value as QRCodeType) } - options={[ - { label: 'URL', value: 'URL' }, - { label: 'Text', value: 'Text' }, - { label: 'Email', value: 'Email' }, - { label: 'Phone', value: 'Phone' }, - { label: 'SMS', value: 'SMS' }, - { label: 'WiFi', value: 'WiFi' }, - { label: 'vCard', value: 'vCard' } - ]} - description={t('qrCode.options.qrType')} - /> + label={t('qrCode.groups.type.label')} + margin="normal" + > + + {t('qrCode.groups.type.options.url')} + + + {t('qrCode.groups.type.options.text')} + + + {t('qrCode.groups.type.options.email')} + + + {t('qrCode.groups.type.options.phone')} + + + {t('qrCode.groups.type.options.sms')} + + + {t('qrCode.groups.type.options.wifi')} + + + {t('qrCode.groups.type.options.vcard')} + + ) }, { - title: 'QR Code Settings', + title: t('qrCode.groups.settings.title'), component: ( updateField('size', val)} - description={t('qrCode.options.size')} + description={t('qrCode.groups.settings.size.description')} inputProps={{ type: 'number', min: 100, max: 1000 }} /> + + updateField( + 'correctionLevel', + e.target.value as 'L' | 'M' | 'Q' | 'H' + ) + } + helperText={t( + 'qrCode.groups.settings.correctionLevel.helperText' + )} + > + + {t('qrCode.groups.settings.correctionLevel.options.l')} + + + {t('qrCode.groups.settings.correctionLevel.options.m')} + + + {t('qrCode.groups.settings.correctionLevel.options.q')} + + + {t('qrCode.groups.settings.correctionLevel.options.h')} + + updateField('bgColor', val)} /> updateField('fgColor', val)} /> @@ -227,16 +158,16 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { }, // Dynamic form fields based on QR code type { - title: `${values.qrCodeType} Details`, + title: t('qrCode.groups.details.title', { type: values.qrCodeType }), component: ( {values.qrCodeType === 'URL' && ( updateField('url', val)} - description={t('qrCode.options.url')} + description={t('qrCode.groups.details.url.description')} inputProps={{ - placeholder: 'https://example.com' + placeholder: t('qrCode.groups.details.url.placeholder') }} /> )} @@ -245,11 +176,11 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('text', val)} - description={t('qrCode.options.text')} + description={t('qrCode.groups.details.text.description')} multiline rows={4} inputProps={{ - placeholder: 'Lorem Ipsum' + placeholder: t('qrCode.groups.details.text.placeholder') }} /> )} @@ -259,28 +190,40 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('emailAddress', val)} - description={t('qrCode.options.email')} + description={t( + 'qrCode.groups.details.email.address.description' + )} inputProps={{ - placeholder: 'example@example.com', + placeholder: t( + 'qrCode.groups.details.email.address.placeholder' + ), type: 'email' }} /> updateField('emailSubject', val)} - description={t('qrCode.options.emailSubject')} + description={t( + 'qrCode.groups.details.email.subject.description' + )} inputProps={{ - placeholder: 'Subject line' + placeholder: t( + 'qrCode.groups.details.email.subject.placeholder' + ) }} /> updateField('emailBody', val)} - description={t('qrCode.options.emailBody')} + description={t( + 'qrCode.groups.details.email.body.description' + )} multiline rows={4} inputProps={{ - placeholder: 'Body text' + placeholder: t( + 'qrCode.groups.details.email.body.placeholder' + ) }} /> @@ -290,9 +233,9 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('phoneNumber', val)} - description={t('qrCode.options.phone')} + description={t('qrCode.groups.details.phone.description')} inputProps={{ - placeholder: '+1234567890', + placeholder: t('qrCode.groups.details.phone.placeholder'), type: 'tel' }} /> @@ -303,20 +246,28 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('smsNumber', val)} - description={t('qrCode.options.phone')} + description={t( + 'qrCode.groups.details.sms.number.description' + )} inputProps={{ - placeholder: '+1234567890', + placeholder: t( + 'qrCode.groups.details.sms.number.placeholder' + ), type: 'tel' }} /> updateField('smsMessage', val)} - description={t('qrCode.options.message')} + description={t( + 'qrCode.groups.details.sms.message.description' + )} multiline rows={4} inputProps={{ - placeholder: 'Lorem Ipsum' + placeholder: t( + 'qrCode.groups.details.sms.message.placeholder' + ) }} /> @@ -327,32 +278,49 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('wifiSsid', val)} - description={t('qrCode.options.ssid')} + description={t('qrCode.groups.details.wifi.ssid.description')} inputProps={{ - placeholder: 'WIFI name' + placeholder: t( + 'qrCode.groups.details.wifi.ssid.placeholder' + ) }} /> updateField('wifiPassword', val)} - description={t('qrCode.options.password')} + description={t( + 'qrCode.groups.details.wifi.password.description' + )} inputProps={{ - placeholder: '******', + placeholder: t( + 'qrCode.groups.details.wifi.password.placeholder' + ), type: 'password' }} /> - - updateField('wifiEncryption', value as WifiEncryptionType) + + updateField( + 'wifiEncryption', + e.target.value as WifiEncryptionType + ) } - options={[ - { label: 'WPA', value: 'WPA' }, - { label: 'WEP', value: 'WEP' }, - { label: 'None', value: 'None' } - ]} - description={t('qrCode.options.encryptionType')} - /> + label={t('qrCode.groups.details.wifi.encryption.label')} + margin="normal" + > + + {t('qrCode.groups.details.wifi.encryption.options.wpa')} + + + {t('qrCode.groups.details.wifi.encryption.options.wep')} + + + {t('qrCode.groups.details.wifi.encryption.options.none')} + + )} @@ -361,59 +329,87 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { updateField('vCardName', val)} - description={t('qrCode.options.fullName')} + description={t( + 'qrCode.groups.details.vcard.name.description' + )} inputProps={{ - placeholder: 'John Doe' + placeholder: t( + 'qrCode.groups.details.vcard.name.placeholder' + ) }} /> updateField('vCardEmail', val)} - description={t('qrCode.options.email')} + description={t( + 'qrCode.groups.details.vcard.email.description' + )} inputProps={{ - placeholder: 'john@example.com', + placeholder: t( + 'qrCode.groups.details.vcard.email.placeholder' + ), type: 'email' }} /> updateField('vCardPhone', val)} - description={t('qrCode.options.phone')} + description={t( + 'qrCode.groups.details.vcard.phone.description' + )} inputProps={{ - placeholder: '+1234567890', + placeholder: t( + 'qrCode.groups.details.vcard.phone.placeholder' + ), type: 'tel' }} /> updateField('vCardAddress', val)} - description={t('qrCode.options.address')} + description={t( + 'qrCode.groups.details.vcard.address.description' + )} inputProps={{ - placeholder: '123 Main St, City, Country' + placeholder: t( + 'qrCode.groups.details.vcard.address.placeholder' + ) }} /> updateField('vCardCompany', val)} - description={t('qrCode.options.company')} + description={t( + 'qrCode.groups.details.vcard.company.description' + )} inputProps={{ - placeholder: 'Company name' + placeholder: t( + 'qrCode.groups.details.vcard.company.placeholder' + ) }} /> updateField('vCardTitle', val)} - description={t('qrCode.options.job')} + description={t( + 'qrCode.groups.details.vcard.title.description' + )} inputProps={{ - placeholder: 'Software Developer' + placeholder: t( + 'qrCode.groups.details.vcard.title.placeholder' + ) }} /> updateField('vCardWebsite', val)} - description={t('qrCode.options.website')} + description={t( + 'qrCode.groups.details.vcard.website.description' + )} inputProps={{ - placeholder: 'https://example.com' + placeholder: t( + 'qrCode.groups.details.vcard.website.placeholder' + ) }} /> @@ -425,27 +421,15 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { }; const compute = async (options: InitialValuesType) => { - const qrValue = formatQRCodeData(options); - if (!qrValue) return; - const canvas = document.createElement('canvas'); - QRCode.toDataURL( - canvas, - qrValue, - { - color: { - dark: options.fgColor, - light: options.bgColor - }, - width: Number(options.size) || 200 - }, - async (error, url) => { - const res = await fetch(url); - const blob = await res.blob(); - const file = new File([blob], 'Qr code.png', { type: 'image/png' }); - setResult(file); - } - ); + try { + const file = await generateQrCodeFile(options); + setResult(file); + } catch (err) { + console.error('Failed to generate QR code', err); + setResult(null); + } }; + const debouncedCompute = useCallback(debounce(compute, 1000), []); return ( @@ -453,14 +437,13 @@ export default function QRCodeGenerator({ title }: ToolComponentProps) { title={title} initialValues={initialValues} getGroups={getGroups} - validationSchema={validationSchema} compute={debouncedCompute} resultComponent={ - + } toolInfo={{ title: t('qrCode.title'), - description: t('qrCode.description') + description: t('qrCode.longDescription') }} /> ); diff --git a/src/pages/tools/image/generic/qr-code/service.ts b/src/pages/tools/image/generic/qr-code/service.ts new file mode 100644 index 00000000..69a33b93 --- /dev/null +++ b/src/pages/tools/image/generic/qr-code/service.ts @@ -0,0 +1,106 @@ +import * as QRCode from 'qrcode'; +import { InitialValuesType } from './types'; + +/** Formats the raw form values into the string that gets encoded in the QR code, based on the selected type. */ +export function formatQRCodeData(values: InitialValuesType): string { + switch (values.qrCodeType) { + case 'URL': + return values.url; + + case 'Text': + return values.text; + + case 'Email': { + let emailData = `mailto:${values.emailAddress}`; + if (values.emailSubject || values.emailBody) { + emailData += '?'; + if (values.emailSubject) { + emailData += `subject=${encodeURIComponent(values.emailSubject)}`; + } + if (values.emailBody) { + emailData += `${ + values.emailSubject ? '&' : '' + }body=${encodeURIComponent(values.emailBody)}`; + } + } + return emailData; + } + case 'Phone': + return `tel:${values.phoneNumber}`; + + case 'SMS': + return `sms:${values.smsNumber}${ + values.smsMessage + ? `?body=${encodeURIComponent(values.smsMessage)}` + : '' + }`; + + case 'WiFi': { + const encryption = + values.wifiEncryption === 'None' ? 'nopass' : values.wifiEncryption; + return `WIFI:T:${encryption};S:${values.wifiSsid};P:${values.wifiPassword};;`; + } + case 'vCard': + return `BEGIN:VCARD +VERSION:3.0 +N:${values.vCardName} +FN:${values.vCardName} +ORG:${values.vCardCompany} +TITLE:${values.vCardTitle} +TEL:${values.vCardPhone} +EMAIL:${values.vCardEmail} +ADR:${values.vCardAddress} +URL:${values.vCardWebsite} +END:VCARD`; + + default: + return ''; + } +} + +/** + * Renders the QR code for the given form values and returns it as a + * downloadable PNG File. Returns null if there's nothing to encode yet + * (e.g. required field for the current type is still empty). + */ +export function generateQrCodeFile( + options: InitialValuesType +): Promise { + const qrValue = formatQRCodeData(options); + if (!qrValue) return Promise.resolve(null); + + const canvas = document.createElement('canvas'); + + return new Promise((resolve, reject) => { + QRCode.toDataURL( + canvas, + qrValue, + { + color: { + dark: options.fgColor, + light: options.bgColor + }, + width: Number(options.size) || 200, + errorCorrectionLevel: options.correctionLevel + }, + async (error, url) => { + // The original callback never checked `error`, so a QR generation + // failure (e.g. text too long for the chosen correction level) + // would silently try to fetch `undefined` and throw a confusing + // error instead. Surface it properly here. + if (error) { + reject(error); + return; + } + try { + const res = await fetch(url); + const blob = await res.blob(); + const file = new File([blob], 'qr-code.png', { type: 'image/png' }); + resolve(file); + } catch (fetchErr) { + reject(fetchErr); + } + } + ); + }); +} diff --git a/src/pages/tools/image/generic/qr-code/types.ts b/src/pages/tools/image/generic/qr-code/types.ts index b9959247..4aa78280 100644 --- a/src/pages/tools/image/generic/qr-code/types.ts +++ b/src/pages/tools/image/generic/qr-code/types.ts @@ -7,6 +7,8 @@ export type QRCodeType = | 'WiFi' | 'vCard'; +export type QRErrorCorrectionLevel = 'L' | 'M' | 'Q' | 'H'; + export type WifiEncryptionType = 'WPA' | 'WEP' | 'None'; export interface InitialValuesType { @@ -16,6 +18,7 @@ export interface InitialValuesType { size: string; bgColor: string; fgColor: string; + correctionLevel: QRErrorCorrectionLevel; // URL url: string;