Skip to content

Commit

Permalink
refactor(image): add i18n to upload and make error messages more helpful
Browse files Browse the repository at this point in the history
  • Loading branch information
elbotho committed Dec 20, 2024
1 parent 442d6e9 commit 42ab619
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 16 deletions.
5 changes: 5 additions & 0 deletions packages/editor/src/i18n/strings/de/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,11 @@ export const editStrings = {
invalidUrl: 'Fehler: Ungültige oder unvollständige URL',
invalidUrlMessage:
'Die eingegebene URL ist entweder ungültig oder unvollständig. Bitte stelle sicher, dass du die vollständige URL korrekt kopiert und eingefügt hast. Die URL sollte mit "http://" oder "https://" beginnen.',
noFileSelected: 'Bitte wähle eine Datei aus',
badExtension:
"Sorry, %ext% ist leider nicht erlaubt. Versuch's mit diesen Typen: %allowed%",
fileTooBig:
"Sorry, diese Datei ist zu groß. Versuch's weniger als %maxsize% MB",
},
settings: 'Einstellungen',
extendedSettings: 'Erweiterte Einstellungen',
Expand Down
4 changes: 4 additions & 0 deletions packages/editor/src/i18n/strings/en/edit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,10 @@ export const editStrings = {
invalidUrl: 'Error: Invalid or Incomplete URL',
invalidUrlMessage:
'The URL you entered is either invalid or incomplete. Please ensure you have copied and pasted the full URL correctly. The URL should start with "http://" or "https://".',
noFileSelected: 'Please select a file',
badExtension:
'Sorry, %ext% is not an accepted file type. Try one of: %allowed%',
fileTooBig: 'Sorry, this file is too big. Maximum size is %maxsize% MB',
},
settings: 'Settings',
extendedSettings: 'Extended Settings',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function UploadButton({
<input
type="file"
multiple={!!config.onMultipleUpload}
accept="image/*"
accept="image/*,.gif,.jpg,.jpeg,.png,.svg,.webp"
className="sr-only"
onChange={({ target }) => {
if (target.files && target.files.length) {
Expand Down
11 changes: 8 additions & 3 deletions packages/editor/src/plugins/image/utils/upload-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import {
EditorMetaContext,
type EditorMeta,
} from '@editor/core/contexts/editor-meta-context'
import { useEditStrings } from '@editor/i18n/edit-strings-provider'
import { type UploadHandler } from '@editor/plugin'
import { EditStrings } from '@editor/types/language-data'
import { useContext } from 'react'

import { handleError, validateFile } from './validate-file'
Expand All @@ -11,8 +13,9 @@ type UploadMeta = Pick<EditorMeta, 'editorVariant' | 'userId'>

export function useUploadFile(oldUploader?: UploadHandler<string>) {
const { editorVariant, userId } = useContext(EditorMetaContext)

const uploader = (file: File) => uploadFile({ file, editorVariant, userId })
const uploadStrings = useEditStrings().edtrIo.fileUpload
const uploader = (file: File) =>
uploadFile({ file, editorVariant, userId, uploadStrings })
return shouldUseNewUpload() ? uploader : (oldUploader ?? uploader)
}

Expand All @@ -38,10 +41,12 @@ async function uploadFile({
file,
editorVariant,
userId,
uploadStrings,
}: UploadMeta & {
file: File
uploadStrings: EditStrings['edtrIo']['fileUpload']
}) {
const validated = validateFile(file)
const validated = validateFile(file, uploadStrings)
if (!validated) return Promise.reject()

const parentHost = getParentHost()
Expand Down
41 changes: 31 additions & 10 deletions packages/editor/src/plugins/image/utils/validate-file.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { showToastNotice } from '@editor/editor-ui/show-toast-notice'
import { EditStrings } from '@editor/types/language-data'

export enum FileErrorCode {
TOO_MANY_FILES,
Expand All @@ -12,7 +13,8 @@ export interface FileError {
errorCode: FileErrorCode
message: string
}
const maxFileSize = 2 * 1024 * 1024
const maxImageFileSize = 2 * 1024 * 1024
const maxVideoFileSize = 16 * 1024 * 1024
const allowedExtensions = [
'gif',
'jpg',
Expand All @@ -24,31 +26,50 @@ const allowedExtensions = [
'mp4',
]

export function validateFile(file: File) {
// TODO: i18n and make error messages actually helpful
export function validateFile(
file: File,
uploadStrings: EditStrings['edtrIo']['fileUpload']
) {
if (!file) {
handleError('No file selected')
handleError(uploadStrings.noFileSelected)
return false
}
if (!matchesAllowedExtensions(file.name)) {
handleError('Not an accepted file type')

const extension = file.name
.toLowerCase()
.slice(file.name.lastIndexOf('.') + 1)

if (!matchesAllowedExtensions(extension)) {
handleError(
uploadStrings.badExtension
.replace('%ext%', extension)
.replace('%allowed%', allowedExtensions.join(', '))
)
return false
}
const maxFileSize = file.type.startsWith('video/')
? maxVideoFileSize
: maxImageFileSize

if (file.size > maxFileSize) {
handleError('File is too big')
handleError(
uploadStrings.fileTooBig.replace(
'%maxsize%',
String(maxFileSize / 1024 / 1024)
)
)
return false
}

return true
}

function matchesAllowedExtensions(fileName: string) {
const extension = fileName.toLowerCase().slice(fileName.lastIndexOf('.') + 1)
function matchesAllowedExtensions(extension: string) {
return allowedExtensions.includes(extension)
}

export function handleError(message: string) {
// eslint-disable-next-line no-console
console.error(message)
showToastNotice(message, 'warning')
showToastNotice('⚠️ ' + message, 'warning')
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,10 @@ export function UploadButton({ src, onFocus, onBlur }: UploadButtonProps) {
</span>
<input
type="file"
accept="video/mp4, video/webm"
accept="video/mp4,video/webm,.mp4,.webm"
className="sr-only"
onChange={({ target }) => {
if (target.files && target.files.length) {
// const filesArray = Array.from(target.files)
void src.upload(target.files[0], upload)
}
}}
Expand Down

0 comments on commit 42ab619

Please sign in to comment.