Skip to content

Commit

Permalink
🐛 fix: fix clipboard copy issue and improve upload cors feedback (lob…
Browse files Browse the repository at this point in the history
…ehub#3557)

* 🐛 fix: fix clipboard copy issue

* 🐛 fix: fix clipboard copy issue

* 🚸 style: improve cors upload issue

* 🚸 style: improve cors upload issue

* 🚸 style: improve cors upload issue
  • Loading branch information
arvinxx authored Aug 22, 2024
1 parent 2ed0b8e commit 86c5a99
Show file tree
Hide file tree
Showing 23 changed files with 244 additions and 24 deletions.
5 changes: 4 additions & 1 deletion locales/ar/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "التفاصيل: {{detail}}",
"fileOnlySupportInServerMode": "وضع النشر الحالي لا يدعم تحميل ملفات غير الصور. إذا كنت بحاجة إلى تحميل تنسيق {{ext}}، يرجى التبديل إلى نشر قاعدة بيانات الخادم أو استخدام خدمة LobeChat Cloud.",
"title": "فشل تحميل الملف، يرجى التحقق من الاتصال بالشبكة أو المحاولة لاحقًا"
"networkError": "يرجى التأكد من أن اتصال الشبكة لديك يعمل بشكل صحيح، والتحقق من إعدادات تكوين خدمة تخزين الملفات عبر النطاق.",
"title": "فشل تحميل الملف، يرجى التحقق من الاتصال بالشبكة أو المحاولة لاحقًا",
"unknownError": "سبب الخطأ: {{reason}}",
"uploadFailed": "فشل تحميل الملف"
}
}
5 changes: 4 additions & 1 deletion locales/bg-BG/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Подробности: {{detail}}",
"fileOnlySupportInServerMode": "Текущият режим на разполагане не поддържа качване на файлове, различни от изображения. За да качите формат {{ext}}, моля, превключете на разполагане с база данни на сървъра или използвайте услугата LobeChat Cloud.",
"title": "Неуспешно качване на файл, моля проверете интернет връзката или опитайте по-късно"
"networkError": "Моля, уверете се, че вашата мрежа работи нормално и проверете дали конфигурацията за крос-домейн на услугата за съхранение на файлове е правилна.",
"title": "Неуспешно качване на файл, моля проверете интернет връзката или опитайте по-късно",
"unknownError": "Причина за грешка: {{reason}}",
"uploadFailed": "Неуспешно качване на файла."
}
}
5 changes: 4 additions & 1 deletion locales/de-DE/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Details: {{detail}}",
"fileOnlySupportInServerMode": "Der aktuelle Bereitstellungsmodus unterstützt das Hochladen von Nicht-Bilddateien nicht. Um Dateien im {{ext}}-Format hochzuladen, wechseln Sie bitte zum Serverdatenbank-Bereitstellungsmodus oder verwenden Sie den LobeChat Cloud-Dienst.",
"title": "Dateiupload fehlgeschlagen. Bitte überprüfen Sie Ihre Netzwerkverbindung und versuchen Sie es später erneut."
"networkError": "Bitte überprüfen Sie, ob Ihre Internetverbindung stabil ist, und prüfen Sie die Cross-Origin-Konfiguration des Dateispeicherdienstes.",
"title": "Dateiupload fehlgeschlagen. Bitte überprüfen Sie Ihre Netzwerkverbindung und versuchen Sie es später erneut.",
"unknownError": "Fehlerursache: {{reason}}",
"uploadFailed": "Der Datei-Upload ist fehlgeschlagen."
}
}
5 changes: 4 additions & 1 deletion locales/en-US/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Details: {{detail}}",
"fileOnlySupportInServerMode": "The current deployment mode does not support uploading non-image files. To upload files in {{ext}} format, please switch to server database deployment or use LobeChat Cloud service.",
"title": "File upload failed. Please check your network connection or try again later"
"networkError": "Please check your network connection and ensure that the file storage service's cross-origin configuration is correct.",
"title": "File upload failed. Please check your network connection or try again later",
"unknownError": "Error reason: {{reason}}",
"uploadFailed": "File upload failed."
}
}
5 changes: 4 additions & 1 deletion locales/es-ES/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Detalles: {{detail}}",
"fileOnlySupportInServerMode": "El modo de implementación actual no admite la carga de archivos que no sean imágenes. Si desea cargar un archivo en formato {{ext}}, cambie a la implementación de base de datos en servidor o utilice el servicio LobeChat Cloud.",
"title": "Error al subir el archivo, por favor verifica la conexión a internet o inténtalo de nuevo más tarde"
"networkError": "Por favor, verifica que tu red esté funcionando correctamente y comprueba si la configuración de CORS del servicio de almacenamiento de archivos es correcta.",
"title": "Error al subir el archivo, por favor verifica la conexión a internet o inténtalo de nuevo más tarde",
"unknownError": "Razón del error: {{reason}}",
"uploadFailed": "La carga del archivo ha fallado."
}
}
5 changes: 4 additions & 1 deletion locales/fr-FR/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Détails : {{detail}}",
"fileOnlySupportInServerMode": "Le mode de déploiement actuel ne prend pas en charge le téléchargement de fichiers non image. Pour télécharger un format {{ext}}, veuillez passer à un déploiement de base de données côté serveur ou utiliser le service LobeChat Cloud.",
"title": "Échec de l'envoi du fichier, veuillez vérifier votre connexion réseau ou réessayer plus tard"
"networkError": "Veuillez vérifier si votre réseau fonctionne correctement et assurez-vous que la configuration CORS du service de stockage de fichiers est correcte.",
"title": "Échec de l'envoi du fichier, veuillez vérifier votre connexion réseau ou réessayer plus tard",
"unknownError": "Raison de l'erreur : {{reason}}",
"uploadFailed": "Échec du téléchargement du fichier."
}
}
5 changes: 4 additions & 1 deletion locales/it-IT/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Dettagli: {{detail}}",
"fileOnlySupportInServerMode": "L'attuale modalità di distribuzione non supporta il caricamento di file non immagine. Se desideri caricare un formato {{ext}}, ti preghiamo di passare alla distribuzione del database sul server o di utilizzare il servizio LobeChat Cloud.",
"title": "Caricamento del file fallito, controlla la connessione di rete o riprova più tardi"
"networkError": "Si prega di verificare che la connessione di rete sia stabile e controllare se la configurazione CORS del servizio di archiviazione file è corretta.",
"title": "Caricamento del file fallito, controlla la connessione di rete o riprova più tardi",
"unknownError": "Motivo dell'errore: {{reason}}",
"uploadFailed": "Caricamento del file non riuscito."
}
}
5 changes: 4 additions & 1 deletion locales/ja-JP/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "詳細: {{detail}}",
"fileOnlySupportInServerMode": "現在のデプロイモードでは、画像以外のファイルのアップロードはサポートされていません。{{ext}} 形式のファイルをアップロードするには、サーバーデータベースデプロイに切り替えるか、LobeChat Cloud サービスを使用してください。",
"title": "ファイルのアップロードに失敗しました。ネットワーク接続を確認するか、後でもう一度お試しください"
"networkError": "ネットワークが正常であることを確認し、ファイルストレージサービスのクロスオリジン設定が正しいかどうかを確認してください。",
"title": "ファイルのアップロードに失敗しました。ネットワーク接続を確認するか、後でもう一度お試しください",
"unknownError": "エラーの原因: {{reason}}",
"uploadFailed": "ファイルのアップロードに失敗しました。"
}
}
5 changes: 4 additions & 1 deletion locales/ko-KR/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "상세 내용: {{detail}}",
"fileOnlySupportInServerMode": "현재 배포 모드에서는 이미지 파일이 아닌 파일 업로드를 지원하지 않습니다. {{ext}} 형식을 업로드하려면 서버 데이터베이스 배포로 전환하거나 LobeChat Cloud 서비스를 사용하세요.",
"title": "파일 업로드 실패, 네트워크 연결을 확인하거나 나중에 다시 시도해주세요"
"networkError": "네트워크가 정상인지 확인하고 파일 저장 서비스의 교차 출처 구성도 올바른지 확인하세요.",
"title": "파일 업로드 실패, 네트워크 연결을 확인하거나 나중에 다시 시도해주세요",
"unknownError": "오류 원인: {{reason}}",
"uploadFailed": "파일 업로드에 실패했습니다."
}
}
5 changes: 4 additions & 1 deletion locales/nl-NL/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Details: {{detail}}",
"fileOnlySupportInServerMode": "De huidige implementatiemodus ondersteunt het uploaden van niet-afbeeldingsbestanden niet. Als u bestanden in {{ext}}-formaat wilt uploaden, schakelt u over naar de serverdatabase-implementatie of gebruikt u de LobeChat Cloud-service.",
"title": "Bestand uploaden mislukt, controleer uw internetverbinding of probeer het later opnieuw"
"networkError": "Controleer of je netwerk goed werkt en of de cross-origin configuratie van de bestandsopslagservice correct is.",
"title": "Bestand uploaden mislukt, controleer uw internetverbinding of probeer het later opnieuw",
"unknownError": "Foutreden: {{reason}}",
"uploadFailed": "Bestand uploaden is mislukt."
}
}
5 changes: 4 additions & 1 deletion locales/pl-PL/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Szczegóły: {{detail}}",
"fileOnlySupportInServerMode": "Aktualny tryb wdrożenia nie obsługuje przesyłania plików, które nie są obrazami. Aby przesłać pliki w formacie {{ext}}, przełącz się na wdrożenie bazy danych na serwerze lub skorzystaj z usługi LobeChat Cloud.",
"title": "Nie udało się przesłać pliku. Sprawdź połączenie sieciowe lub spróbuj ponownie później"
"networkError": "Proszę upewnić się, że Twoja sieć działa poprawnie oraz sprawdzić, czy konfiguracja CORS dla usługi przechowywania plików jest prawidłowa.",
"title": "Nie udało się przesłać pliku. Sprawdź połączenie sieciowe lub spróbuj ponownie później",
"unknownError": "Przyczyna błędu: {{reason}}",
"uploadFailed": "Wysyłanie pliku nie powiodło się."
}
}
5 changes: 4 additions & 1 deletion locales/pt-BR/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Detalhes: {{detail}}",
"fileOnlySupportInServerMode": "O modo de implantação atual não suporta o upload de arquivos que não sejam imagens. Para fazer o upload de arquivos no formato {{ext}}, por favor, mude para a implantação do banco de dados no servidor ou utilize o serviço LobeChat Cloud.",
"title": "Falha ao enviar o arquivo, verifique a conexão de rede ou tente novamente mais tarde"
"networkError": "Por favor, verifique se sua rede está funcionando corretamente e se a configuração de CORS do serviço de armazenamento de arquivos está correta.",
"title": "Falha ao enviar o arquivo, verifique a conexão de rede ou tente novamente mais tarde",
"unknownError": "Erro: {{reason}}",
"uploadFailed": "Falha ao fazer o upload do arquivo."
}
}
5 changes: 4 additions & 1 deletion locales/ru-RU/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Подробности: {{detail}}",
"fileOnlySupportInServerMode": "Текущий режим развертывания не поддерживает загрузку файлов, отличных от изображений. Если вы хотите загрузить файл формата {{ext}}, пожалуйста, переключитесь на развертывание с серверной базой данных или используйте LobeChat Cloud.",
"title": "Ошибка загрузки файла. Проверьте подключение к сети или попробуйте позже"
"networkError": "Пожалуйста, убедитесь, что ваше соединение с сетью работает нормально, и проверьте правильность конфигурации кросс-доменных запросов для службы хранения файлов.",
"title": "Ошибка загрузки файла. Проверьте подключение к сети или попробуйте позже",
"unknownError": "Причина ошибки: {{reason}}",
"uploadFailed": "Ошибка загрузки файла"
}
}
5 changes: 4 additions & 1 deletion locales/tr-TR/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Detay: {{detail}}",
"fileOnlySupportInServerMode": "Mevcut dağıtım modu, yalnızca resim dosyalarının yüklenmesini desteklemektedir. {{ext}} formatında bir dosya yüklemek istiyorsanız, lütfen sunucu veritabanı dağıtımına geçin veya LobeChat Cloud hizmetini kullanın.",
"title": "Dosya yükleme başarısız, lütfen ağ bağlantınızı kontrol edin veya daha sonra tekrar deneyin"
"networkError": "Lütfen ağ bağlantınızın düzgün çalıştığından emin olun ve dosya depolama hizmetinin çapraz alan yapılandırmasının doğru olup olmadığını kontrol edin.",
"title": "Dosya yükleme başarısız, lütfen ağ bağlantınızı kontrol edin veya daha sonra tekrar deneyin",
"unknownError": "Hata nedeni: {{reason}}",
"uploadFailed": "Dosya yüklemesi başarısız oldu."
}
}
5 changes: 4 additions & 1 deletion locales/vi-VN/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "Chi tiết: {{detail}}",
"fileOnlySupportInServerMode": "Chế độ triển khai hiện tại không hỗ trợ tải lên các tệp không phải hình ảnh. Nếu bạn cần tải lên định dạng {{ext}}, vui lòng chuyển sang triển khai cơ sở dữ liệu trên máy chủ hoặc sử dụng dịch vụ LobeChat Cloud.",
"title": "Tải lên tệp thất bại, vui lòng kiểm tra kết nối mạng hoặc thử lại sau"
"networkError": "Vui lòng kiểm tra xem mạng của bạn có hoạt động bình thường không và kiểm tra cấu hình chia sẻ tệp giữa các miền có đúng không",
"title": "Tải lên tệp thất bại, vui lòng kiểm tra kết nối mạng hoặc thử lại sau",
"unknownError": "Lỗi: {{reason}}",
"uploadFailed": "Tải tệp lên không thành công"
}
}
5 changes: 4 additions & 1 deletion locales/zh-CN/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "详情: {{detail}}",
"fileOnlySupportInServerMode": "当前部署模式不支持上传非图片文件,如需上传 {{ext}} 格式,请切换到服务端数据库部署或使用 LobeChat Cloud 服务",
"title": "文件上传失败,请检查网络连接或稍后再试"
"networkError": "请确认你的网络是否正常,并检查文件存储服务跨域配置是否正确",
"title": "文件上传失败,请检查网络连接或稍后再试",
"unknownError": "错误原因: {{reason}}",
"uploadFailed": "文件上传失败"
}
}
5 changes: 4 additions & 1 deletion locales/zh-TW/error.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,9 @@
"upload": {
"desc": "詳情: {{detail}}",
"fileOnlySupportInServerMode": "當前部署模式不支持上傳非圖片文件,如需上傳 {{ext}} 格式,請切換到伺服器端資料庫部署或使用 LobeChat Cloud 服務",
"title": "檔案上傳失敗,請檢查網路連線或稍後再試"
"networkError": "請確認你的網路是否正常,並檢查檔案儲存服務的跨域配置是否正確",
"title": "檔案上傳失敗,請檢查網路連線或稍後再試",
"unknownError": "錯誤原因: {{reason}}",
"uploadFailed": "檔案上傳失敗"
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@
"@vercel/speed-insights": "^1.0.12",
"ahooks": "^3.8.0",
"ai": "^3.2.16",
"antd": "5.20.0",
"antd": "^5.20.2",
"antd-style": "^3.6.2",
"brotli-wasm": "^3.0.1",
"chroma-js": "^2.4.2",
Expand Down
130 changes: 130 additions & 0 deletions src/components/DragUpload/useDragUpload.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { act, renderHook } from '@testing-library/react';
import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { getContainer, useDragUpload } from './useDragUpload';

describe('useDragUpload', () => {
let mockOnUploadFiles: Mock;

beforeEach(() => {
mockOnUploadFiles = vi.fn();
vi.useFakeTimers();
document.body.innerHTML = '';
});

afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
});

it('should initialize and cleanup correctly', () => {
const { result, unmount } = renderHook(() => useDragUpload(mockOnUploadFiles));

expect(result.current).toBe(false);
expect(document.getElementById('dragging-root')).not.toBeNull();

unmount();

expect(document.getElementById('dragging-root')).toBeNull();
});

it('should handle drag events correctly', () => {
const { result } = renderHook(() => useDragUpload(mockOnUploadFiles));

act(() => {
window.dispatchEvent(new Event('dragenter'));
});

expect(result.current).toBe(false);

act(() => {
const dragEnterEvent = new Event('dragenter') as DragEvent;
Object.defineProperty(dragEnterEvent, 'dataTransfer', {
value: {
items: [{}],
types: ['Files'],
},
});
window.dispatchEvent(dragEnterEvent);
});

expect(result.current).toBe(true);

act(() => {
const dragLeaveEvent = new Event('dragleave') as DragEvent;
Object.defineProperty(dragLeaveEvent, 'dataTransfer', {
value: {
items: [{}],
types: ['Files'],
},
});
window.dispatchEvent(dragLeaveEvent);
});

expect(result.current).toBe(false);
});

it('should handle file drop', async () => {
renderHook(() => useDragUpload(mockOnUploadFiles));

const mockFile = new File([''], 'test.txt', { type: 'text/plain' });
const dropEvent = new Event('drop') as DragEvent;
Object.defineProperty(dropEvent, 'dataTransfer', {
value: {
items: [
{
kind: 'file',
getAsFile: () => mockFile,
webkitGetAsEntry: () => ({
isFile: true,
file: (cb: (file: File) => void) => cb(mockFile),
}),
},
],
types: ['Files'],
},
});

await act(async () => {
window.dispatchEvent(dropEvent);
});

expect(mockOnUploadFiles).toHaveBeenCalledWith([mockFile]);
});

it('should handle paste event', async () => {
renderHook(() => useDragUpload(mockOnUploadFiles));

const mockFile = new File([''], 'test.txt', { type: 'text/plain' });
const pasteEvent = new Event('paste') as ClipboardEvent;
Object.defineProperty(pasteEvent, 'clipboardData', {
value: {
items: [
{
kind: 'file',
getAsFile: () => mockFile,
webkitGetAsEntry: () => null,
},
],
},
});

await act(async () => {
window.dispatchEvent(pasteEvent);
});

expect(mockOnUploadFiles).toHaveBeenCalledWith([mockFile]);
});
});

