Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ujia
/
uj-admin
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 17e654c7
authored
Nov 20, 2026
by
liimin
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
优化下载中心下载逻辑
1 parent
4109f976
Pipeline
#575
for
17e654c7
failed
in 0 seconds
Changes
19
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
19 changed files
with
501 additions
and
67 deletions
apps/web/shell/package.json
apps/web/subapps/usedcar/package.json
apps/web/subapps/usedcar/src/pages/Condition/index.tsx
apps/web/subapps/usedcar/src/pages/CustomerGroup/LiveCodesTab.tsx
apps/web/subapps/usedcar/src/pages/Operation/ContractDetail.tsx
apps/web/subapps/usedcar/src/pages/Reports/index.tsx
packages/contracts/src/download-center.ts
packages/download-center/src/DownloadCenterButton.tsx
packages/download-center/src/DownloadCenterProvider.tsx
packages/download-center/src/TaskPreviewModal.tsx
packages/download-center/src/deliver.ts
packages/download-center/src/engine.ts
packages/download-center/src/handlers/asyncExport.ts
packages/download-center/src/handlers/simple.ts
packages/download-center/src/handlers/stream.ts
packages/download-center/src/index.ts
packages/download-center/src/store.ts
packages/download-center/src/types.ts
packages/platform-sdk/src/downloadCenter.ts
apps/web/shell/package.json
View file @
17e654c
{
{
"name"
:
"@uj/web-shell"
,
"name"
:
"@uj/web-shell"
,
"version"
:
"0.0.1
3
"
,
"version"
:
"0.0.1
4
"
,
"private"
:
true
,
"private"
:
true
,
"type"
:
"module"
,
"type"
:
"module"
,
"scripts"
:
{
"scripts"
:
{
...
...
apps/web/subapps/usedcar/package.json
View file @
17e654c
{
{
"name"
:
"@uj/web-usedcar"
,
"name"
:
"@uj/web-usedcar"
,
"version"
:
"0.0.
9
"
,
"version"
:
"0.0.
10
"
,
"private"
:
true
,
"private"
:
true
,
"type"
:
"module"
,
"type"
:
"module"
,
"scripts"
:
{
"scripts"
:
{
...
...
apps/web/subapps/usedcar/src/pages/Condition/index.tsx
View file @
17e654c
import { useMemo, useState } from 'react';
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';
import { UAlert, UButton, UCard, UResult, useUMessage } from '@uj/ui';
import { UAlert, UButton, UCard, UResult, useUMessage } from '@uj/ui';
import { openExternal } from '@uj/platform-sdk';
import {
import {
DataTable,
DataTable,
PageShell,
PageShell,
...
@@ -140,10 +141,8 @@ export default function Condition() {
...
@@ -140,10 +141,8 @@ export default function Condition() {
return;
return;
}
}
const join = baseUrl.includes('?') ? '&' : '?';
const join = baseUrl.includes('?') ? '&' : '?';
window.open
(
openExternal
(
`${baseUrl}${join}source=1&carConditionCode=${encodeURIComponent(String(row.carConditionCode ?? ''))}`,
`${baseUrl}${join}source=1&carConditionCode=${encodeURIComponent(String(row.carConditionCode ?? ''))}`,
'_blank',
'noopener,noreferrer',
);
);
} catch (error) {
} catch (error) {
message.error(errorDetail(error));
message.error(errorDetail(error));
...
...
apps/web/subapps/usedcar/src/pages/CustomerGroup/LiveCodesTab.tsx
View file @
17e654c
...
@@ -68,6 +68,9 @@ export default function LiveCodesTab() {
...
@@ -68,6 +68,9 @@ export default function LiveCodesTab() {
source: 'usedcar',
source: 'usedcar',
sourceLabel: '二手车管理 / 一客一群',
sourceLabel: '二手车管理 / 一客一群',
label: `${text(row.liveName)}二维码`,
label: `${text(row.liveName)}二维码`,
// 直链末端是预签名路径(qrcode_xxx_static_时间戳.png),不带可读文件名。
// 这里给业务文件名,下载中心和浏览器保存对话框才显示用户认识的名字。
fileName: `${text(row.liveName)}二维码.png`,
url: row.defaultQrCodeUrl,
url: row.defaultQrCodeUrl,
silent: true,
silent: true,
}),
}),
...
...
apps/web/subapps/usedcar/src/pages/Operation/ContractDetail.tsx
View file @
17e654c
...
@@ -241,6 +241,8 @@ export default function ContractDetail({ params }: { params: PageParams }) {
...
@@ -241,6 +241,8 @@ export default function ContractDetail({ params }: { params: PageParams }) {
sourceLabel: '二手车管理 / 运营管理 / 合同内容',
sourceLabel: '二手车管理 / 运营管理 / 合同内容',
label: `${String(item.label ?? '合同资料')} · 图片 ${urlIndex + 1}`,
label: `${String(item.label ?? '合同资料')} · 图片 ${urlIndex + 1}`,
url,
url,
// 点缩略图是要看原图,不是要把文件存到磁盘。
preview: true,
silent: true,
silent: true,
dedupeKey: `usedcar-contract-field-${url}`,
dedupeKey: `usedcar-contract-field-${url}`,
})
})
...
@@ -257,6 +259,7 @@ export default function ContractDetail({ params }: { params: PageParams }) {
...
@@ -257,6 +259,7 @@ export default function ContractDetail({ params }: { params: PageParams }) {
sourceLabel: '二手车管理 / 运营管理 / 合同内容',
sourceLabel: '二手车管理 / 运营管理 / 合同内容',
label: `${String(item.label ?? '合同资料')} · 视频 ${urlIndex + 1}`,
label: `${String(item.label ?? '合同资料')} · 视频 ${urlIndex + 1}`,
url,
url,
preview: true,
silent: true,
silent: true,
dedupeKey: `usedcar-contract-field-${url}`,
dedupeKey: `usedcar-contract-field-${url}`,
})
})
...
...
apps/web/subapps/usedcar/src/pages/Reports/index.tsx
View file @
17e654c
...
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
...
@@ -2,7 +2,7 @@ import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useQuery } from '@tanstack/react-query';
import type { Dayjs } from 'dayjs';
import type { Dayjs } from 'dayjs';
import { UAlert, UButton, UCard, UImage, UResult, UTag } from '@uj/ui';
import { UAlert, UButton, UCard, UImage, UResult, UTag } from '@uj/ui';
import { downloadCenter } from '@uj/platform-sdk';
import { downloadCenter
, openExternal
} from '@uj/platform-sdk';
import {
import {
DataTable,
DataTable,
PageShell,
PageShell,
...
@@ -121,7 +121,7 @@ export default function Reports() {
...
@@ -121,7 +121,7 @@ export default function Reports() {
permission: UC.REPORT_DETAIL,
permission: UC.REPORT_DETAIL,
visible: (r) => String(r.status) === '1' && Boolean(r.reportUrl),
visible: (r) => String(r.status) === '1' && Boolean(r.reportUrl),
onClick: (r) => {
onClick: (r) => {
if (r.reportUrl)
window.open(r.reportUrl, '_blank', 'noopener,noreferrer'
);
if (r.reportUrl)
openExternal(r.reportUrl
);
},
},
},
},
];
];
...
...
packages/contracts/src/download-center.ts
View file @
17e654c
...
@@ -151,6 +151,15 @@ export const DOWNLOAD_CENTER_REGISTER_EVENT = 'uj:download-center:register';
...
@@ -151,6 +151,15 @@ export const DOWNLOAD_CENTER_REGISTER_EVENT = 'uj:download-center:register';
export
const
DOWNLOAD_CENTER_CANCEL_EVENT
=
'uj:download-center:cancel'
;
export
const
DOWNLOAD_CENTER_CANCEL_EVENT
=
'uj:download-center:cancel'
;
/**
/**
* 子应用 -> 主壳:打开一个可见的外部标签页(payload 为 URL)。
*
* 用途:非线性下载的外部页面跳转(报告、AI 分析页)也统一由主壳开标签,
* 子应用 iframe 内直接 window.open 容易被弹窗拦截,且行为与主壳预览不一致。
* 与下载任务无关:这里只开标签,不登记任务、不落盘。
*/
export
const
OPEN_EXTERNAL_EVENT
=
'uj:open-external'
;
/**
* 子应用 -> 主壳:注册一个请求通道(供下载任务的 handler 按 channel 名选用)。
* 子应用 -> 主壳:注册一个请求通道(供下载任务的 handler 按 channel 名选用)。
*
*
* payload: `{ name: string; request: RemoteRequestFn }`。函数经 wujie bus 引用传递
* payload: `{ name: string; request: RemoteRequestFn }`。函数经 wujie bus 引用传递
...
...
packages/download-center/src/DownloadCenterButton.tsx
View file @
17e654c
...
@@ -8,7 +8,8 @@ import {
...
@@ -8,7 +8,8 @@ import {
InfoCircleFilled,
InfoCircleFilled,
} from '@ant-design/icons';
} from '@ant-design/icons';
import { useDownloadCenterStore } from './store';
import { useDownloadCenterStore } from './store';
import { cancelTask, removeTask, redownload } from './engine';
import { cancelTask, removeTask, redownload, saveTaskAs, hasTaskFile } from './engine';
import { TaskPreviewModal } from './TaskPreviewModal';
import type { DownloadTaskStatus, DownloadTask } from './types';
import type { DownloadTaskStatus, DownloadTask } from './types';
type TaskFilter = 'all' | 'active' | 'success' | 'failed';
type TaskFilter = 'all' | 'active' | 'success' | 'failed';
...
@@ -149,12 +150,22 @@ function displaySource(t: DownloadTask): string {
...
@@ -149,12 +150,22 @@ function displaySource(t: DownloadTask): string {
return t.sourceLabel ?? SOURCE_LABELS[t.source] ?? t.source;
return t.sourceLabel ?? SOURCE_LABELS[t.source] ?? t.source;
}
}
/**
* 跨域无 CORS 的直链拿不到字节,只能打开可见标签让用户右键另存。
* 这类任务的 stage 由 deliverRemoteFile 写成「未自动保存…」,面板据此标「待另存」,
* 不能再顶着「可下载」让用户去浏览器下载记录里白找。
*/
function needsManualSave(t: DownloadTask): boolean {
return t.status === 'done' && /未自动保存|点击「另存为」/.test(t.stage ?? '');
}
/** 主壳 Header 右侧的全系统下载中心入口。 */
/** 主壳 Header 右侧的全系统下载中心入口。 */
export function DownloadCenterButton() {
export function DownloadCenterButton() {
const tasks = useDownloadCenterStore((s) => s.tasks);
const tasks = useDownloadCenterStore((s) => s.tasks);
const clearFinished = useDownloadCenterStore((s) => s.clearFinished);
const clearFinished = useDownloadCenterStore((s) => s.clearFinished);
const notice = useDownloadCenterStore((s) => s.notice);
const notice = useDownloadCenterStore((s) => s.notice);
const clearNotice = useDownloadCenterStore((s) => s.clearNotice);
const clearNotice = useDownloadCenterStore((s) => s.clearNotice);
const showPreview = useDownloadCenterStore((s) => s.showPreview);
const [filter, setFilter] = useState<TaskFilter>('all');
const [filter, setFilter] = useState<TaskFilter>('all');
const [copiedId, setCopiedId] = useState<string | null>(null);
const [copiedId, setCopiedId] = useState<string | null>(null);
const [showHelp, setShowHelp] = useState(false);
const [showHelp, setShowHelp] = useState(false);
...
@@ -179,6 +190,7 @@ export function DownloadCenterButton() {
...
@@ -179,6 +190,7 @@ export function DownloadCenterButton() {
const successCount = tasks.filter((t) => t.status === 'done').length;
const successCount = tasks.filter((t) => t.status === 'done').length;
const failedCount = tasks.filter((t) => t.status === 'failed').length;
const failedCount = tasks.filter((t) => t.status === 'failed').length;
const hasFinished = tasks.some((t) => FINISHED.has(t.status));
const hasFinished = tasks.some((t) => FINISHED.has(t.status));
const manualSaveCount = tasks.filter(needsManualSave).length;
const filteredTasks = useMemo(() => {
const filteredTasks = useMemo(() => {
if (filter === 'active') return tasks.filter((t) => IN_FLIGHT.has(t.status));
if (filter === 'active') return tasks.filter((t) => IN_FLIGHT.has(t.status));
...
@@ -235,12 +247,17 @@ export function DownloadCenterButton() {
...
@@ -235,12 +247,17 @@ export function DownloadCenterButton() {
/>
/>
</div>
</div>
{
successCount > 0
&& (
{
(successCount > 0 || manualSaveCount > 0)
&& (
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 8, lineHeight: 1.6 }}>
<div style={{ fontSize: 11, color: '#8c8c8c', marginTop: 8, lineHeight: 1.6 }}>
{/* {manualSaveCount > 0 && (
<div style={{ color: '#cf1322' }}>
有 {manualSaveCount} 个任务未自动保存(标记「待另存」),请点「预览」后在画面上右键另存为。
</div>
)} */}
<div>
<div>
文件已自动下载;找不到
可按
已自动下载的文件
可按
<strong style={{ color: '#cf1322' }}> {DOWNLOAD_MANAGER_SHORTCUT} </strong>
<strong style={{ color: '#cf1322' }}> {DOWNLOAD_MANAGER_SHORTCUT} </strong>
在浏览器下载管理查看。
在浏览器下载管理查看
;也可在下方任务里点「预览 / 另存为」
。
<a
<a
onClick={() => setShowHelp((v) => !v)}
onClick={() => setShowHelp((v) => !v)}
style={{ marginLeft: 6, cursor: 'pointer', whiteSpace: 'nowrap' }}
style={{ marginLeft: 6, cursor: 'pointer', whiteSpace: 'nowrap' }}
...
@@ -251,7 +268,8 @@ export function DownloadCenterButton() {
...
@@ -251,7 +268,8 @@ export function DownloadCenterButton() {
{showHelp && (
{showHelp && (
<div style={{ marginTop: 4 }}>
<div style={{ marginTop: 4 }}>
{[
{[
'下载中心无法直接查看或获取已下载的文件。',
'带「预览 / 保存」按钮的任务可直接在面板查看或保存到本地。',
'跨域直链无法读取文件内容,面板内可直接预览,请在画面上右键另存为。',
'部分浏览器插件可能占用该快捷键,无响应可从浏览器菜单进入下载管理。',
'部分浏览器插件可能占用该快捷键,无响应可从浏览器菜单进入下载管理。',
'链接可能过期,仅作备用。',
'链接可能过期,仅作备用。',
'删除记录或「清除已完成」不会删除已下载到本地的文件。',
'删除记录或「清除已完成」不会删除已下载到本地的文件。',
...
@@ -293,8 +311,8 @@ export function DownloadCenterButton() {
...
@@ -293,8 +311,8 @@ export function DownloadCenterButton() {
>
>
{t.label}
{t.label}
</span>
</span>
<Tag color={meta.color} style={{ marginInlineEnd: 0 }}>
<Tag color={
needsManualSave(t) ? 'warning' :
meta.color} style={{ marginInlineEnd: 0 }}>
{meta.text}
{
needsManualSave(t) ? '待另存' :
meta.text}
</Tag>
</Tag>
</div>
</div>
...
@@ -328,6 +346,27 @@ export function DownloadCenterButton() {
...
@@ -328,6 +346,27 @@ export function DownloadCenterButton() {
)}
)}
{t.status === 'done' && (
{t.status === 'done' && (
<>
<>
{(hasTaskFile(t.id) || t.fileUrl) && (
<Button
type="link"
size="small"
style={{ padding: 0 }}
onClick={(e) => {
e.stopPropagation();
// 先收起面板:Popover(z-index 1030) 会盖住预览 Modal,
// 且留着面板遮挡视线。Modal 自身 zIndex 1200 也高于浮窗 1050。
setPanelOpen(false);
showPreview(t.id);
}}
>
预览
</Button>
)}
{hasTaskFile(t.id) && (
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); saveTaskAs(t.id); }}>
保存
</Button>
)}
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); redownload(t); }}>
<Button type="link" size="small" style={{ padding: 0 }} onClick={(e) => { e.stopPropagation(); redownload(t); }}>
再次下载
再次下载
</Button>
</Button>
...
@@ -401,6 +440,8 @@ export function DownloadCenterButton() {
...
@@ -401,6 +440,8 @@ export function DownloadCenterButton() {
onClick={openPanelFromToast}
onClick={openPanelFromToast}
/>
/>
)}
)}
<TaskPreviewModal />
</span>
</span>
);
);
}
}
packages/download-center/src/DownloadCenterProvider.tsx
View file @
17e654c
...
@@ -5,6 +5,7 @@ import {
...
@@ -5,6 +5,7 @@ import {
DOWNLOAD_CENTER_REGISTER_EVENT,
DOWNLOAD_CENTER_REGISTER_EVENT,
DOWNLOAD_CENTER_CANCEL_EVENT,
DOWNLOAD_CENTER_CANCEL_EVENT,
DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT,
DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT,
OPEN_EXTERNAL_EVENT,
} from '@uj/contracts';
} from '@uj/contracts';
import {
import {
configureDownloadCenter,
configureDownloadCenter,
...
@@ -14,6 +15,7 @@ import {
...
@@ -14,6 +15,7 @@ import {
cancelTask,
cancelTask,
} from './engine';
} from './engine';
import { registerDownload } from './register';
import { registerDownload } from './register';
import { openPreview } from './deliver';
import { useDownloadCenterStore } from './store';
import { useDownloadCenterStore } from './store';
import type { DownloadTask } from './types';
import type { DownloadTask } from './types';
...
@@ -55,9 +57,14 @@ export function DownloadCenterProvider({
...
@@ -55,9 +57,14 @@ export function DownloadCenterProvider({
registerChannel(payload.name, payload.request as RemoteRequestFn);
registerChannel(payload.name, payload.request as RemoteRequestFn);
}
}
};
};
const onOpenExternal = (...args: unknown[]) => {
const url = args[0];
if (typeof url === 'string' && url) openPreview(url);
};
bus.$on(DOWNLOAD_CENTER_REGISTER_EVENT, onRegister);
bus.$on(DOWNLOAD_CENTER_REGISTER_EVENT, onRegister);
bus.$on(DOWNLOAD_CENTER_CANCEL_EVENT, onCancel);
bus.$on(DOWNLOAD_CENTER_CANCEL_EVENT, onCancel);
bus.$on(DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT, onRegisterChannel);
bus.$on(DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT, onRegisterChannel);
bus.$on(OPEN_EXTERNAL_EVENT, onOpenExternal);
// 提示去重:按「任务的第几次尝试」去重,而不是按任务 id 永久去重。
// 提示去重:按「任务的第几次尝试」去重,而不是按任务 id 永久去重。
//
//
...
@@ -102,6 +109,12 @@ export function DownloadCenterProvider({
...
@@ -102,6 +109,12 @@ export function DownloadCenterProvider({
notifiedAt.set(t.id, t.updatedAt);
notifiedAt.set(t.id, t.updatedAt);
if (t.status === 'done') {
if (t.status === 'done') {
// preview:true 的任务(合同缩略图点开看原图等)完成后直接弹 Modal。
// silent 只压浮窗提示,不能压掉用户主动要求的预览。
if ((t.input.payload as { preview?: unknown } | null)?.preview === true) {
// 避免在 store.subscribe 回调里同步再 set,交给微任务执行。
queueMicrotask(() => useDownloadCenterStore.getState().showPreview(t.id));
}
// silent 只压「完成」类提示;失败永远要提示,不能被 silent 吞掉。
// silent 只压「完成」类提示;失败永远要提示,不能被 silent 吞掉。
if (t.input.silent) return;
if (t.input.silent) return;
// 仅异步导出(长任务、需「稍后查看」)弹完成提示;
// 仅异步导出(长任务、需「稍后查看」)弹完成提示;
...
@@ -133,6 +146,7 @@ export function DownloadCenterProvider({
...
@@ -133,6 +146,7 @@ export function DownloadCenterProvider({
bus.$off(DOWNLOAD_CENTER_REGISTER_EVENT, onRegister);
bus.$off(DOWNLOAD_CENTER_REGISTER_EVENT, onRegister);
bus.$off(DOWNLOAD_CENTER_CANCEL_EVENT, onCancel);
bus.$off(DOWNLOAD_CENTER_CANCEL_EVENT, onCancel);
bus.$off(DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT, onRegisterChannel);
bus.$off(DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT, onRegisterChannel);
bus.$off(OPEN_EXTERNAL_EVENT, onOpenExternal);
unsubscribe();
unsubscribe();
stopDownloadCenter();
stopDownloadCenter();
};
};
...
...
packages/download-center/src/TaskPreviewModal.tsx
0 → 100644
View file @
17e654c
import { useState } from 'react';
import { Button, Modal } from 'antd';
import { useDownloadCenterStore } from './store';
import { getTaskPreviewUrl, hasTaskFile, saveTaskAs } from './engine';
import type { DownloadTask } from './types';
type PreviewKind = 'image' | 'pdf' | 'video' | 'other';
/** 按文件名 / 地址后缀判断预览方式。content-disposition 给的名字优先于直链末段。 */
function previewKind(task: DownloadTask): PreviewKind {
const s = `${task.fileName ?? ''} ${task.fileUrl ?? ''}`.toLowerCase();
if (/\.(png|jpe?g|gif|webp|bmp|svg)(\?|$)/.test(s)) return 'image';
if (/\.pdf(\?|$)/.test(s)) return 'pdf';
if (/\.(mp4|webm|ogg|mov|m4v)(\?|$)/.test(s)) return 'video';
return 'other';
}
/** http 开发环境(非安全上下文)下 clipboard API 不可用,降级到 textarea + execCommand。 */
function copyText(text: string): void {
const native =
typeof navigator !== 'undefined' && navigator.clipboard?.writeText
? navigator.clipboard.writeText(text)
: Promise.reject(new Error('clipboard unavailable'));
native.catch(() => {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try {
document.execCommand('copy');
} finally {
ta.remove();
}
});
}
/**
* 全系统统一的预览弹窗。
*
* 有字节(probe ok / stream / blob)时用 objectURL 渲染,同源且不受原站鉴权影响;
* 没有字节(跨域无 CORS)时用原始直链渲染——浏览器允许 <img>/<iframe>/<video>
* 显示跨域资源,只是 JS 读不到字节,用户仍可在画面上右键另存。
* 不支持内联的格式(xlsx/doc/zip 等)不自动下载:弹窗只给链接与「下载文件」按钮,
* 用户主动点击才把直链挂给隐藏 iframe 触发下载/本机打开,避免看一眼就下载一次。
* 两种情形都不开新标签,不打断用户当前页面。
*/
export function TaskPreviewModal() {
const previewTaskId = useDownloadCenterStore((s) => s.previewTaskId);
const hidePreview = useDownloadCenterStore((s) => s.hidePreview);
const task = useDownloadCenterStore((s) =>
s.previewTaskId ? s.tasks.find((t) => t.id === s.previewTaskId) : undefined,
);
const [copied, setCopied] = useState(false);
// other 格式:弹窗打开时绝不自动下载。只有用户主动点「下载文件」才挂载 iframe 触发。
// state 带 taskId:切到别的任务时旧请求自动失效;关闭弹窗时清空,重开同一任务也不会再触发。
const [downloadReq, setDownloadReq] = useState<{ taskId: string; seq: number }>({ taskId: '', seq: 0 });
if (!previewTaskId || !task) return null;
const url = getTaskPreviewUrl(previewTaskId);
if (!url) return null;
const kind = previewKind(task);
const hasBytes = hasTaskFile(previewTaskId);
const downloadActive = downloadReq.taskId === previewTaskId && downloadReq.seq > 0;
const handleCopy = () => {
copyText(url);
setCopied(true);
window.setTimeout(() => setCopied(false), 1600);
};
const handleClose = () => {
setDownloadReq({ taskId: '', seq: 0 });
setCopied(false);
hidePreview();
};
return (
<Modal
open
zIndex={1200}
title={`预览 · ${task.label}`}
width={kind === 'image' ? 720 : 860}
onCancel={handleClose}
footer={
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
<span style={{ fontSize: 12, color: '#8c8c8c', textAlign: 'left' }}>
{hasBytes
? '文件已缓存,点「保存到本地」即可保存'
: kind === 'other'
? '此格式无法在线预览,需主动点「下载文件」才会触发下载'
: '请在预览画面上右键另存为'}
</span>
<span style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
{/* 有字节的 other 复制的是 blob: 地址,粘到浏览器打不开,隐藏掉避免误导。 */}
{!(hasBytes && kind === 'other') && (
<Button onClick={handleCopy}>{copied ? '已复制' : '复制链接'}</Button>
)}
{/* 只有确实拿到字节才显示:没有字节时 a[download] 也救不了跨域直链。 */}
{hasBytes && (
<Button type="primary" onClick={() => saveTaskAs(task.id)}>
保存到本地
</Button>
)}
<Button onClick={handleClose}>关闭</Button>
</span>
</div>
}
>
{kind === 'image' && (
<div style={{ textAlign: 'center', background: '#fafafa', padding: 12 }}>
<img
src={url}
alt={task.label}
style={{ maxWidth: '100%', maxHeight: '65vh', objectFit: 'contain' }}
/>
</div>
)}
{kind === 'pdf' && (
<iframe src={url} title={task.label} style={{ width: '100%', height: '65vh', border: 0 }} />
)}
{kind === 'video' && (
<div style={{ textAlign: 'center', background: '#fafafa', padding: 12 }}>
<video src={url} controls style={{ maxWidth: '100%', maxHeight: '65vh' }} />
</div>
)}
{kind === 'other' && !hasBytes && (
<div style={{ padding: 8 }}>
<div style={{ color: '#8c8c8c', marginBottom: 8 }}>
此格式无法在页面内渲染(xlsx / doc / zip 等)。点「下载文件」后浏览器才会下载或用本机程序打开;
仅打开预览不会下载。没反应可再点「重新下载」,或复制下方地址到浏览器地址栏。
</div>
{/* 只在用户主动点下载后才挂载 iframe:src 一挂上浏览器就会触发下载/本机打开。
打开弹窗先不渲染,避免看一眼预览就莫名下载一次。0×0 移出视口不占版面。 */}
{downloadActive && (
<iframe
key={downloadReq.seq}
src={url}
title={task.label}
aria-hidden="true"
style={{ position: 'fixed', width: 0, height: 0, border: 0, left: -9999, top: -9999 }}
/>
)}
<div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<Button
type="primary"
size="small"
onClick={() => setDownloadReq({ taskId: previewTaskId, seq: downloadReq.seq + 1 })}
>
{downloadActive ? '重新下载' : '下载文件'}
</Button>
</div>
<div
role="button"
tabIndex={0}
title="点击复制地址"
onClick={handleCopy}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') handleCopy();
}}
style={{
marginTop: 8,
padding: 10,
background: '#fafafa',
border: '1px solid #f0f0f0',
borderRadius: 4,
fontFamily: 'monospace',
fontSize: 12,
wordBreak: 'break-all',
cursor: 'pointer',
color: '#1677ff',
}}
>
{url}
</div>
</div>
)}
{kind === 'other' && hasBytes && (
<div style={{ padding: 12, color: '#8c8c8c', lineHeight: 1.7 }}>
此格式无法在页面内预览,但文件已完整缓存到本地。点右下角「保存到本地」即可保存,
保存位置由浏览器的下载设置决定。
</div>
)}
</Modal>
);
}
packages/download-center/src/deliver.ts
View file @
17e654c
import
type
{
DeliverTools
}
from
'./types'
;
import
type
{
DeliverTools
,
RemoteDelivery
}
from
'./types'
;
export
type
{
RemoteDelivery
}
from
'./types'
;
const
DEFAULT_FILENAME
=
'下载文件'
;
const
DEFAULT_FILENAME
=
'下载文件'
;
...
@@ -30,6 +32,9 @@ export function parseFileName(disposition: string, fallback = DEFAULT_FILENAME):
...
@@ -30,6 +32,9 @@ export function parseFileName(disposition: string, fallback = DEFAULT_FILENAME):
return
sanitizeFileName
(
filename
,
fallback
);
return
sanitizeFileName
(
filename
,
fallback
);
}
}
/** objectURL 延迟释放:0ms 释放会让 async 链路里的下载在浏览器消费前失效。 */
const
OBJECT_URL_TTL
=
60
_000
;
/** Blob -> <a download>。objectURL 延迟释放,确保浏览器已消费下载链接。 */
/** Blob -> <a download>。objectURL 延迟释放,确保浏览器已消费下载链接。 */
export
function
saveBlob
(
blob
:
Blob
,
fileName
:
string
):
void
{
export
function
saveBlob
(
blob
:
Blob
,
fileName
:
string
):
void
{
const
objectUrl
=
URL
.
createObjectURL
(
blob
);
const
objectUrl
=
URL
.
createObjectURL
(
blob
);
...
@@ -42,10 +47,21 @@ export function saveBlob(blob: Blob, fileName: string): void {
...
@@ -42,10 +47,21 @@ export function saveBlob(blob: Blob, fileName: string): void {
link
.
click
();
link
.
click
();
}
finally
{
}
finally
{
link
.
remove
();
link
.
remove
();
setTimeout
(()
=>
URL
.
revokeObjectURL
(
objectUrl
),
0
);
setTimeout
(()
=>
URL
.
revokeObjectURL
(
objectUrl
),
OBJECT_URL_TTL
);
}
}
}
}
/**
* 面板「另存为」:统一走 probe ok 链路已验证过的 a[download]。
*
* 不用 showSaveFilePicker 的原因:微前端沙箱 / 非安全上下文下它经常直接抛
* SecurityError 或静默不弹窗,而打开预览弹窗时已经过了用户手势窗口,
* 表现为「点了没反应」。保存位置由浏览器自身下载策略(下载前询问)决定。
*/
export
function
saveBlobAs
(
blob
:
Blob
,
fileName
:
string
):
void
{
saveBlob
(
blob
,
fileName
);
}
/** 本地回环地址没有 TLS 服务,浏览器本身也不拦,改写只会把它改坏。 */
/** 本地回环地址没有 TLS 服务,浏览器本身也不拦,改写只会把它改坏。 */
const
LOCAL_HOSTNAMES
=
new
Set
([
'localhost'
,
'127.0.0.1'
,
'::1'
]);
const
LOCAL_HOSTNAMES
=
new
Set
([
'localhost'
,
'127.0.0.1'
,
'::1'
]);
...
@@ -320,10 +336,68 @@ export function invalidDownload(payload: unknown): Error {
...
@@ -320,10 +336,68 @@ export function invalidDownload(payload: unknown): Error {
return
new
Error
(
'导出响应不是可下载的文件'
);
return
new
Error
(
'导出响应不是可下载的文件'
);
}
}
/**
* url / 异步导出共用的落地出口。
*
* 为什么统一:过去两条链路各自处理 probe 结果,opaque 一律退回 0×0 隐藏 iframe。
* 浏览器对 inline 资源(PNG / PDF)只会内联渲染,不写下载记录——用户看到任务
* 「完成 / 可下载」,磁盘和浏览器下载管理里却什么都没有,零提示。现在:
* - ok:用响应体 saveBlob 真落盘,并把 blob 交给引擎缓存;
* - opaque:只回传地址与明确 note,由主壳 Modal 内联渲染预览(跨域无 CORS 时
* JS 拿不到字节,浏览器也禁止跨源 <a download> 强制保存,这是安全边界);
* - error:抛错,由引擎落 failed 并弹失败提示。
*/
export
async
function
deliverRemoteFile
(
url
:
string
,
fallbackName
:
string
,
signal
:
AbortSignal
|
undefined
,
opts
:
{
preview
?:
boolean
;
autoDownload
?:
boolean
;
openInNewTab
?:
boolean
}
=
{},
):
Promise
<
RemoteDelivery
>
{
const
probe
=
await
probeDownloadUrl
(
url
,
fallbackName
,
signal
);
// 探测期间可能被取消(abort 会让 probe 返回 opaque 而不是抛错)。
// 必须在任何落地动作(saveBlob / 开标签)之前停下,否则取消后还弹出标签页。
if
(
signal
?.
aborted
)
throw
new
DOMException
(
'已取消'
,
'AbortError'
);
if
(
probe
.
kind
===
'error'
)
throw
new
Error
(
probe
.
message
);
if
(
probe
.
kind
===
'ok'
)
{
if
(
opts
.
preview
)
{
// 只回传字节,由主壳 Modal 渲染;不自动落盘(点缩略图是要看原图,不是下载)。
return
{
fileName
:
probe
.
fileName
,
bytes
:
probe
.
bytes
,
blob
:
probe
.
blob
,
note
:
'已打开预览'
,
openedOnly
:
false
,
};
}
if
(
opts
.
autoDownload
!==
false
)
saveBlob
(
probe
.
blob
,
probe
.
fileName
);
return
{
fileName
:
probe
.
fileName
,
bytes
:
probe
.
bytes
,
blob
:
probe
.
blob
,
note
:
'下载完成'
,
openedOnly
:
false
,
};
}
// opaque:JS 读不到字节,但浏览器允许 <img>/<iframe>/<video> 内联显示跨域资源。
// 不再开可见标签打断用户:预览统一由下载中心的 Modal 渲染,用户在画面上右键另存。
assertDownloadableUrl
(
url
);
return
{
fileName
:
fallbackName
,
note
:
opts
.
preview
?
'已获取预览地址,请在预览画面上右键另存为'
:
'文件未自动保存:请在下载中心点「预览」后右键另存为'
,
openedOnly
:
true
,
};
}
export
const
deliverTools
:
DeliverTools
=
{
export
const
deliverTools
:
DeliverTools
=
{
saveBlob
,
saveBlob
,
saveBlobAs
,
openUrl
,
openUrl
,
openPreview
,
openPreview
,
deliverRemoteFile
,
parseFileName
,
parseFileName
,
sanitizeFileName
,
sanitizeFileName
,
};
};
packages/download-center/src/engine.ts
View file @
17e654c
import
type
{
RemoteRequestFn
}
from
'@uj/contracts'
;
import
type
{
RemoteRequestFn
}
from
'@uj/contracts'
;
import
{
useDownloadCenterStore
}
from
'./store'
;
import
{
useDownloadCenterStore
}
from
'./store'
;
import
{
deliverTools
}
from
'./deliver'
;
import
{
deliverTools
,
saveBlobAs
}
from
'./deliver'
;
import
{
handlerOf
,
registerHandler
}
from
'./handlers/registry'
;
import
{
handlerOf
,
registerHandler
}
from
'./handlers/registry'
;
import
{
registerBuiltinHandlers
}
from
'./handlers/builtin'
;
import
{
registerBuiltinHandlers
}
from
'./handlers/builtin'
;
import
type
{
DownloadContext
,
DownloadHandler
,
DownloadTask
}
from
'./types'
;
import
type
{
DownloadContext
,
DownloadHandler
,
DownloadTask
}
from
'./types'
;
...
@@ -16,6 +16,13 @@ let concurrency = DEFAULT_CONCURRENCY;
...
@@ -16,6 +16,13 @@ let concurrency = DEFAULT_CONCURRENCY;
const
channels
=
new
Map
<
string
,
RemoteRequestFn
>
();
const
channels
=
new
Map
<
string
,
RemoteRequestFn
>
();
/** 正在执行的任务 -> 可中止控制器。用于并发计数、取消、登出清理。 */
/** 正在执行的任务 -> 可中止控制器。用于并发计数、取消、登出清理。 */
const
controllers
=
new
Map
<
string
,
AbortController
>
();
const
controllers
=
new
Map
<
string
,
AbortController
>
();
/**
* 已完成任务的字节缓存(仅内存,不进 localStorage)。
* probe ok 时 handler 会回传 blob,面板据此提供真正的「预览 / 另存为」;
* 跨域无 CORS 的任务没有 blob,按钮退化为开可见标签让用户右键另存。
* objectUrl 只在首次预览时生成并复用,避免每次点击都泄漏一个 URL。
*/
const
taskFiles
=
new
Map
<
string
,
{
blob
:
Blob
;
fileName
:
string
;
objectUrl
?:
string
}
>
();
/** 主壳启动时注入请求能力;同时注册内置下载方式与可选自定义方式。 */
/** 主壳启动时注入请求能力;同时注册内置下载方式与可选自定义方式。 */
export
function
configureDownloadCenter
(
opts
:
{
export
function
configureDownloadCenter
(
opts
:
{
...
@@ -110,9 +117,20 @@ async function runOne(task: DownloadTask): Promise<void> {
...
@@ -110,9 +117,20 @@ async function runOne(task: DownloadTask): Promise<void> {
try
{
try
{
const
result
=
await
handler
.
execute
(
task
,
ctx
);
const
result
=
await
handler
.
execute
(
task
,
ctx
);
if
(
ctx
.
isCanceled
())
return
;
if
(
ctx
.
isCanceled
())
return
;
// 先缓存字节再落 done:React 在 patch 后重渲染,此时 hasTaskFile 必须已经是 true。
if
(
result
.
blob
)
{
taskFiles
.
set
(
task
.
id
,
{
blob
:
result
.
blob
,
fileName
:
result
.
fileName
??
task
.
fileName
??
task
.
label
,
});
}
else
{
taskFiles
.
delete
(
task
.
id
);
}
useDownloadCenterStore
.
getState
().
patch
(
task
.
id
,
{
useDownloadCenterStore
.
getState
().
patch
(
task
.
id
,
{
status
:
'done'
,
status
:
'done'
,
stage
:
'完成'
,
// 用 handler 的 note 取代笼统的「完成」:opaque 分支靠它告诉用户
// 「未自动保存,请在标签页中右键另存为」,不再制造「可下载」的假象。
stage
:
result
.
note
??
'完成'
,
progress
:
100
,
progress
:
100
,
fileName
:
result
.
fileName
??
task
.
fileName
,
fileName
:
result
.
fileName
??
task
.
fileName
,
fileUrl
:
result
.
fileUrl
,
fileUrl
:
result
.
fileUrl
,
...
@@ -178,6 +196,11 @@ export function stopDownloadCenter(opts?: { markCanceled?: boolean }): void {
...
@@ -178,6 +196,11 @@ export function stopDownloadCenter(opts?: { markCanceled?: boolean }): void {
controllers
.
forEach
((
c
)
=>
c
.
abort
());
controllers
.
forEach
((
c
)
=>
c
.
abort
());
controllers
.
clear
();
controllers
.
clear
();
if
(
!
opts
?.
markCanceled
)
return
;
if
(
!
opts
?.
markCanceled
)
return
;
// 登出:字节缓存可能属于上一个账号,连同 objectURL 一起丢弃。
taskFiles
.
forEach
((
f
)
=>
{
if
(
f
.
objectUrl
)
URL
.
revokeObjectURL
(
f
.
objectUrl
);
});
taskFiles
.
clear
();
const
store
=
useDownloadCenterStore
.
getState
();
const
store
=
useDownloadCenterStore
.
getState
();
store
.
tasks
.
forEach
((
t
)
=>
{
store
.
tasks
.
forEach
((
t
)
=>
{
if
(
t
.
status
===
'waiting'
||
t
.
status
===
'running'
)
{
if
(
t
.
status
===
'waiting'
||
t
.
status
===
'running'
)
{
...
@@ -198,9 +221,44 @@ export function cancelTask(id: string): void {
...
@@ -198,9 +221,44 @@ export function cancelTask(id: string): void {
*/
*/
export
function
removeTask
(
id
:
string
):
void
{
export
function
removeTask
(
id
:
string
):
void
{
controllers
.
get
(
id
)?.
abort
();
controllers
.
get
(
id
)?.
abort
();
forgetFile
(
id
);
useDownloadCenterStore
.
getState
().
remove
(
id
);
useDownloadCenterStore
.
getState
().
remove
(
id
);
}
}
function
forgetFile
(
id
:
string
):
void
{
const
cached
=
taskFiles
.
get
(
id
);
if
(
cached
?.
objectUrl
)
URL
.
revokeObjectURL
(
cached
.
objectUrl
);
taskFiles
.
delete
(
id
);
}
/** 面板按钮显示条件:缓存里有字节(probe ok / stream / blob 类)。 */
export
function
hasTaskFile
(
taskId
:
string
):
boolean
{
return
taskFiles
.
has
(
taskId
);
}
/**
* 取预览地址:有字节用 objectURL(同源、不受原站鉴权与 CORS 影响),
* 否则退回原始直链。只返回 URL,不打开任何新标签——渲染交给 TaskPreviewModal。
*/
export
function
getTaskPreviewUrl
(
taskId
:
string
):
string
|
undefined
{
const
cached
=
taskFiles
.
get
(
taskId
);
if
(
cached
)
{
if
(
!
cached
.
objectUrl
)
cached
.
objectUrl
=
URL
.
createObjectURL
(
cached
.
blob
);
return
cached
.
objectUrl
;
}
const
task
=
useDownloadCenterStore
.
getState
().
tasks
.
find
((
t
)
=>
t
.
id
===
taskId
);
return
task
?.
fileUrl
;
}
/**
* 面板「另存为」:有字节走 showSaveFilePicker 让用户选位置(不支持则回退 a[download])。
* 没有字节时由 Modal 提示用户右键另存,这里不开标签也不做无意义的跳转。
*/
export
function
saveTaskAs
(
taskId
:
string
):
void
{
const
cached
=
taskFiles
.
get
(
taskId
);
if
(
cached
)
saveBlobAs
(
cached
.
blob
,
cached
.
fileName
);
}
/**
/**
* 面板「再次下载」:统一重新登记同类任务、走 handler 完整重跑一遍。
* 面板「再次下载」:统一重新登记同类任务、走 handler 完整重跑一遍。
*
*
...
...
packages/download-center/src/handlers/asyncExport.ts
View file @
17e654c
...
@@ -309,8 +309,20 @@ export const asyncExportHandler: DownloadHandler = {
...
@@ -309,8 +309,20 @@ export const asyncExportHandler: DownloadHandler = {
);
);
}
}
const
fileName
=
task
.
input
.
fileName
??
task
.
label
;
const
fileName
=
task
.
input
.
fileName
??
task
.
label
;
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
openUrl
(
fileUrl
);
// 与 url 直链共用落地出口:拿到 fileUrl 后先探测再保存,inline 的 PDF / 图片
return
{
fileUrl
,
fileName
,
note
:
'导出完成'
};
// 不再只在 0×0 隐藏 iframe 里渲染;拿不到字节(跨域无 CORS)时开可见标签,
// 并把「未自动保存,请右键另存为」写进 stage,不再误报「完成」。
const
delivery
=
await
ctx
.
deliver
.
deliverRemoteFile
(
fileUrl
,
fileName
,
ctx
.
signal
,
{
autoDownload
:
task
.
input
.
autoDownload
,
});
if
(
ctx
.
isCanceled
())
throw
new
DOMException
(
'已取消'
,
'AbortError'
);
return
{
fileUrl
,
fileName
:
delivery
.
fileName
,
bytes
:
delivery
.
bytes
,
blob
:
delivery
.
blob
,
note
:
delivery
.
note
,
};
}
}
if
(
status
===
2
)
{
if
(
status
===
2
)
{
throw
new
Error
(
buildFailError
(
info
,
envelope
,
uuid
,
'后端生成文件失败'
));
throw
new
Error
(
buildFailError
(
info
,
envelope
,
uuid
,
'后端生成文件失败'
));
...
...
packages/download-center/src/handlers/simple.ts
View file @
17e654c
...
@@ -5,12 +5,7 @@ import type {
...
@@ -5,12 +5,7 @@ import type {
DownloadResult
,
DownloadResult
,
UrlPayload
,
UrlPayload
,
}
from
'../types'
;
}
from
'../types'
;
import
{
import
{
blobFromBase64
,
upgradeInsecureUrl
}
from
'../deliver'
;
assertDownloadableUrl
,
blobFromBase64
,
probeDownloadUrl
,
upgradeInsecureUrl
,
}
from
'../deliver'
;
/** 从 URL 路径末段推断文件名(预签名 URL 的 query 不参与)。 */
/** 从 URL 路径末段推断文件名(预签名 URL 的 query 不参与)。 */
function
fileNameFromUrl
(
url
:
string
):
string
{
function
fileNameFromUrl
(
url
:
string
):
string
{
...
@@ -39,44 +34,21 @@ export const urlHandler: DownloadHandler = {
...
@@ -39,44 +34,21 @@ export const urlHandler: DownloadHandler = {
const
url
=
upgradeInsecureUrl
(
payload
.
url
);
const
url
=
upgradeInsecureUrl
(
payload
.
url
);
const
fileName
=
task
.
input
.
fileName
??
fileNameFromUrl
(
url
);
const
fileName
=
task
.
input
.
fileName
??
fileNameFromUrl
(
url
);
// 先 fetch 探测:同源 / 带 CORS 的直链能读到 HTTP 状态与响应体,
// 探测 + 落地统一走 deliverRemoteFile:ok 用响应体真落盘并回传字节;
// 过去 iframe 读不到的「请求资源不存在」(404 或 200+JSON 业务错误)
// opaque 开可见新标签(不再用 0×0 隐藏 iframe 静默吞掉 inline 图片);
// 现在会走 error 分支抛错,由引擎落 failed 并触发失败通知。
// error 抛错由引擎落 failed。取消与落地顺序也由它统一保证。
const
probe
=
await
probeDownloadUrl
(
url
,
fileName
,
ctx
.
signal
);
const
delivery
=
await
ctx
.
deliver
.
deliverRemoteFile
(
url
,
fileName
,
ctx
.
signal
,
{
// 探测期间任务可能被取消(signal abort 会让 probe 返回 opaque 而非抛错)。
preview
:
payload
.
preview
,
// 这里主动抛 AbortError,交回引擎按「已取消」落状态,避免取消后仍继续下载。
autoDownload
:
task
.
input
.
autoDownload
,
openInNewTab
:
payload
.
openInNewTab
,
});
if
(
ctx
.
isCanceled
())
throw
new
DOMException
(
'已取消'
,
'AbortError'
);
if
(
ctx
.
isCanceled
())
throw
new
DOMException
(
'已取消'
,
'AbortError'
);
if
(
probe
.
kind
===
'error'
)
throw
new
Error
(
probe
.
message
);
if
(
probe
.
kind
===
'ok'
)
{
if
(
payload
.
preview
)
{
ctx
.
deliver
.
openPreview
(
url
);
return
{
fileUrl
:
url
,
fileName
:
probe
.
fileName
,
bytes
:
probe
.
bytes
,
note
:
'已打开预览'
};
}
// 探测成功即直接用响应体落盘,不再重复发一次 iframe 请求。
if
(
task
.
input
.
autoDownload
!==
false
)
{
ctx
.
deliver
.
saveBlob
(
probe
.
blob
,
probe
.
fileName
);
}
return
{
fileUrl
:
url
,
fileName
:
probe
.
fileName
,
bytes
:
probe
.
bytes
,
note
:
'下载完成'
,
};
}
// opaque:跨域无 CORS 的 OSS 预签名地址,无法探测,退回原 iframe 行为。
// 这类地址的加载失败浏览器不让 JS 感知,是既定限制,不能因此误判为失败。
assertDownloadableUrl
(
url
);
if
(
payload
.
preview
)
{
ctx
.
deliver
.
openPreview
(
url
);
}
else
if
(
task
.
input
.
autoDownload
!==
false
)
{
ctx
.
deliver
.
openUrl
(
url
,
payload
.
openInNewTab
??
true
);
}
return
{
return
{
fileUrl
:
url
,
fileUrl
:
url
,
fileName
,
fileName
:
delivery
.
fileName
,
note
:
payload
.
preview
?
'已打开预览'
:
'已打开下载地址'
,
bytes
:
delivery
.
bytes
,
blob
:
delivery
.
blob
,
note
:
delivery
.
note
,
};
};
},
},
};
};
...
@@ -89,7 +61,7 @@ export const blobHandler: DownloadHandler = {
...
@@ -89,7 +61,7 @@ export const blobHandler: DownloadHandler = {
if
(
!
(
payload
?.
blob
instanceof
Blob
))
throw
new
Error
(
'Blob 下载缺少有效 blob'
);
if
(
!
(
payload
?.
blob
instanceof
Blob
))
throw
new
Error
(
'Blob 下载缺少有效 blob'
);
const
fileName
=
task
.
input
.
fileName
??
task
.
label
;
const
fileName
=
task
.
input
.
fileName
??
task
.
label
;
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
saveBlob
(
payload
.
blob
,
fileName
);
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
saveBlob
(
payload
.
blob
,
fileName
);
return
{
fileName
,
bytes
:
payload
.
blob
.
size
,
note
:
'下载完成'
};
return
{
fileName
,
bytes
:
payload
.
blob
.
size
,
note
:
'下载完成'
,
blob
:
payload
.
blob
};
},
},
};
};
...
@@ -102,7 +74,7 @@ export const base64Handler: DownloadHandler = {
...
@@ -102,7 +74,7 @@ export const base64Handler: DownloadHandler = {
const
fileName
=
task
.
input
.
fileName
??
task
.
label
;
const
fileName
=
task
.
input
.
fileName
??
task
.
label
;
const
blob
=
blobFromBase64
(
payload
.
base64
,
payload
.
mime
??
'application/octet-stream'
);
const
blob
=
blobFromBase64
(
payload
.
base64
,
payload
.
mime
??
'application/octet-stream'
);
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
saveBlob
(
blob
,
fileName
);
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
saveBlob
(
blob
,
fileName
);
return
{
fileName
,
bytes
:
blob
.
size
,
note
:
'下载完成'
};
return
{
fileName
,
bytes
:
blob
.
size
,
note
:
'下载完成'
,
blob
};
},
},
};
};
...
...
packages/download-center/src/handlers/stream.ts
View file @
17e654c
...
@@ -69,6 +69,6 @@ export const streamHandler: DownloadHandler = {
...
@@ -69,6 +69,6 @@ export const streamHandler: DownloadHandler = {
ctx
.
report
({
stage
:
'正在保存文件'
});
ctx
.
report
({
stage
:
'正在保存文件'
});
const
blob
=
blobFromArrayBuffer
(
body
,
mime
);
const
blob
=
blobFromArrayBuffer
(
body
,
mime
);
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
saveBlob
(
blob
,
fileName
);
if
(
task
.
input
.
autoDownload
!==
false
)
ctx
.
deliver
.
saveBlob
(
blob
,
fileName
);
return
{
fileName
,
bytes
:
blob
.
size
,
note
:
'下载完成'
};
return
{
fileName
,
bytes
:
blob
.
size
,
note
:
'下载完成'
,
blob
};
},
},
};
};
packages/download-center/src/index.ts
View file @
17e654c
...
@@ -30,6 +30,7 @@ export type {
...
@@ -30,6 +30,7 @@ export type {
DownloadContext
,
DownloadContext
,
DownloadResult
,
DownloadResult
,
DeliverTools
,
DeliverTools
,
RemoteDelivery
,
ExportQueryItem
,
ExportQueryItem
,
ExportQueryEnvelope
,
ExportQueryEnvelope
,
}
from
'./types'
;
}
from
'./types'
;
...
@@ -43,6 +44,9 @@ export {
...
@@ -43,6 +44,9 @@ export {
stopDownloadCenter
,
stopDownloadCenter
,
cancelTask
,
cancelTask
,
redownload
,
redownload
,
getTaskPreviewUrl
,
saveTaskAs
,
hasTaskFile
,
}
from
'./engine'
;
}
from
'./engine'
;
export
{
export
{
registerHandler
,
registerHandler
,
...
@@ -56,7 +60,10 @@ export { streamHandler } from './handlers/stream';
...
@@ -56,7 +60,10 @@ export { streamHandler } from './handlers/stream';
export
{
urlHandler
,
blobHandler
,
base64Handler
}
from
'./handlers/simple'
;
export
{
urlHandler
,
blobHandler
,
base64Handler
}
from
'./handlers/simple'
;
export
{
export
{
saveBlob
,
saveBlob
,
saveBlobAs
,
openUrl
,
openUrl
,
openPreview
,
deliverRemoteFile
,
parseFileName
,
parseFileName
,
sanitizeFileName
,
sanitizeFileName
,
blobFromArrayBuffer
,
blobFromArrayBuffer
,
...
@@ -66,4 +73,5 @@ export {
...
@@ -66,4 +73,5 @@ export {
}
from
'./deliver'
;
}
from
'./deliver'
;
export
{
registerDownload
,
registerExportTask
}
from
'./register'
;
export
{
registerDownload
,
registerExportTask
}
from
'./register'
;
export
{
DownloadCenterButton
}
from
'./DownloadCenterButton'
;
export
{
DownloadCenterButton
}
from
'./DownloadCenterButton'
;
export
{
TaskPreviewModal
}
from
'./TaskPreviewModal'
;
export
{
DownloadCenterProvider
}
from
'./DownloadCenterProvider'
;
export
{
DownloadCenterProvider
}
from
'./DownloadCenterProvider'
;
packages/download-center/src/store.ts
View file @
17e654c
...
@@ -89,6 +89,12 @@ interface DownloadCenterState {
...
@@ -89,6 +89,12 @@ interface DownloadCenterState {
notice
:
DownloadNotice
|
null
;
notice
:
DownloadNotice
|
null
;
/** 最近一次登记(用户点导出/下载)的时间戳:驱动图标短时反馈动画,与任务状态解耦。 */
/** 最近一次登记(用户点导出/下载)的时间戳:驱动图标短时反馈动画,与任务状态解耦。 */
lastRegisterAt
:
number
;
lastRegisterAt
:
number
;
/** 当前预览的任务 id。Modal 由 DownloadCenterButton 渲染,不持久化。 */
previewTaskId
:
string
|
null
;
/** 打开预览弹窗。 */
showPreview
:
(
id
:
string
)
=>
void
;
/** 关闭预览弹窗。 */
hidePreview
:
()
=>
void
;
/** 推送一条浮窗提示。 */
/** 推送一条浮窗提示。 */
pushNotice
:
(
notice
:
Omit
<
DownloadNotice
,
'seq'
>
)
=>
void
;
pushNotice
:
(
notice
:
Omit
<
DownloadNotice
,
'seq'
>
)
=>
void
;
/** 清掉指定序号的提示;seq 不匹配时不动,避免旧 timer 关掉后来的新提示。 */
/** 清掉指定序号的提示;seq 不匹配时不动,避免旧 timer 关掉后来的新提示。 */
...
@@ -114,6 +120,10 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
...
@@ -114,6 +120,10 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
tasks
:
loadPersisted
(),
tasks
:
loadPersisted
(),
notice
:
null
,
notice
:
null
,
lastRegisterAt
:
0
,
lastRegisterAt
:
0
,
previewTaskId
:
null
,
showPreview
:
(
id
)
=>
set
({
previewTaskId
:
id
}),
hidePreview
:
()
=>
set
({
previewTaskId
:
null
}),
pushNotice
:
(
notice
)
=>
set
({
notice
:
{
...
notice
,
seq
:
++
noticeSeq
}
}),
pushNotice
:
(
notice
)
=>
set
({
notice
:
{
...
notice
,
seq
:
++
noticeSeq
}
}),
...
@@ -161,7 +171,11 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
...
@@ -161,7 +171,11 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
),
),
),
),
remove
:
(
id
)
=>
set
((
s
)
=>
write
(
s
.
tasks
.
filter
((
t
)
=>
t
.
id
!==
id
))),
remove
:
(
id
)
=>
set
((
s
)
=>
({
...
write
(
s
.
tasks
.
filter
((
t
)
=>
t
.
id
!==
id
)),
...(
s
.
previewTaskId
===
id
?
{
previewTaskId
:
null
}
:
{}),
})),
cancel
:
(
id
)
=>
cancel
:
(
id
)
=>
set
((
s
)
=>
set
((
s
)
=>
...
@@ -175,6 +189,13 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
...
@@ -175,6 +189,13 @@ export const useDownloadCenterStore = create<DownloadCenterState>((set, get) =>
),
),
clearFinished
:
()
=>
clearFinished
:
()
=>
set
((
s
)
=>
write
(
s
.
tasks
.
filter
((
t
)
=>
!
FINISHED
.
includes
(
t
.
status
)))),
set
((
s
)
=>
{
const
next
=
write
(
s
.
tasks
.
filter
((
t
)
=>
!
FINISHED
.
includes
(
t
.
status
)));
// 预览中的任务被清掉时一并关窗,避免 Modal 显示一条已不存在的记录。
const
previewing
=
s
.
tasks
.
find
((
t
)
=>
t
.
id
===
s
.
previewTaskId
);
return
previewing
&&
FINISHED
.
includes
(
previewing
.
status
)
?
{
...
next
,
previewTaskId
:
null
}
:
next
;
}),
};
};
});
});
packages/download-center/src/types.ts
View file @
17e654c
...
@@ -24,16 +24,37 @@ export type {
...
@@ -24,16 +24,37 @@ export type {
export
interface
DeliverTools
{
export
interface
DeliverTools
{
/** Blob -> <a download>(含 objectURL 释放)。 */
/** Blob -> <a download>(含 objectURL 释放)。 */
saveBlob
(
blob
:
Blob
,
fileName
:
string
):
void
;
saveBlob
(
blob
:
Blob
,
fileName
:
string
):
void
;
/** Blob -> 用户选择位置保存(统一走 a[download],避免沙箱下手势丢失)。 */
saveBlobAs
(
blob
:
Blob
,
fileName
:
string
):
void
;
/** 打开自带鉴权的 URL(新标签页,避免主壳被导航走)。 */
/** 打开自带鉴权的 URL(新标签页,避免主壳被导航走)。 */
openUrl
(
url
:
string
,
openInNewTab
?:
boolean
):
void
;
openUrl
(
url
:
string
,
openInNewTab
?:
boolean
):
void
;
/** 可见新标签预览:与 openUrl 的隐藏 iframe 落盘不同,只给用户看,不触发下载。 */
/** 可见新标签预览:与 openUrl 的隐藏 iframe 落盘不同,只给用户看,不触发下载。 */
openPreview
(
url
:
string
):
void
;
openPreview
(
url
:
string
):
void
;
/**
* 远程 URL 统一落地:可探测则 saveBlob + 回传字节;不可探测则开可见标签并给出
* 明确 note,不再静默「完成」但磁盘上没文件。
*/
deliverRemoteFile
(
url
:
string
,
fallbackName
:
string
,
signal
:
AbortSignal
|
undefined
,
opts
?:
{
preview
?:
boolean
;
autoDownload
?:
boolean
;
openInNewTab
?:
boolean
},
):
Promise
<
RemoteDelivery
>
;
/** 从 content-disposition 解析并清洗文件名。 */
/** 从 content-disposition 解析并清洗文件名。 */
parseFileName
(
disposition
:
string
,
fallback
:
string
):
string
;
parseFileName
(
disposition
:
string
,
fallback
:
string
):
string
;
/** 清洗文件名中的非法字符与 C0 控制字符。 */
/** 清洗文件名中的非法字符与 C0 控制字符。 */
sanitizeFileName
(
name
:
string
,
fallback
?:
string
):
string
;
sanitizeFileName
(
name
:
string
,
fallback
?:
string
):
string
;
}
}
/** deliverRemoteFile 的返回,单独导出供类型引用。 */
export
interface
RemoteDelivery
{
fileName
:
string
;
bytes
?:
number
;
blob
?:
Blob
;
note
:
string
;
openedOnly
:
boolean
;
}
/** handler 执行完交给统一层的结果(用于面板展示与「再次下载」)。 */
/** handler 执行完交给统一层的结果(用于面板展示与「再次下载」)。 */
export
interface
DownloadResult
{
export
interface
DownloadResult
{
/** 最终文件名。 */
/** 最终文件名。 */
...
@@ -42,7 +63,9 @@ export interface DownloadResult {
...
@@ -42,7 +63,9 @@ export interface DownloadResult {
fileUrl
?:
string
;
fileUrl
?:
string
;
/** 字节数(stream / blob 类,用于面板展示)。 */
/** 字节数(stream / blob 类,用于面板展示)。 */
bytes
?:
number
;
bytes
?:
number
;
/** 附加说明。 */
/** 实际拿到的文件字节(probe ok 时由 deliverRemoteFile 回传),引擎按 taskId 缓存供预览 / 另存为。 */
blob
?:
Blob
;
/** 附加说明。引擎写入 stage,面板直接展示——opaque 分支靠它告诉用户「未自动保存,请右键另存为」。 */
note
?:
string
;
note
?:
string
;
}
}
...
...
packages/platform-sdk/src/downloadCenter.ts
View file @
17e654c
...
@@ -3,6 +3,7 @@ import {
...
@@ -3,6 +3,7 @@ import {
DOWNLOAD_CENTER_REGISTER_EVENT
,
DOWNLOAD_CENTER_REGISTER_EVENT
,
DOWNLOAD_CENTER_CANCEL_EVENT
,
DOWNLOAD_CENTER_CANCEL_EVENT
,
DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT
,
DOWNLOAD_CENTER_REGISTER_CHANNEL_EVENT
,
OPEN_EXTERNAL_EVENT
,
downloadChannelRop
,
downloadChannelRop
,
type
AsyncExportPayload
,
type
AsyncExportPayload
,
type
Base64Payload
,
type
Base64Payload
,
...
@@ -103,6 +104,14 @@ function withDefaults(input: AsyncExportInput): AsyncExportInput {
...
@@ -103,6 +104,14 @@ function withDefaults(input: AsyncExportInput): AsyncExportInput {
return
withProvider
(
withRopChannel
(
input
));
return
withProvider
(
withRopChannel
(
input
));
}
}
/**
* 打开外部页面(报告 / AI 分析等),不登记下载任务。
* 子应用 iframe 内直接 window.open 常被弹窗拦截,统一交给主壳开可见标签并处理回退。
*/
export
function
openExternal
(
url
:
string
):
void
{
subappBus
()?.
$emit
(
OPEN_EXTERNAL_EVENT
,
url
);
}
export
const
downloadCenter
=
{
export
const
downloadCenter
=
{
/** 统一登记(显式 kind);兼容旧写法:不带 kind 但带 method 时默认 async-export。 */
/** 统一登记(显式 kind);兼容旧写法:不带 kind 但带 method 时默认 async-export。 */
register
(
input
:
RegisterDownloadInput
|
RegisterExportTaskInput
):
void
{
register
(
input
:
RegisterDownloadInput
|
RegisterExportTaskInput
):
void
{
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment