Files
XCDesktop/electron/services/htmlImport.ts
2026-03-08 01:34:54 +08:00

70 lines
1.9 KiB
TypeScript

import { dialog, BrowserWindow } from 'electron'
import path from 'path'
import fs from 'fs'
import log from 'electron-log'
export interface HtmlImportResult {
success: boolean
canceled?: boolean
error?: string
htmlPath?: string
htmlDir?: string
htmlFileName?: string
assetsDirName?: string
assetsFiles?: string[]
}
export const selectHtmlFile = async (win: BrowserWindow | null): Promise<HtmlImportResult> => {
if (!win) return { success: false, error: 'No window found' }
try {
const { filePaths, canceled } = await dialog.showOpenDialog(win, {
title: '选择 HTML 文件',
filters: [
{ name: 'HTML Files', extensions: ['html', 'htm'] }
],
properties: ['openFile']
})
if (canceled || filePaths.length === 0) {
return { success: false, canceled: true }
}
const htmlPath = filePaths[0]
const htmlDir = path.dirname(htmlPath)
const htmlFileName = path.basename(htmlPath, path.extname(htmlPath))
const assetsDirName = `${htmlFileName}_files`
const assetsDirPath = path.join(htmlDir, assetsDirName)
const assetsFiles: string[] = []
if (fs.existsSync(assetsDirPath)) {
const collectFiles = (dir: string, baseDir: string) => {
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
collectFiles(fullPath, baseDir)
} else {
const relPath = path.relative(baseDir, fullPath)
assetsFiles.push(relPath)
}
}
}
collectFiles(assetsDirPath, assetsDirPath)
}
return {
success: true,
htmlPath,
htmlDir,
htmlFileName,
assetsDirName,
assetsFiles
}
} catch (error: any) {
log.error('Select HTML file failed:', error)
return { success: false, error: error.message }
}
}