Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(editor): show file upload progress (#17308)

Tsukiac8bd5296440
diff --git a/locales/ar/editor.json b/locales/ar/editor.json
index 4ca22330c2e..cab86984b92 100644
--- a/locales/ar/editor.json
+++ b/locales/ar/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "استخدام التبويبات",
"confirm": "تأكيد",
"file.error": "خطأ: {{message}}",
+ "file.preparing": "جارٍ تحضير التحميل…",
+ "file.processing": "جارٍ معالجة الملف…",
"file.uploading": "جاري رفع الملف...",
+ "file.uploadingProgress": "جارٍ التحميل… {{progress}}%",
"image.broken": "الصورة تالفة",
"link.edit": "تعديل الرابط",
"link.editLinkTitle": "الرابط",
diff --git a/locales/bg-BG/editor.json b/locales/bg-BG/editor.json
index 06c051cbbc1..27b540b017a 100644
--- a/locales/bg-BG/editor.json
+++ b/locales/bg-BG/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Използвай табулации",
"confirm": "Потвърди",
"file.error": "Грешка: {{message}}",
+ "file.preparing": "Подготвяне за качване…",
+ "file.processing": "Обработване на файла…",
"file.uploading": "Качване на файл...",
+ "file.uploadingProgress": "Качване… {{progress}}%",
"image.broken": "Изображението е повредено",
"link.edit": "Редактирай връзка",
"link.editLinkTitle": "Връзка",
diff --git a/locales/de-DE/editor.json b/locales/de-DE/editor.json
index 774f0f020e6..d9624e1b449 100644
--- a/locales/de-DE/editor.json
+++ b/locales/de-DE/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Tabs verwenden",
"confirm": "Bestätigen",
"file.error": "Fehler: {{message}}",
+ "file.preparing": "Upload wird vorbereitet…",
+ "file.processing": "Datei wird verarbeitet…",
"file.uploading": "Datei wird hochgeladen...",
+ "file.uploadingProgress": "Hochladen… {{progress}}%",
"image.broken": "Bild ist beschädigt",
"link.edit": "Link bearbeiten",
"link.editLinkTitle": "Link",
diff --git a/locales/en-US/editor.json b/locales/en-US/editor.json
index 17de519c5a1..52f2d512c33 100644
--- a/locales/en-US/editor.json
+++ b/locales/en-US/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Use Tabs",
"confirm": "Confirm",
"file.error": "Error: {{message}}",
+ "file.preparing": "Preparing upload…",
+ "file.processing": "Processing file…",
"file.uploading": "Uploading file...",
+ "file.uploadingProgress": "Uploading… {{progress}}%",
"image.broken": "Image is corrupted",
"link.edit": "Edit link",
"link.editLinkTitle": "Link",
diff --git a/locales/es-ES/editor.json b/locales/es-ES/editor.json
index 9ae905b588a..4b34d9b4fba 100644
--- a/locales/es-ES/editor.json
+++ b/locales/es-ES/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Usar tabulaciones",
"confirm": "Confirmar",
"file.error": "Error: {{message}}",
+ "file.preparing": "Preparando la carga…",
+ "file.processing": "Procesando el archivo…",
"file.uploading": "Subiendo archivo...",
+ "file.uploadingProgress": "Subiendo… {{progress}}%",
"image.broken": "La imagen está dañada",
"link.edit": "Editar enlace",
"link.editLinkTitle": "Enlace",
diff --git a/locales/fa-IR/editor.json b/locales/fa-IR/editor.json
index 9e5d85a02ec..999d53f3534 100644
--- a/locales/fa-IR/editor.json
+++ b/locales/fa-IR/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "استفاده از تب‌ها",
"confirm": "تأیید",
"file.error": "خطا: {{message}}",
+ "file.preparing": "در حال آماده‌سازی برای بارگذاری…",
+ "file.processing": "در حال پردازش فایل…",
"file.uploading": "در حال بارگذاری فایل...",
+ "file.uploadingProgress": "در حال بارگذاری… {{progress}}%",
"image.broken": "تصویر خراب است",
"link.edit": "ویرایش لینک",
"link.editLinkTitle": "لینک",
diff --git a/locales/fr-FR/editor.json b/locales/fr-FR/editor.json
index bd093ed30fb..508305043a3 100644
--- a/locales/fr-FR/editor.json
+++ b/locales/fr-FR/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Utiliser des tabulations",
"confirm": "Confirmer",
"file.error": "Erreur : {{message}}",
+ "file.preparing": "Préparation du téléchargement…",
+ "file.processing": "Traitement du fichier…",
"file.uploading": "Téléversement du fichier...",
+ "file.uploadingProgress": "Téléchargement… {{progress}}%",
"image.broken": "Image corrompue",
"link.edit": "Modifier le lien",
"link.editLinkTitle": "Lien",
diff --git a/locales/it-IT/editor.json b/locales/it-IT/editor.json
index 7fc60270b7b..58d47cfaad5 100644
--- a/locales/it-IT/editor.json
+++ b/locales/it-IT/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Usa tabulazioni",
"confirm": "Conferma",
"file.error": "Errore: {{message}}",
+ "file.preparing": "Preparazione del caricamento…",
+ "file.processing": "Elaborazione del file…",
"file.uploading": "Caricamento file in corso...",
+ "file.uploadingProgress": "Caricamento… {{progress}}%",
"image.broken": "Immagine danneggiata",
"link.edit": "Modifica link",
"link.editLinkTitle": "Link",
diff --git a/locales/ja-JP/editor.json b/locales/ja-JP/editor.json
index 644c1b689a2..118868e3b3c 100644
--- a/locales/ja-JP/editor.json
+++ b/locales/ja-JP/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "タブを使用",
"confirm": "確認",
"file.error": "エラー:{{message}}",
+ "file.preparing": "アップロードの準備中…",
+ "file.processing": "ファイルを処理中…",
"file.uploading": "ファイルをアップロードしています...",
+ "file.uploadingProgress": "アップロード中… {{progress}}%",
"image.broken": "画像が破損しています",
"link.edit": "リンクを編集",
"link.editLinkTitle": "リンク",
diff --git a/locales/ko-KR/editor.json b/locales/ko-KR/editor.json
index aa7b95ac2c0..13586697957 100644
--- a/locales/ko-KR/editor.json
+++ b/locales/ko-KR/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "탭 사용",
"confirm": "확인",
"file.error": "오류: {{message}}",
+ "file.preparing": "업로드 준비 중…",
+ "file.processing": "파일 처리 중…",
"file.uploading": "파일 업로드 중...",
+ "file.uploadingProgress": "업로드 중… {{progress}}%",
"image.broken": "이미지가 손상되었습니다",
"link.edit": "링크 편집",
"link.editLinkTitle": "링크",
diff --git a/locales/nl-NL/editor.json b/locales/nl-NL/editor.json
index 65c81abef29..a1754f80599 100644
--- a/locales/nl-NL/editor.json
+++ b/locales/nl-NL/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Tabs gebruiken",
"confirm": "Bevestigen",
"file.error": "Fout: {{message}}",
+ "file.preparing": "Upload voorbereiden…",
+ "file.processing": "Bestand verwerken…",
"file.uploading": "Bestand uploaden...",
+ "file.uploadingProgress": "Uploaden… {{progress}}%",
"image.broken": "Afbeelding is beschadigd",
"link.edit": "Link bewerken",
"link.editLinkTitle": "Link",
diff --git a/locales/pl-PL/editor.json b/locales/pl-PL/editor.json
index 89b6c9b9c16..230628e0f50 100644
--- a/locales/pl-PL/editor.json
+++ b/locales/pl-PL/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Użyj tabulatorów",
"confirm": "Potwierdź",
"file.error": "Błąd: {{message}}",
+ "file.preparing": "Przygotowywanie przesyłania…",
+ "file.processing": "Przetwarzanie pliku…",
"file.uploading": "Przesyłanie pliku...",
+ "file.uploadingProgress": "Przesyłanie… {{progress}}%",
"image.broken": "Obraz jest uszkodzony",
"link.edit": "Edytuj link",
"link.editLinkTitle": "Link",
diff --git a/locales/pt-BR/editor.json b/locales/pt-BR/editor.json
index d832304b3be..15ba1cd9f12 100644
--- a/locales/pt-BR/editor.json
+++ b/locales/pt-BR/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Usar tabulações",
"confirm": "Confirmar",
"file.error": "Erro: {{message}}",
+ "file.preparing": "Preparando o upload…",
+ "file.processing": "Processando o arquivo…",
"file.uploading": "Enviando arquivo...",
+ "file.uploadingProgress": "Enviando… {{progress}}%",
"image.broken": "Imagem corrompida",
"link.edit": "Editar link",
"link.editLinkTitle": "Link",
diff --git a/locales/ru-RU/editor.json b/locales/ru-RU/editor.json
index df645d9f901..3e2de91fb67 100644
--- a/locales/ru-RU/editor.json
+++ b/locales/ru-RU/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Использовать табуляцию",
"confirm": "Подтвердить",
"file.error": "Ошибка: {{message}}",
+ "file.preparing": "Подготовка к загрузке…",
+ "file.processing": "Обработка файла…",
"file.uploading": "Загрузка файла...",
+ "file.uploadingProgress": "Загрузка… {{progress}}%",
"image.broken": "Изображение повреждено",
"link.edit": "Редактировать ссылку",
"link.editLinkTitle": "Ссылка",
diff --git a/locales/tr-TR/editor.json b/locales/tr-TR/editor.json
index 7b32c16ae75..59be331a040 100644
--- a/locales/tr-TR/editor.json
+++ b/locales/tr-TR/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Sekme kullan",
"confirm": "Onayla",
"file.error": "Hata: {{message}}",
+ "file.preparing": "Yükleme hazırlanıyor…",
+ "file.processing": "Dosya işleniyor…",
"file.uploading": "Dosya yükleniyor...",
+ "file.uploadingProgress": "Yükleniyor… {{progress}}%",
"image.broken": "Görsel bozuk",
"link.edit": "Bağlantıyı düzenle",
"link.editLinkTitle": "Bağlantı",
diff --git a/locales/vi-VN/editor.json b/locales/vi-VN/editor.json
index 6cce29eb9f8..149b1be66a7 100644
--- a/locales/vi-VN/editor.json
+++ b/locales/vi-VN/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "Sử dụng tab",
"confirm": "Xác nhận",
"file.error": "Lỗi: {{message}}",
+ "file.preparing": "Đang chuẩn bị tải lên…",
+ "file.processing": "Đang xử lý tệp…",
"file.uploading": "Đang tải tệp lên...",
+ "file.uploadingProgress": "Đang tải lên… {{progress}}%",
"image.broken": "Hình ảnh bị hỏng",
"link.edit": "Chỉnh sửa liên kết",
"link.editLinkTitle": "Liên kết",
diff --git a/locales/zh-CN/editor.json b/locales/zh-CN/editor.json
index af83df7fcb6..4a34949c2e8 100644
--- a/locales/zh-CN/editor.json
+++ b/locales/zh-CN/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "使用制表符",
"confirm": "确认",
"file.error": "错误:{{message}}",
+ "file.preparing": "正在准备上传…",
+ "file.processing": "正在处理文件…",
"file.uploading": "正在上传文件…",
+ "file.uploadingProgress": "正在上传… {{progress}}%",
"image.broken": "图片损坏",
"link.edit": "编辑链接",
"link.editLinkTitle": "链接",
diff --git a/locales/zh-TW/editor.json b/locales/zh-TW/editor.json
index 4716867b09c..c9359f653f1 100644
--- a/locales/zh-TW/editor.json
+++ b/locales/zh-TW/editor.json
@@ -31,7 +31,10 @@
"codemirror.useTabs": "使用 Tab 鍵",
"confirm": "確認",
"file.error": "錯誤:{{message}}",
+ "file.preparing": "準備上傳中…",
+ "file.processing": "檔案處理中…",
"file.uploading": "正在上傳檔案...",
+ "file.uploadingProgress": "上傳中… {{progress}}%",
"image.broken": "圖片損毀",
"link.edit": "編輯連結",
"link.editLinkTitle": "連結",
diff --git a/packages/locales/src/default/editor.ts b/packages/locales/src/default/editor.ts
index aeb82f38812..361de75e4f1 100644
--- a/packages/locales/src/default/editor.ts
+++ b/packages/locales/src/default/editor.ts
@@ -20,7 +20,10 @@ export default {
'codemirror.useTabs': 'Use Tabs',
'confirm': 'Confirm',
'file.error': 'Error: {{message}}',
+ 'file.preparing': 'Preparing upload…',
+ 'file.processing': 'Processing file…',
'file.uploading': 'Uploading file...',
+ 'file.uploadingProgress': 'Uploading… {{progress}}%',
'image.broken': 'Image is corrupted',
'link.edit': 'Edit link',
'link.editLinkTitle': 'Link',
diff --git a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
index 64036c250d5..65caa4fa248 100644
--- a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
+++ b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
@@ -2,10 +2,13 @@
* @vitest-environment happy-dom
*/
import { type IEditor, ReactToolbarPlugin } from '@lobehub/editor';
-import { render } from '@testing-library/react';
+import { act, render, screen } from '@testing-library/react';
+import { StrictMode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createEditorFileUploadTracker } from './editorFileUploadTracker';
import InternalEditor from './InternalEditor';
+import { LinearFileCard } from './LinearFilePlugin';
const editorProps = vi.hoisted(() => ({
last: undefined as any,
@@ -38,6 +41,10 @@ vi.mock('./InlineToolbar', () => ({
default: () => <div />,
}));
+vi.mock('@/components/FileIcon', () => ({
+ default: ({ fileName }: { fileName: string }) => <div>{fileName}</div>,
+}));
+
vi.mock('./useImageUpload', () => ({
useFileUpload: () => vi.fn(),
useImageUpload: () => vi.fn(),
@@ -48,7 +55,10 @@ vi.mock('@lobechat/const', () => ({
}));
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (key: string, options?: { progress?: number }) =>
+ key === 'file.uploadingProgress' ? `Uploading… ${options?.progress}%` : key,
+ }),
}));
describe('InternalEditor readonly state', () => {
@@ -95,4 +105,99 @@ describe('InternalEditor readonly state', () => {
expect(editorProps.last?.plugins).not.toContain(ReactToolbarPlugin);
});
+
+ it('renders the current file upload percentage', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['video'], 'recording.mp4', { type: 'video/mp4' });
+ const uploadId = tracker.start(file);
+ tracker.update(uploadId, 'uploading', { progress: 42, restTime: 8, speed: 1024 });
+
+ render(
+ <LinearFileCard
+ node={{ getKey: () => 'node-1', name: file.name, status: 'pending' }}
+ uploadTracker={tracker}
+ />,
+ );
+
+ expect(screen.getByText('Uploading… 42%', { exact: false })).toBeInTheDocument();
+ expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '42');
+ });
+
+ it('keeps the final upload status in the processing state', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['video'], 'recording.mp4', { type: 'video/mp4' });
+ const uploadId = tracker.start(file);
+ tracker.update(uploadId, 'success', { progress: 100, restTime: 0, speed: 1024 });
+
+ render(
+ <LinearFileCard
+ node={{ getKey: () => 'node-1', name: file.name, status: 'pending' }}
+ uploadTracker={tracker}
+ />,
+ );
+
+ expect(screen.getByText('file.processing', { exact: false })).toBeInTheDocument();
+ expect(screen.queryByText('file.preparing', { exact: false })).not.toBeInTheDocument();
+ });
+
+ it('keeps tracking progress through Strict Mode effect replay', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['video'], 'recording.mp4', { type: 'video/mp4' });
+ const uploadId = tracker.start(file);
+
+ render(
+ <StrictMode>
+ <LinearFileCard
+ node={{ getKey: () => 'node-1', name: file.name, status: 'pending' }}
+ uploadTracker={tracker}
+ />
+ </StrictMode>,
+ );
+
+ act(() => {
+ tracker.update(uploadId, 'uploading', { progress: 42, restTime: 8, speed: 1024 });
+ });
+
+ expect(screen.getByText('Uploading… 42%', { exact: false })).toBeInTheDocument();
+ });
+
+ it('releases upload state when a pending file node unmounts', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['video'], 'recording.mp4', { type: 'video/mp4' });
+ const uploadId = tracker.start(file);
+
+ const { unmount } = render(
+ <LinearFileCard
+ node={{ getKey: () => 'node-1', name: file.name, status: 'pending' }}
+ uploadTracker={tracker}
+ />,
+ );
+
+ expect(tracker.getSnapshot('node-1')).toBeDefined();
+
+ unmount();
+
+ expect(tracker.getSnapshot('node-1')).toBeUndefined();
+
+ tracker.finish(uploadId);
+ const nextFile = new File(['next'], file.name, { type: file.type });
+ const nextUploadId = tracker.start(nextFile);
+ tracker.bindNode('node-2', nextFile.name);
+
+ expect(tracker.getSnapshot('node-2')?.id).toBe(nextUploadId);
+ });
+
+ it('renders a persisted file card without an upload tracker', () => {
+ render(
+ <LinearFileCard
+ node={{
+ fileUrl: 'https://example.com/report.pdf',
+ name: 'report.pdf',
+ status: 'uploaded',
+ }}
+ />,
+ );
+
+ expect(screen.getAllByText('report.pdf')).not.toHaveLength(0);
+ });
});
diff --git a/src/features/EditorCanvas/LinearFilePlugin.tsx b/src/features/EditorCanvas/LinearFilePlugin.tsx
index fd09e37e1c4..207469f4f30 100644
--- a/src/features/EditorCanvas/LinearFilePlugin.tsx
+++ b/src/features/EditorCanvas/LinearFilePlugin.tsx
@@ -5,11 +5,23 @@ import { FilePlugin, UploadPlugin, useLexicalComposerContext } from '@lobehub/ed
import { ActionIcon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import { DownloadIcon } from 'lucide-react';
-import { type FC, memo, useLayoutEffect } from 'react';
+import {
+ type FC,
+ memo,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useSyncExternalStore,
+} from 'react';
import { useTranslation } from 'react-i18next';
import FileIcon from '@/components/FileIcon';
-import { formatSize } from '@/utils/format';
+import { formatSize, formatSpeed, formatTime } from '@/utils/format';
+
+import type { EditorFileUploadTracker } from './editorFileUploadTracker';
+import { createEditorFileUploadTracker } from './editorFileUploadTracker';
+import type { EditorAttachmentUpload } from './useImageUpload';
const styles = createStaticStyles(({ css, cssVar }) => ({
card: css`
@@ -60,6 +72,26 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
text-overflow: ellipsis;
white-space: nowrap;
`,
+ progress: css`
+ position: absolute;
+ inset-block-end: 0;
+ inset-inline-start: 0;
+
+ height: 3px;
+
+ background: ${cssVar.colorPrimary};
+
+ transition: width ${cssVar.motionDurationMid} ease-out;
+ `,
+ progressTrack: css`
+ position: absolute;
+ inset-block-end: 0;
+ inset-inline: 0;
+
+ height: 3px;
+
+ background: ${cssVar.colorFillSecondary};
+ `,
size: css`
margin-block-start: 2px;
font-size: ${cssVar.fontSizeSM};
@@ -80,10 +112,41 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorBgContainer};
`,
+ uploadCard: css`
+ position: relative;
+
+ overflow: hidden;
+ display: flex;
+ gap: 12px;
+ align-items: center;
+
+ box-sizing: border-box;
+ width: 100%;
+ padding-block: 10px;
+ padding-inline: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ color: ${cssVar.colorText};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ uploadMeta: css`
+ overflow: hidden;
+
+ margin-block-start: 2px;
+
+ font-size: ${cssVar.fontSizeSM};
+ line-height: 1.4;
+ color: ${cssVar.colorTextTertiary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
}));
interface FileNodeLike {
fileUrl?: string;
+ getKey?: () => string;
message?: string;
name: string;
size?: number;
@@ -92,15 +155,81 @@ interface FileNodeLike {
interface LinearFileCardProps {
node: FileNodeLike;
+ uploadTracker?: EditorFileUploadTracker;
}
-export const LinearFileCard = memo<LinearFileCardProps>(({ node }) => {
- const { t } = useTranslation('editor');
+const subscribeToNoUpload = () => () => {};
+
+export const LinearFileCard = memo<LinearFileCardProps>(({ node, uploadTracker }) => {
+ const { t } = useTranslation(['editor', 'file']);
const { fileUrl, message, name, size, status } = node;
+ const nodeKey = uploadTracker ? node.getKey?.() : undefined;
+ const upload = useSyncExternalStore(
+ uploadTracker && nodeKey !== undefined ? uploadTracker.subscribe : subscribeToNoUpload,
+ () => (uploadTracker && nodeKey !== undefined ? uploadTracker.getSnapshot(nodeKey) : undefined),
+ () => undefined,
+ );
+
+ useEffect(() => {
+ if (!uploadTracker || nodeKey === undefined) return;
+
+ if (status !== 'pending') {
+ uploadTracker.releaseNode(nodeKey);
+ return;
+ }
+
+ uploadTracker.bindNode(nodeKey, name);
+ return () => uploadTracker.releaseNode(nodeKey);
+ }, [name, nodeKey, status, uploadTracker]);
if (status === 'pending') {
- return <div className={styles.state}>{t('file.uploading')}</div>;
+ const uploadState = upload?.uploadState;
+ const rawProgress = Math.max(0, Math.min(100, uploadState?.progress || 0));
+ const progress =
+ upload?.status === 'uploading' ? Math.min(99, Math.round(rawProgress)) : rawProgress;
+ const fileSize = upload?.file.size || size;
+ const statusText =
+ upload?.status === 'processing' || upload?.status === 'success'
+ ? t('file.processing')
+ : upload?.status === 'uploading'
+ ? t('file.uploadingProgress', { progress })
+ : t('file.preparing');
+ const details = [
+ fileSize
+ ? uploadState
+ ? `${formatSize(fileSize * (rawProgress / 100))} / ${formatSize(fileSize)}`
+ : formatSize(fileSize)
+ : undefined,
+ upload?.status === 'uploading' && uploadState?.speed
+ ? formatSpeed(uploadState.speed)
+ : undefined,
+ upload?.status === 'uploading' && uploadState?.restTime
+ ? t('file:uploadDock.body.item.restTime', { time: formatTime(uploadState.restTime) })
+ : undefined,
+ ].filter(Boolean);
+
+ return (
+ <div className={styles.uploadCard}>
+ <FileIcon fileName={name} fileType={upload?.file.type} size={36} />
+ <div className={styles.info}>
+ <div className={styles.name}>{name}</div>
+ <div className={styles.uploadMeta}>
+ {[statusText, ...details].filter(Boolean).join(' · ')}
+ </div>
+ </div>
+ <div
+ aria-label={statusText}
+ aria-valuemax={100}
+ aria-valuemin={0}
+ aria-valuenow={progress}
+ className={styles.progressTrack}
+ role="progressbar"
+ >
+ <div className={styles.progress} style={{ width: `${progress}%` }} />
+ </div>
+ </div>
+ );
}
if (status === 'error') {
return (
@@ -140,7 +269,7 @@ export const LinearFileCard = memo<LinearFileCardProps>(({ node }) => {
LinearFileCard.displayName = 'LinearFileCard';
interface LinearFilePluginProps {
- handleUpload: (file: File) => Promise<{ url: string }>;
+ handleUpload: EditorAttachmentUpload;
/**
* Class applied to the outer Lexical `<span>` wrapper. Set to a block-level
* style so the file card claims its own line in the paragraph.
@@ -150,15 +279,36 @@ interface LinearFilePluginProps {
const LinearFilePlugin: FC<LinearFilePluginProps> = ({ handleUpload, theme }) => {
const [editor] = useLexicalComposerContext();
+ const uploadTrackerRef = useRef<EditorFileUploadTracker | null>(null);
+ if (!uploadTrackerRef.current) uploadTrackerRef.current = createEditorFileUploadTracker();
+ const uploadTracker = uploadTrackerRef.current;
+ const trackedHandleUpload = useCallback<EditorAttachmentUpload>(
+ async (file) => {
+ const uploadId = uploadTracker.start(file);
+
+ try {
+ const result = await handleUpload(file, (status, uploadState) => {
+ uploadTracker.update(uploadId, status, uploadState);
+ });
+ uploadTracker.finish(uploadId);
+ return result;
+ } catch (error) {
+ uploadTracker.update(uploadId, 'error');
+ uploadTracker.finish(uploadId);
+ throw error;
+ }
+ },
+ [handleUpload, uploadTracker],
+ );
useLayoutEffect(() => {
editor.registerPlugin(UploadPlugin);
editor.registerPlugin(FilePlugin, {
- decorator: (node) => <LinearFileCard node={node} />,
- handleUpload,
+ decorator: (node) => <LinearFileCard node={node} uploadTracker={uploadTracker} />,
+ handleUpload: trackedHandleUpload,
theme,
});
- }, [editor, handleUpload, theme]);
+ }, [editor, trackedHandleUpload, theme, uploadTracker]);
return null;
};
diff --git a/src/features/EditorCanvas/editorFileUploadTracker.test.ts b/src/features/EditorCanvas/editorFileUploadTracker.test.ts
new file mode 100644
index 00000000000..42c8fab395a
--- /dev/null
+++ b/src/features/EditorCanvas/editorFileUploadTracker.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createEditorFileUploadTracker } from './editorFileUploadTracker';
+
+describe('createEditorFileUploadTracker', () => {
+ it('tracks progress for the pending editor node', () => {
+ const tracker = createEditorFileUploadTracker();
+ const listener = vi.fn();
+ tracker.subscribe(listener);
+
+ const file = new File(['content'], 'report.pdf', { type: 'application/pdf' });
+ const uploadId = tracker.start(file);
+ listener.mockClear();
+ tracker.bindNode('node-1', file.name);
+
+ expect(listener).toHaveBeenCalledOnce();
+
+ tracker.update(uploadId, 'uploading', { progress: 42, restTime: 8, speed: 1024 });
+
+ expect(tracker.getSnapshot('node-1')).toEqual({
+ file,
+ id: uploadId,
+ status: 'uploading',
+ uploadState: { progress: 42, restTime: 8, speed: 1024 },
+ });
+ });
+
+ it('binds progress when the pending editor node renders before the upload starts', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['content'], 'report.pdf', { type: 'application/pdf' });
+
+ tracker.bindNode('node-1', file.name);
+ const uploadId = tracker.start(file);
+ tracker.update(uploadId, 'uploading', { progress: 42, restTime: 8, speed: 1024 });
+
+ expect(tracker.getSnapshot('node-1')).toEqual({
+ file,
+ id: uploadId,
+ status: 'uploading',
+ uploadState: { progress: 42, restTime: 8, speed: 1024 },
+ });
+ });
+
+ it('rebinds the same node after an effect cleanup while the upload is active', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['content'], 'report.pdf', { type: 'application/pdf' });
+ const uploadId = tracker.start(file);
+
+ tracker.bindNode('node-1', file.name);
+ tracker.releaseNode('node-1');
+ tracker.bindNode('node-1', file.name);
+ tracker.update(uploadId, 'uploading', { progress: 42, restTime: 8, speed: 1024 });
+
+ expect(tracker.getSnapshot('node-1')?.uploadState?.progress).toBe(42);
+ });
+
+ it('keeps simultaneous files with the same name bound to separate editor nodes', () => {
+ const tracker = createEditorFileUploadTracker();
+ const firstFile = new File(['first'], 'recording.mp4', { type: 'video/mp4' });
+ const secondFile = new File(['second'], 'recording.mp4', { type: 'video/mp4' });
+ const firstUploadId = tracker.start(firstFile);
+ const secondUploadId = tracker.start(secondFile);
+
+ tracker.bindNode('node-1', firstFile.name);
+ tracker.bindNode('node-2', secondFile.name);
+ tracker.update(firstUploadId, 'uploading', { progress: 25, restTime: 10, speed: 100 });
+ tracker.update(secondUploadId, 'uploading', { progress: 75, restTime: 3, speed: 300 });
+
+ expect(tracker.getSnapshot('node-1')?.uploadState?.progress).toBe(25);
+ expect(tracker.getSnapshot('node-2')?.uploadState?.progress).toBe(75);
+ });
+
+ it('does not bind a later node to a completed upload that rendered too quickly', () => {
+ const tracker = createEditorFileUploadTracker();
+ const firstFile = new File(['first'], 'recording.mp4', { type: 'video/mp4' });
+ const secondFile = new File(['second'], 'recording.mp4', { type: 'video/mp4' });
+ const firstUploadId = tracker.start(firstFile);
+ tracker.finish(firstUploadId);
+ const secondUploadId = tracker.start(secondFile);
+
+ tracker.bindNode('node-2', secondFile.name);
+
+ expect(tracker.getSnapshot('node-2')?.id).toBe(secondUploadId);
+ });
+
+ it('releases completed node state', () => {
+ const tracker = createEditorFileUploadTracker();
+ const file = new File(['content'], 'notes.txt', { type: 'text/plain' });
+ const uploadId = tracker.start(file);
+ tracker.bindNode('node-1', file.name);
+ tracker.finish(uploadId);
+
+ tracker.releaseNode('node-1');
+
+ const nextFile = new File(['next'], file.name, { type: file.type });
+ const nextUploadId = tracker.start(nextFile);
+ tracker.bindNode('node-2', nextFile.name);
+
+ expect(tracker.getSnapshot('node-1')).toBeUndefined();
+ expect(tracker.getSnapshot('node-2')?.id).toBe(nextUploadId);
+ });
+});
diff --git a/src/features/EditorCanvas/editorFileUploadTracker.ts b/src/features/EditorCanvas/editorFileUploadTracker.ts
new file mode 100644
index 00000000000..711c6e31abb
--- /dev/null
+++ b/src/features/EditorCanvas/editorFileUploadTracker.ts
@@ -0,0 +1,106 @@
+import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';
+
+export interface EditorFileUploadSnapshot {
+ file: File;
+ id: string;
+ status: FileUploadStatus;
+ uploadState?: FileUploadState;
+}
+
+export interface EditorFileUploadTracker {
+ bindNode: (nodeKey: string, fileName: string) => void;
+ finish: (id: string) => void;
+ getSnapshot: (nodeKey: string) => EditorFileUploadSnapshot | undefined;
+ releaseNode: (nodeKey: string) => void;
+ start: (file: File) => string;
+ subscribe: (listener: () => void) => () => void;
+ update: (id: string, status: FileUploadStatus, uploadState?: FileUploadState) => void;
+}
+
+export const createEditorFileUploadTracker = (): EditorFileUploadTracker => {
+ const finishedUploadIds = new Set<string>();
+ const listeners = new Set<() => void>();
+ const nodeFileNames = new Map<string, string>();
+ const nodeUploadIds = new Map<string, string>();
+ // Keep ownership after an effect cleanup so React Strict Mode can rebind the same node.
+ const uploadNodeKeys = new Map<string, string>();
+ const uploads = new Map<string, EditorFileUploadSnapshot>();
+ let nextId = 0;
+
+ const emit = () => {
+ for (const listener of listeners) listener();
+ };
+
+ const deleteUpload = (id: string) => {
+ finishedUploadIds.delete(id);
+ uploadNodeKeys.delete(id);
+ return uploads.delete(id);
+ };
+
+ return {
+ bindNode: (nodeKey, fileName) => {
+ if (nodeUploadIds.has(nodeKey)) return;
+
+ nodeFileNames.set(nodeKey, fileName);
+
+ const upload =
+ [...uploads.values()].find((item) => uploadNodeKeys.get(item.id) === nodeKey) ??
+ [...uploads.values()].find(
+ (item) => item.file.name === fileName && !uploadNodeKeys.has(item.id),
+ );
+
+ if (upload) {
+ nodeUploadIds.set(nodeKey, upload.id);
+ uploadNodeKeys.set(upload.id, nodeKey);
+ emit();
+ }
+ },
+ finish: (id) => {
+ if (!uploads.has(id)) return;
+
+ finishedUploadIds.add(id);
+ const isBound = [...nodeUploadIds.values()].includes(id);
+ if (isBound || !deleteUpload(id)) return;
+ emit();
+ },
+ getSnapshot: (nodeKey) => {
+ const uploadId = nodeUploadIds.get(nodeKey);
+ return uploadId ? uploads.get(uploadId) : undefined;
+ },
+ releaseNode: (nodeKey) => {
+ nodeFileNames.delete(nodeKey);
+ const uploadId = nodeUploadIds.get(nodeKey);
+ if (!uploadId) return;
+
+ nodeUploadIds.delete(nodeKey);
+ if (finishedUploadIds.has(uploadId)) deleteUpload(uploadId);
+ emit();
+ },
+ start: (file) => {
+ const id = String(++nextId);
+ uploads.set(id, { file, id, status: 'pending' });
+
+ const pendingNode = [...nodeFileNames.entries()].find(
+ ([nodeKey, fileName]) => fileName === file.name && !nodeUploadIds.has(nodeKey),
+ );
+ if (pendingNode) {
+ nodeUploadIds.set(pendingNode[0], id);
+ uploadNodeKeys.set(id, pendingNode[0]);
+ }
+
+ emit();
+ return id;
+ },
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ update: (id, status, uploadState) => {
+ const upload = uploads.get(id);
+ if (!upload) return;
+
+ uploads.set(id, { ...upload, status, uploadState });
+ emit();
+ },
+ };
+};
diff --git a/src/features/EditorCanvas/useImageUpload.ts b/src/features/EditorCanvas/useImageUpload.ts
index 0318825e313..ed8aa0cf38c 100644
--- a/src/features/EditorCanvas/useImageUpload.ts
+++ b/src/features/EditorCanvas/useImageUpload.ts
@@ -1,9 +1,20 @@
import { useCallback } from 'react';
import { useFileStore } from '@/store/file';
+import type { FileUploadState, FileUploadStatus } from '@/types/files/upload';
import { registerAttachment } from './attachmentRegistry';
+export type EditorAttachmentUploadProgress = (
+ status: FileUploadStatus,
+ uploadState?: FileUploadState,
+) => void;
+
+export type EditorAttachmentUpload = (
+ file: File,
+ onProgress?: EditorAttachmentUploadProgress,
+) => Promise<{ url: string }>;
+
/**
* Upload handler compatible with `@lobehub/editor`'s `ReactImagePlugin` /
* `ReactFilePlugin` `handleUpload` signature. Side effect: registers the
@@ -14,9 +25,13 @@ const useEditorAttachmentUpload = (skipCheckFileType: boolean) => {
const uploadWithProgress = useFileStore((s) => s.uploadWithProgress);
return useCallback(
- async (file: File): Promise<{ url: string }> => {
+ async (file: File, onProgress?: EditorAttachmentUploadProgress): Promise<{ url: string }> => {
const result = await uploadWithProgress({
file,
+ onStatusUpdate: (data) => {
+ if (data.type !== 'updateFile' || !data.value.status) return;
+ onProgress?.(data.value.status, data.value.uploadState);
+ },
skipCheckFileType,
source: 'page-editor',
});