fix(翻译预览):打开聊天附件预览抽屉或产物预览 → xlsx 网格上应出现嵌入图片(按锚点单元格定位)
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
若仍无图:按 F12 打开浏览器控制台,查找 [DocumentPreview] extract embedded images failed 告警发我——现在失败不再静默,可直接定位
This commit is contained in:
1 parent
10db1be7fa
commit
a6632e7b55
3 files changed
+229
-3
No files matched your search
@@ -95,8 +95,10 @@ const inputPlaceholder = computed(() => {
|
||||
if (
|
||||
selectedAgentId.value === SIP_TRANSLATOR_AGENT_ID &&
|
||||
uploadedAttachments.value.length > 0 &&
|
||||
uploadedAttachments.value.every(item => item.documentId && item.status !== 'failed')
|
||||
uploadedAttachments.value.every(item => item.status !== 'failed')
|
||||
) {
|
||||
// A first conversation has no session yet, so local files carry no
|
||||
// documentId until send — readiness is "not failed", not "uploaded".
|
||||
return '翻译文件已就绪,直接发送即可开始翻译';
|
||||
}
|
||||
return t('input.placeholder');
|
||||
@@ -115,9 +117,9 @@ watch(
|
||||
sipAutoFilled.value = false;
|
||||
return;
|
||||
}
|
||||
const ready = items.every(a => a.documentId && a.status !== 'failed');
|
||||
const ready = items.every(a => a.status !== 'failed');
|
||||
if (ready && !sipAutoFilled.value && !query.value.trim()) {
|
||||
query.value = '翻译';
|
||||
query.value = '翻译文件已就绪,直接发送即可开始翻译';
|
||||
sipAutoFilled.value = true;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useI18n } from 'vue-i18n';
|
||||
import { sanitizeHTML, sanitizeMarkdownHTML, hydrateProtectedFileImages } from '@/utils/security';
|
||||
import { preparePptxPreview, isCompletePptxRender } from '@/utils/pptxPreview';
|
||||
import { findMarkdownSourceRange } from '@/utils/markdownSourceLocate';
|
||||
import { extractExcelImages, mountExcelPreviewImages } from '@/utils/xlsxDrawings';
|
||||
import { renderDocumentPreviewMarkdown } from '@/utils/documentPreviewMarkdown';
|
||||
import { buildHtmlPreview } from '@/utils/htmlPreview';
|
||||
import { openMermaidFullscreen } from '@/utils/mermaidViewer';
|
||||
@@ -373,6 +374,12 @@ function decodeCSVBlob(arrayBuffer: ArrayBuffer): string {
|
||||
async function renderExcel(blob: Blob, fileType?: string) {
|
||||
const XLSX = await import('xlsx');
|
||||
const arrayBuffer = await blob.arrayBuffer();
|
||||
// Embedded photos live outside the cell model; keep the bytes so the
|
||||
// drawings overlay can mount them after the grid renders.
|
||||
const drawings = await extractExcelImages(arrayBuffer).catch(e => {
|
||||
console.warn('[DocumentPreview] extract embedded images failed:', e);
|
||||
return [];
|
||||
});
|
||||
|
||||
let workbook;
|
||||
const lowerType = fileType?.toLowerCase();
|
||||
@@ -399,6 +406,12 @@ async function renderExcel(blob: Blob, fileType?: string) {
|
||||
html += `</div>`;
|
||||
});
|
||||
excelHtml.value = sanitizeHTML(html);
|
||||
|
||||
await nextTick();
|
||||
const container = previewContent.value as HTMLElement | null;
|
||||
if (container && drawings.length > 0) {
|
||||
mountExcelPreviewImages(container, drawings);
|
||||
}
|
||||
}
|
||||
|
||||
async function renderText(blob: Blob, fileType: string) {
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
// xlsxDrawings — extracts embedded images and their cell anchors from an
|
||||
// .xlsx package so the spreadsheet preview can overlay them on the rendered
|
||||
// sheet grid. SheetJS only models cells; drawings (xl/drawings/*) live
|
||||
// outside its data model, which is why a plain sheet_to_html preview loses
|
||||
// every embedded photo.
|
||||
import JSZip from 'jszip';
|
||||
|
||||
// EMU (English Metric Unit) per CSS pixel: 914400 EMU / inch at 96 DPI.
|
||||
const EMU_PER_PX = 9525;
|
||||
|
||||
export interface ExcelCellPoint {
|
||||
col: number;
|
||||
colOffPx: number;
|
||||
row: number;
|
||||
rowOffPx: number;
|
||||
}
|
||||
|
||||
export interface ExcelDrawingImage {
|
||||
/** zero-based sheet index, matching workbook.SheetNames order */
|
||||
sheetIndex: number;
|
||||
from: ExcelCellPoint;
|
||||
/** twoCellAnchor end corner; null when the anchor carries an explicit size */
|
||||
to: ExcelCellPoint | null;
|
||||
/** explicit size from <a:ext> (oneCellAnchor), in preview pixels */
|
||||
extPx: { width: number; height: number } | null;
|
||||
/** data URL of the embedded image */
|
||||
src: string;
|
||||
}
|
||||
|
||||
function attr(tag: string, name: string): string {
|
||||
const m = tag.match(new RegExp(`${name}="([^"]*)"`));
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
function blockNum(block: string, tag: string): number {
|
||||
const m = block.match(new RegExp(`<${tag}>(-?\\d+)</${tag}>`));
|
||||
return m ? Number(m[1]) : 0;
|
||||
}
|
||||
|
||||
function parseCellPoint(block: string): ExcelCellPoint {
|
||||
return {
|
||||
col: blockNum(block, 'xdr:col'),
|
||||
colOffPx: Math.round(blockNum(block, 'xdr:colOff') / EMU_PER_PX),
|
||||
row: blockNum(block, 'xdr:row'),
|
||||
rowOffPx: Math.round(blockNum(block, 'xdr:rowOff') / EMU_PER_PX),
|
||||
};
|
||||
}
|
||||
|
||||
// normalizeRelPath resolves a rels Target such as "../media/image5.png"
|
||||
// against the part's own directory ("xl/drawings/") into a zip path.
|
||||
function normalizeRelPath(baseDir: string, target: string): string {
|
||||
const parts = `${baseDir}/${target}`.split('/');
|
||||
const out: string[] = [];
|
||||
for (const part of parts) {
|
||||
if (part === '' || part === '.') continue;
|
||||
if (part === '..') out.pop();
|
||||
else out.push(part);
|
||||
}
|
||||
return out.join('/');
|
||||
}
|
||||
|
||||
function relsMap(relsXml: string): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const tag of relsXml.match(/<Relationship\b[^>]*>/g) ?? []) {
|
||||
const id = attr(tag, 'Id');
|
||||
const target = attr(tag, 'Target');
|
||||
if (id && target) map.set(id, target);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
async function mediaDataUrl(zip: JSZip, mediaPath: string): Promise<string> {
|
||||
const file = zip.file(mediaPath);
|
||||
if (!file) return '';
|
||||
const b64 = await file.async('base64');
|
||||
const ext = (mediaPath.split('.').pop() || 'png').toLowerCase();
|
||||
const mime = ext === 'jpg' ? 'image/jpeg' : `image/${ext}`;
|
||||
return `data:${mime};base64,${b64}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* extractExcelImages reads every embedded picture of an .xlsx package with
|
||||
* its cell anchor, converted to preview pixel geometry. Best-effort: anchors
|
||||
* that reference unreadable media are skipped.
|
||||
*/
|
||||
export async function extractExcelImages(buf: ArrayBuffer): Promise<ExcelDrawingImage[]> {
|
||||
const zip = await JSZip.loadAsync(buf);
|
||||
|
||||
// Sheet order in workbook.xml matches SheetJS's workbook.SheetNames order.
|
||||
const workbookXml = (await zip.file('xl/workbook.xml')?.async('string')) ?? '';
|
||||
const sheetRids = (workbookXml.match(/<sheet\b[^>]*>/g) ?? []).map(tag => attr(tag, 'r:id'));
|
||||
|
||||
const wbRelsXml = (await zip.file('xl/_rels/workbook.xml.rels')?.async('string')) ?? '';
|
||||
const wbRels = relsMap(wbRelsXml);
|
||||
|
||||
const mediaCache = new Map<string, string>();
|
||||
const resolveMedia = async (baseDir: string, relsXml: string, rid: string): Promise<{ src: string } | null> => {
|
||||
const mediaTarget = relsMap(relsXml).get(rid);
|
||||
if (!mediaTarget) return null;
|
||||
const mediaPath = normalizeRelPath(baseDir, mediaTarget);
|
||||
let src = mediaCache.get(mediaPath);
|
||||
if (src === undefined) {
|
||||
src = await mediaDataUrl(zip, mediaPath);
|
||||
mediaCache.set(mediaPath, src ?? '');
|
||||
}
|
||||
return src ? { src } : null;
|
||||
};
|
||||
|
||||
const result: ExcelDrawingImage[] = [];
|
||||
for (let sheetIndex = 0; sheetIndex < sheetRids.length; sheetIndex++) {
|
||||
const sheetTarget = wbRels.get(sheetRids[sheetIndex]);
|
||||
if (!sheetTarget) continue;
|
||||
const sheetPath = normalizeRelPath('xl', sheetTarget);
|
||||
const sheetXml = (await zip.file(sheetPath)?.async('string')) ?? '';
|
||||
const drawingTag = sheetXml.match(/<drawing\b[^>]*\br:id="([^"]+)"/);
|
||||
if (!drawingTag) continue;
|
||||
|
||||
const sheetBaseDir = sheetPath.replace(/[^/]+$/, '');
|
||||
const sheetRelsXml =
|
||||
(await zip.file(normalizeRelPath(sheetBaseDir, `_rels/${sheetPath.split('/').pop()}.rels`))?.async('string')) ?? '';
|
||||
const drawingTarget = relsMap(sheetRelsXml).get(drawingTag[1]);
|
||||
if (!drawingTarget) continue;
|
||||
const drawingPath = normalizeRelPath(sheetBaseDir, drawingTarget);
|
||||
const drawingXml = (await zip.file(drawingPath)?.async('string')) ?? '';
|
||||
if (!drawingXml) continue;
|
||||
|
||||
const drawingBaseDir = drawingPath.replace(/[^/]+$/, '');
|
||||
const drawingRelsXml =
|
||||
(await zip.file(normalizeRelPath(drawingBaseDir, `_rels/${drawingPath.split('/').pop()}.rels`))?.async('string')) ?? '';
|
||||
|
||||
const anchorRe = /<xdr:(twoCellAnchor|oneCellAnchor)\b[\s\S]*?<\/xdr:\1>/g;
|
||||
for (const anchor of drawingXml.match(anchorRe) ?? []) {
|
||||
const blip = anchor.match(/<a:blip[^>]*\br:embed="([^"]+)"/);
|
||||
if (!blip) continue;
|
||||
const media = await resolveMedia(drawingBaseDir, drawingRelsXml, blip[1]);
|
||||
if (!media) continue;
|
||||
|
||||
const fromMatch = anchor.match(/<xdr:from>[\s\S]*?<\/xdr:from>/);
|
||||
if (!fromMatch) continue;
|
||||
const toMatch = anchor.match(/<xdr:to>[\s\S]*?<\/xdr:to>/);
|
||||
const extMatch = anchor.match(/<a:ext\s+cx="(\d+)"\s+cy="(\d+)"/);
|
||||
|
||||
result.push({
|
||||
sheetIndex,
|
||||
from: parseCellPoint(fromMatch[0]),
|
||||
to: toMatch ? parseCellPoint(toMatch[0]) : null,
|
||||
extPx: extMatch
|
||||
? {
|
||||
width: Math.round(Number(extMatch[1]) / EMU_PER_PX),
|
||||
height: Math.round(Number(extMatch[2]) / EMU_PER_PX),
|
||||
}
|
||||
: null,
|
||||
src: media.src,
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* mountExcelPreviewImages overlays extracted images onto the rendered sheet
|
||||
* tables inside `container`. Geometry is derived from the rendered table so
|
||||
* images follow the actual row/column sizes. Anchors beyond the rendered
|
||||
* extent clamp to the table edge.
|
||||
*/
|
||||
export function mountExcelPreviewImages(container: HTMLElement, images: ExcelDrawingImage[]): void {
|
||||
for (const img of images) {
|
||||
const table = container.querySelector(`#sheet-${img.sheetIndex}`) as HTMLTableElement | null;
|
||||
if (!table) continue;
|
||||
const parent = table.parentElement;
|
||||
if (!parent) continue;
|
||||
parent.style.position = 'relative';
|
||||
|
||||
const tableRect = table.getBoundingClientRect();
|
||||
const point = (anchor: ExcelCellPoint): { x: number; y: number } => {
|
||||
let x = anchor.colOffPx;
|
||||
let y = anchor.rowOffPx;
|
||||
const rowEl = table.rows[Math.min(anchor.row, table.rows.length - 1)];
|
||||
if (rowEl) {
|
||||
y += rowEl.getBoundingClientRect().top - tableRect.top;
|
||||
const cellEl = rowEl.cells[Math.min(anchor.col, rowEl.cells.length - 1)];
|
||||
if (cellEl) {
|
||||
x += cellEl.getBoundingClientRect().left - tableRect.left;
|
||||
}
|
||||
}
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
const from = point(img.from);
|
||||
let width = img.extPx?.width ?? 160;
|
||||
let height = img.extPx?.height ?? 120;
|
||||
if (img.to) {
|
||||
const to = point(img.to);
|
||||
width = Math.max(to.x - from.x, 2);
|
||||
height = Math.max(to.y - from.y, 2);
|
||||
}
|
||||
|
||||
const el = document.createElement('img');
|
||||
el.className = 'excel-preview-image';
|
||||
el.src = img.src;
|
||||
el.alt = '';
|
||||
el.style.position = 'absolute';
|
||||
el.style.left = `${Math.round(from.x)}px`;
|
||||
el.style.top = `${Math.round(from.y)}px`;
|
||||
el.style.width = `${Math.round(width)}px`;
|
||||
el.style.height = `${Math.round(height)}px`;
|
||||
el.style.objectFit = 'fill';
|
||||
el.style.zIndex = '5';
|
||||
parent.appendChild(el);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user