From 97602cf734d752c6be10058eaa78be82bc41d554 Mon Sep 17 00:00:00 2001 From: CommaBot Date: Tue, 24 Nov 2026 18:04:36 +0800 Subject: [PATCH] fix(core): report files skipped during import (#15892) Markdown, HTML and Word imports silently dropped a file when it could not be read or converted: the per-file loop only kept files that returned a doc id, and the file picker's snapshot step dropped unreadable files with a `console.error`. The dialog then reported "Import completed". This change: - moves snapshotting of picked files into the importer (`snapshotReadableFiles`, already used by the Obsidian import), which records unreadable files as warnings; the picker no longer has a `snapshot` option - records files the converter returned no doc for as `skipped_doc` warnings - shows "Import completed with warnings" and the list of warnings instead of the success message when there are any - sets `sourcePath` on Markdown zip docs so skipped entries are named by path instead of a generated id fix #15718 ## Summary by CodeRabbit * **New Features** * Import status now reports when files are skipped, unreadable, or only partially imported. * Imported Markdown documents retain their source paths within the archive. * File and directory pickers can use the standard browser picker instead of the File System Access API. * **Bug Fixes** * Importing multiple files now handles unreadable files and files that cannot be converted without interrupting the remaining imports. Co-authored-by: DarkSky --- .../affine/shared/src/utils/file/filesys.ts | 85 +++-------------- .../linked-doc/src/transformers/markdown.ts | 1 + .../dialogs/import/file-import.spec.ts | 47 ++++++++++ .../src/desktop/dialogs/import/file-import.ts | 42 +++++++++ .../core/src/desktop/dialogs/import/index.tsx | 94 +++++++++---------- .../src/modules/import/services/service.ts | 21 +---- packages/frontend/i18n/src/i18n.gen.ts | 8 ++ packages/frontend/i18n/src/resources/en.json | 2 + 8 files changed, 158 insertions(+), 142 deletions(-) create mode 100644 packages/frontend/core/src/desktop/dialogs/import/file-import.spec.ts create mode 100644 packages/frontend/core/src/desktop/dialogs/import/file-import.ts diff --git a/blocksuite/affine/shared/src/utils/file/filesys.ts b/blocksuite/affine/shared/src/utils/file/filesys.ts index 47b35ce20c..146080ca2c 100644 --- a/blocksuite/affine/shared/src/utils/file/filesys.ts +++ b/blocksuite/affine/shared/src/utils/file/filesys.ts @@ -168,7 +168,6 @@ type AcceptTypes = type OpenFileOptions = { fileSystemAccess?: boolean; - snapshot?: boolean; }; function copyToArrayBuffer(bytes: Uint8Array) { @@ -211,21 +210,6 @@ export async function snapshotFile(file: File, relativePath?: string) { return snapshot; } -export async function snapshotFiles(files: File[]) { - const results = await Promise.allSettled( - files.map(file => snapshotFile(file)) - ); - const snapshots: File[] = []; - for (const result of results) { - if (result.status === 'fulfilled') { - snapshots.push(result.value); - } else { - console.error('Failed to snapshot file', result.reason); - } - } - return snapshots; -} - function canUseFileSystemAccessAPI( api: 'showOpenFilePicker' | 'showDirectoryPicker' ) { @@ -241,10 +225,6 @@ function canUseFileSystemAccessAPI( ); } -function isAbortError(error: unknown) { - return error instanceof Error && error.name === 'AbortError'; -} - function isNotReadableError(error: unknown) { return error instanceof Error && error.name === 'NotReadableError'; } @@ -274,19 +254,15 @@ export async function openFilesWith( // Show the file picker, optionally allowing multiple files. const handles = await window.showOpenFilePicker(pickerOpts); - const files = await Promise.all(handles.map(handle => handle.getFile())); - return options?.snapshot ? await snapshotFiles(files) : files; + return await Promise.all(handles.map(handle => handle.getFile())); } catch (err) { - if (options?.snapshot && !isAbortError(err)) { - throw err; - } console.error(err); return null; } } // Fallback if the File System Access API is not supported. - return new Promise((resolve, reject) => { + return new Promise(resolve => { // Append a new `` and hide it. const input = document.createElement('input'); input.classList.add('affine-upload-input'); @@ -303,21 +279,9 @@ export async function openFilesWith( document.body.append(input); // The `change` event fires when the user interacts with the dialog. input.addEventListener('change', () => { - const files = input.files ? Array.from(input.files) : null; - const finish = (result: File[] | null) => { - // Remove the `` again from the DOM. - input.remove(); - resolve(result); - }; - - if (files && options?.snapshot) { - snapshotFiles(files).then(finish, error => { - input.remove(); - reject(error); - }); - } else { - finish(files); - } + // Remove the `` again from the DOM. + input.remove(); + resolve(input.files ? Array.from(input.files) : null); }); // The `cancel` event fires when the user cancels the dialog. input.addEventListener('cancel', () => { @@ -359,19 +323,11 @@ export async function openDirectory( const fileHandle = handle as FileSystemFileHandle; if (fileHandle.getFile) { const file = await fileHandle.getFile(); - if (options?.snapshot) { - try { - files.push(await snapshotFile(file, relativePath)); - } catch (error) { - console.error('Failed to snapshot file', relativePath, error); - } - } else { - Object.defineProperty(file, 'webkitRelativePath', { - value: relativePath, - writable: false, - }); - files.push(file); - } + Object.defineProperty(file, 'webkitRelativePath', { + value: relativePath, + writable: false, + }); + files.push(file); } } else if (handle.kind === 'directory') { await readDirectory( @@ -385,15 +341,12 @@ export async function openDirectory( await readDirectory(dirHandle, ''); return files; } catch (err) { - if (options?.snapshot && !isAbortError(err)) { - throw err; - } console.error(err); return null; } } - return new Promise((resolve, reject) => { + return new Promise(resolve => { const input = document.createElement('input'); input.classList.add('affine-upload-input'); input.style.display = 'none'; @@ -405,20 +358,8 @@ export async function openDirectory( document.body.append(input); input.addEventListener('change', () => { - const files = input.files ? Array.from(input.files) : null; - const finish = (result: File[] | null) => { - input.remove(); - resolve(result); - }; - - if (files && options?.snapshot) { - snapshotFiles(files).then(finish, error => { - input.remove(); - reject(error); - }); - } else { - finish(files); - } + input.remove(); + resolve(input.files ? Array.from(input.files) : null); }); input.addEventListener('cancel', () => { diff --git a/blocksuite/affine/widgets/linked-doc/src/transformers/markdown.ts b/blocksuite/affine/widgets/linked-doc/src/transformers/markdown.ts index 38f6e25257..d1c4589b6e 100644 --- a/blocksuite/affine/widgets/linked-doc/src/transformers/markdown.ts +++ b/blocksuite/affine/widgets/linked-doc/src/transformers/markdown.ts @@ -836,6 +836,7 @@ async function planMarkdownZipInternal({ applySnapshotTitle(snapshot, preferredTitle); docs.push({ id: pageId, + sourcePath: fullPath, snapshot, meta: { ...meta, diff --git a/packages/frontend/core/src/desktop/dialogs/import/file-import.spec.ts b/packages/frontend/core/src/desktop/dialogs/import/file-import.spec.ts new file mode 100644 index 0000000000..1e560a6715 --- /dev/null +++ b/packages/frontend/core/src/desktop/dialogs/import/file-import.spec.ts @@ -0,0 +1,47 @@ +import { describe, expect, test } from 'vitest'; + +import { importFilesAsDocs } from './file-import'; + +function unreadableFile(name: string) { + const file = new File(['# unreadable'], name); + Object.defineProperty(file, 'arrayBuffer', { + value: () => + Promise.reject(new DOMException('Permission denied', 'SecurityError')), + }); + return file; +} + +describe('importFilesAsDocs', () => { + test.each([ + { + name: 'imports every converted file without warnings', + files: [new File(['# a'], 'a.md'), new File(['# b'], 'b.md')], + failingNames: [], + docIds: ['doc:a.md', 'doc:b.md'], + warnings: [], + }, + { + name: 'reports files the importer could not convert', + files: [new File(['# a'], 'a.md'), new File(['# b'], 'b.md')], + failingNames: ['b.md'], + docIds: ['doc:a.md'], + warnings: [{ code: 'skipped_doc', sourcePath: 'b.md' }], + }, + { + name: 'reports files that cannot be read', + files: [new File(['# a'], 'a.md'), unreadableFile('b.md')], + failingNames: [], + docIds: ['doc:a.md'], + warnings: [{ code: 'file-unreadable', sourcePath: 'b.md' }], + }, + ])('$name', async ({ files, failingNames, docIds, warnings }) => { + const result = await importFilesAsDocs(files, async file => + failingNames.includes(file.name) ? undefined : `doc:${file.name}` + ); + + expect(result.docIds).toEqual(docIds); + expect(result.warnings).toEqual( + warnings.map(warning => expect.objectContaining(warning)) + ); + }); +}); diff --git a/packages/frontend/core/src/desktop/dialogs/import/file-import.ts b/packages/frontend/core/src/desktop/dialogs/import/file-import.ts new file mode 100644 index 0000000000..c9daa8562f --- /dev/null +++ b/packages/frontend/core/src/desktop/dialogs/import/file-import.ts @@ -0,0 +1,42 @@ +import { snapshotFile } from '@blocksuite/affine/shared/utils'; +import type { ImportWarning } from '@blocksuite/affine/widgets/linked-doc'; + +export async function snapshotReadableFiles(files: File[]) { + const snapshots: File[] = []; + const warnings: ImportWarning[] = []; + for (const file of files) { + try { + snapshots.push(await snapshotFile(file)); + } catch (error) { + const sourcePath = file.webkitRelativePath || file.name; + const reason = error instanceof Error ? error.message : String(error); + warnings.push({ + code: 'file-unreadable', + message: `Skipped unreadable file: ${sourcePath}. ${reason}`, + sourcePath, + }); + } + } + return { files: snapshots, warnings }; +} + +export async function importFilesAsDocs( + files: File[], + importFile: (file: File) => Promise +) { + const { files: readableFiles, warnings } = await snapshotReadableFiles(files); + const docIds: string[] = []; + for (const file of readableFiles) { + const docId = await importFile(file); + if (docId) { + docIds.push(docId); + } else { + warnings.push({ + code: 'skipped_doc', + message: `Skipped ${file.name}: the file could not be converted to a document`, + sourcePath: file.name, + }); + } + } + return { docIds, warnings }; +} diff --git a/packages/frontend/core/src/desktop/dialogs/import/index.tsx b/packages/frontend/core/src/desktop/dialogs/import/index.tsx index f97b91b6d6..3a452c89dd 100644 --- a/packages/frontend/core/src/desktop/dialogs/import/index.tsx +++ b/packages/frontend/core/src/desktop/dialogs/import/index.tsx @@ -25,7 +25,11 @@ import { import { DebugLogger } from '@affine/debug'; import { useI18n } from '@affine/i18n'; import track from '@affine/track'; -import { openDirectory, openFilesWith } from '@blocksuite/affine/shared/utils'; +import { + openDirectory, + openFilesWith, + snapshotFile, +} from '@blocksuite/affine/shared/utils'; import type { Workspace } from '@blocksuite/affine/store'; import { DocxTransformer, @@ -56,15 +60,11 @@ import { useState, } from 'react'; +import { importFilesAsDocs } from './file-import'; import * as style from './styles.css'; const logger = new DebugLogger('import'); -function shouldSnapshotPickedFiles(type: ImportType, acceptType: AcceptType) { - if (acceptType === 'Directory' || acceptType === 'Skip') return false; - return !['markdownZip', 'notion', 'bear', 'oneNote'].includes(type); -} - type ImportType = | 'markdown' | 'markdownZip' @@ -292,22 +292,17 @@ const importConfigs: Record = { markdown: { fileOptions: { acceptType: 'Markdown', multiple: true }, importFunction: async ({ docCollection, files }) => { - const docIds: string[] = []; - for (const file of files) { + return importFilesAsDocs(files, async file => { const text = await file.text(); const fileName = file.name.split('.').slice(0, -1).join('.'); - const docId = await MarkdownTransformer.importMarkdownToDoc({ + return MarkdownTransformer.importMarkdownToDoc({ collection: docCollection, schema: getAFFiNEWorkspaceSchema(), markdown: text, fileName, extensions: getStoreManager().config.init().value.get('store'), }); - if (docId) docIds.push(docId); - } - return { - docIds, - }; + }); }, }, markdownZip: { @@ -326,22 +321,17 @@ const importConfigs: Record = { html: { fileOptions: { acceptType: 'Html', multiple: true }, importFunction: async ({ docCollection, files }) => { - const docIds: string[] = []; - for (const file of files) { + return importFilesAsDocs(files, async file => { const text = await file.text(); const fileName = file.name.split('.').slice(0, -1).join('.'); - const docId = await HtmlTransformer.importHTMLToDoc({ + return HtmlTransformer.importHTMLToDoc({ collection: docCollection, schema: getAFFiNEWorkspaceSchema(), extensions: getStoreManager().config.init().value.get('store'), html: text, fileName, }); - if (docId) docIds.push(docId); - } - return { - docIds, - }; + }); }, }, notion: { @@ -390,17 +380,14 @@ const importConfigs: Record = { docx: { fileOptions: { acceptType: 'Docx', multiple: false }, importFunction: async ({ docCollection, files }) => { - const docIds: string[] = []; - for (const file of files) { - const docId = await DocxTransformer.importDocx({ + return importFilesAsDocs(files, file => + DocxTransformer.importDocx({ collection: docCollection, schema: getAFFiNEWorkspaceSchema(), imported: file, extensions: getStoreManager().config.init().value.get('store'), - }); - if (docId) docIds.push(docId); - } - return { docIds }; + }) + ); }, }, snapshot: { @@ -414,7 +401,7 @@ const importConfigs: Record = { await ZipTransformer.importDocs( docCollection, getAFFiNEWorkspaceSchema(), - file + await snapshotFile(file) ) ) .filter((doc): doc is NonNullable => doc !== undefined) @@ -577,27 +564,35 @@ const SuccessStatus = ({ return ( <>
- {t['com.affine.import.status.success.title']()} + {warnings.length + ? t['com.affine.import.status.warning.title']() + : t['com.affine.import.status.success.title']()}
-

- {t['com.affine.import.status.success.message']()}{' '} - - Discord - - . -

{warnings.length ? ( -
- {warnings.map((warning, index) => ( -
{warning}
- ))} -
- ) : null} + <> +

+ {t['com.affine.import.status.warning.message']()} +

+
+ {warnings.map((warning, index) => ( +
{warning}
+ ))} +
+ + ) : ( +

+ {t['com.affine.import.status.success.message']()}{' '} + + Discord + + . +

+ )}