// Runs in an opaque-origin sandbox. Only the owning workbench may supply file bytes. import {renderWord,renderExcel} from './storage-preview-office.js'; const nonce=new URLSearchParams(location.search).get('nonce'),parentOrigin=new URL(location.href).origin; const status=document.querySelector('#preview-status'),content=document.querySelector('#preview-content');let accepted=false,viewer; function error(message){status.hidden=false;status.textContent=message;status.className='preview-error';content.hidden=true;} async function render(info,buffer){ if(info.kind==='text'){const text=document.createElement('pre');text.id='preview-text';text.textContent=new TextDecoder().decode(buffer);content.append(text);} else if(info.kind==='image'){ const url=URL.createObjectURL(new Blob([buffer],{type:info.contentType})),image=document.createElement('img');image.alt=info.filename;image.src=url;image.className='preview-image';const button=document.createElement('button');button.type='button';button.textContent='放大图片';button.className='image-zoom';content.append(button,image);await image.decode(); button.onclick=async()=>{const {default:PhotoSwipe}=await import('/vendor/photoswipe/photoswipe.esm.js');const gallery=new PhotoSwipe({dataSource:[{src:url,width:image.naturalWidth,height:image.naturalHeight,alt:info.filename}],bgOpacity:0.92});gallery.init();}; } else if(info.kind==='docx')await renderWord(buffer,content); else if(info.kind==='xlsx')await renderExcel(buffer,content); else if(info.kind==='pdf'){ const {default:EmbedPDF}=await import('/vendor/embedpdf/embedpdf.js');const url=URL.createObjectURL(new Blob([buffer],{type:'application/pdf'}));const target=document.createElement('div');target.id='preview-pdf';content.append(target); // Blob workers cannot initialize reliably under an opaque sandbox origin. // Keep PDFium in this isolated frame using the viewer's supported direct engine. viewer=EmbedPDF.init({type:'container',worker:false,target,src:url,wasmUrl:new URL('/vendor/embedpdf/pdfium.wasm',location.href).href,stamp:{manifests:[],libraries:[],defaultLibrary:false},fonts:{ui:null,signature:null},fontFallback:null,theme:{preference:'light'},i18n:{defaultLocale:'zh-CN',fallbackLocale:'en'}}); }else throw new Error('此格式暂不支持预览。'); status.hidden=true;content.hidden=false; } window.addEventListener('message',async event=>{ if(event.source!==window.parent||event.origin!==parentOrigin||event.data?.nonce!==nonce||event.data?.kind!=='order-storage-preview'||accepted)return; accepted=true;const message=event.data;if(message.error){error(message.error);return;} try{if(!(message.buffer instanceof ArrayBuffer))throw new Error('文件数据不可用。');await render(message.info,message.buffer);}catch(cause){error(cause.message||'文件预览失败,请下载原文件查看。');} }); window.addEventListener('pagehide',()=>viewer?.destroy?.()); window.parent.postMessage({kind:'order-storage-preview-ready',nonce},parentOrigin);