describe('getContainer', () => {
it('should return the dragging root element', () => {
const rootElement = document.createElement('div');
rootElement.id = 'dragging-root';
document.body.appendChild(rootElement);

const container = getContainer();
expect(container).not.toBeNull();
expect(container?.id).toBe('dragging-root');
});
});
9 changes: 9 additions & 0 deletions src/components/DragUpload/useDragUpload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@ const getFileListFromDataTransferItems = async (items: DataTransferItem[]) => {
const entry = item.webkitGetAsEntry();
if (entry) {
filePromises.push(processEntry(entry));
} else {
const file = item.getAsFile();

if (file)
filePromises.push(
new Promise((resolve) => {
resolve([file]);
}),
);
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/locales/default/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ export default {
desc: '详情: {{detail}}',
fileOnlySupportInServerMode:
'当前部署模式不支持上传非图片文件,如需上传 {{ext}} 格式,请切换到服务端数据库部署或使用 LobeChat Cloud 服务',
networkError: '请确认你的网络是否正常,并检查文件存储服务跨域配置是否正确',
title: '文件上传失败,请检查网络连接或稍后再试',
unknownError: '错误原因: {{reason}}',
uploadFailed: '文件上传失败',
},
};
Loading

0 comments on commit 86c5a99

Please sign in to comment.