Browse Source

♻️ refactor(word-preview): optimize image loading logic in word export

- 实现图片预加载机制,避免异步Promise问题
- 创建imageDataMap缓存图片数据,提高模板渲染性能
- 优化getImage方法为同步调用,直接返回预加载的图片数据
- 改进图片字段处理逻辑,确保图片名称正确传递给模板
- 添加图片加载错误捕获和警告日志
- 移除重复的folderIndex定义,优化变量作用域
yourname 4 months ago
parent
commit
54ff1af0df
1 changed files with 20 additions and 11 deletions
  1. 20 11
      src/client/admin-shadcn/pages/WordPreview.tsx

+ 20 - 11
src/client/admin-shadcn/pages/WordPreview.tsx

@@ -260,18 +260,27 @@ export default function WordPreview() {
       const arrayBuffer = await wordFile.arrayBuffer();
       const zip = new PizZip(arrayBuffer);
       
-      // 配置图片模块
+      // 预加载所有图片数据,避免Promise问题
+      const folderIndex = (rowIndex + 1).toString();
+      const imageDataMap: Record<string, ArrayBuffer> = {};
+      
+      // 预加载当前文件夹的所有图片
+      if (imageMappings[folderIndex]) {
+        for (const [imageName, imageFile] of Object.entries(imageMappings[folderIndex])) {
+          try {
+            imageDataMap[imageName] = await imageFile.arrayBuffer();
+          } catch (error) {
+            console.warn(`Failed to load image ${imageName}:`, error);
+          }
+        }
+      }
+      
+      // 配置图片模块 - 使用同步数据
       const imageOpts = {
         centered: false,
-        getImage: (tagValue: string) => {
-          console.log('tagValue', tagValue);
+        getImage: (tagValue: string): ArrayBuffer | null => {
           if (tagValue && typeof tagValue === 'string') {
-            // 从imageMappings中获取对应的图片
-            const folderIndex = (rowIndex + 1).toString();
-            const imageFile = imageMappings[folderIndex]?.[tagValue];
-            if (imageFile) {
-              return imageFile.arrayBuffer();
-            }
+            return imageDataMap[tagValue] || null;
           }
           return null;
         },
@@ -306,10 +315,10 @@ export default function WordPreview() {
         }
       });
 
-      // 处理图片字段 - 直接传递图片名称
-      const folderIndex = (rowIndex + 1).toString();
+      // 处理图片字段 - 确保图片名称正确传递给模板
       if (imageMappings[folderIndex]) {
         for (const [imageName] of Object.entries(imageMappings[folderIndex])) {
+          // 确保图片名称作为标签值传递给模板
           processedData[imageName] = imageName;
         }
       }