文件
hyb-oa/client/src/lib/wecomFilePreview.ts
T
wangsli da35591bd5
ci-e2e / e2e (push) Canceled after 0s
ci-minimal / check-minimal (push) Canceled after 0s
实现报销材料合并预览与差旅概要(07-27-yang-jun-reimbursement-readiness)
2026-08-01 09:25:44 +08:00

64 行
1.8 KiB
TypeScript

import { fetchWecomConfig, fetchWecomJsSdkSignature } from "../api/auth";
import { isWecomWebView } from "./runtimeContext";
export type NativePreviewFile = {
url: string;
name: string | null | undefined;
size: number | null | undefined;
};
let configuredSdkPromise: Promise<typeof import("@wecom/jssdk")> | null = null;
function currentPageUrl() {
const url = new URL(window.location.href);
url.hash = "";
return url.href;
}
async function configuredWecomSdk() {
if (!configuredSdkPromise) {
configuredSdkPromise = Promise.all([import("@wecom/jssdk"), fetchWecomConfig()])
.then(([ww, config]) => {
if (!config.corpId) {
throw new Error("企业微信文件预览未配置");
}
ww.register({
corpId: config.corpId,
jsApiList: ["previewFile"],
async getConfigSignature(url) {
const signed = await fetchWecomJsSdkSignature(url || currentPageUrl());
return {
timestamp: signed.timestamp,
nonceStr: signed.nonceStr,
signature: signed.signature,
};
},
});
return ww;
})
.catch((error) => {
configuredSdkPromise = null;
throw error;
});
}
return configuredSdkPromise;
}
export async function previewFileInWecom(file: NativePreviewFile) {
if (!isWecomWebView()) {
return false;
}
const name = file.name?.trim();
const size = Number(file.size);
if (!name || !/\.[a-z0-9]{1,10}$/i.test(name) || !Number.isSafeInteger(size) || size <= 0) {
throw new Error("文件信息不完整,暂时无法预览");
}
const ww = await configuredWecomSdk();
await ww.previewFile({ url: file.url, name, size });
return true;
}
export function openFileInBrowser(url: string) {
window.open(url, "_blank", "noopener,noreferrer");
}