feat: 新增docx文档预览带大纲的组件

master
3 days ago
parent 1bbce06b9e
commit 710e1d117b

@ -0,0 +1,626 @@
<template>
<div class="fa-docx-preview">
<!-- 左侧大纲 -->
<aside :class="['outline-sidebar', { collapsed: !outlineVisible }]">
<div class="outline-header">
<div class="outline-title-wrap">
<ElIcon><Document /></ElIcon>
<span class="outline-title">页面大纲</span>
</div>
<ElButton
class="outline-toggle-btn"
link
type="primary"
:icon="Fold"
title="收起大纲"
@click="outlineVisible = false"
/>
</div>
<div v-loading="outlineLoading" class="outline-body">
<ul v-if="outlineItems.length" ref="outlineListRef" class="outline-list">
<li
v-for="item in outlineItems"
:key="item.id"
:ref="(el) => setOutlineItemRef(el as HTMLElement, item.id)"
:class="[
'outline-item',
`outline-level-${Math.min(item.level, 6)}`,
{ active: activeId === item.id },
]"
:title="item.text"
@click="handleOutlineClick(item)"
>
<span class="outline-item-text">{{ item.text }}</span>
<span
v-if="!readonly"
class="outline-item-actions"
@click.stop
>
<slot name="outline-item-action" :item="item" :active="activeId === item.id">
<ElButton
link
size="small"
type="primary"
:icon="Plus"
class="add-icon-btn"
title="添加规则关联"
@click="(e: MouseEvent) => { e.stopPropagation(); emit('add-annotation', item); }"
/>
</slot>
</span>
</li>
</ul>
<ElEmpty
v-else-if="!outlineLoading && !outlineError"
description="暂无大纲"
:image-size="60"
/>
<div v-if="outlineError" class="outline-error">
<ElIcon><WarningFilled /></ElIcon>
<span>大纲解析失败</span>
</div>
</div>
</aside>
<!-- 收起后的展开按钮 -->
<button
v-if="!outlineVisible"
type="button"
class="outline-expand-btn"
@click="outlineVisible = true"
>
<ElIcon><Expand /></ElIcon>
<span>大纲</span>
</button>
<!-- 中间预览 -->
<div
ref="mainRef"
class="docx-viewer-main"
v-loading="outlineLoading || viewerLoading"
element-loading-text="正在加载文档..."
>
<FileViewer
v-if="buffer"
ref="viewerRef"
:file="buffer"
:filename="filename"
:options="options"
@load-complete="handleLoadComplete"
@zoom-change="handleZoomChange"
style="height: 100%"
/>
<div v-else-if="!outlineLoading" class="empty-preview">
<ElEmpty description="请上传 docx 文件以预览" :image-size="80" />
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, shallowRef, computed, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import { Fold, Expand, WarningFilled, Plus, Document } from "@element-plus/icons-vue";
import allPreset from "@file-viewer/preset-all";
import { FileViewer } from "@file-viewer/vue3";
import { useDocxOutline, type DocxOutlineItem } from "./useDocxOutline";
defineOptions({ name: "FaDocxPreview" });
interface Props {
/** docx 文件 url 或 ArrayBuffer */
src?: string | ArrayBuffer | null;
filename?: string;
/** 只读模式:不显示添加按钮 */
readonly?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
src: null,
filename: "",
readonly: false,
});
const emit = defineEmits<{
(e: "ready", payload: { outline: DocxOutlineItem[] }): void;
(e: "heading-click", item: DocxOutlineItem): void;
(e: "add-annotation", item: DocxOutlineItem): void;
(e: "active-change", id: string): void;
}>();
const {
outline: outlineItems,
buffer,
loading: outlineLoading,
error: outlineError,
filename: inferredFilename,
load,
} = useDocxOutline();
const filename = computedFilename();
const options = {
preset: allPreset,
rendererMode: "replace" as const,
theme: "light" as const,
toolbar: { position: "bottom-right" as const },
};
function computedFilename() {
return inferredFilename.value || props.filename || "document.docx";
}
const viewerRef = ref<any>(null);
const mainRef = ref<HTMLElement | null>(null);
const outlineListRef = ref<HTMLElement | null>(null);
const outlineVisible = ref(true);
const activeId = ref<string>("");
/** FileViewer 渲染中的 loadingbuffer 已就绪但未触发 load-complete */
const viewerLoading = ref(false);
const headingElements = shallowRef<Array<{ item: DocxOutlineItem; el: HTMLElement }>>([]);
let headingPositions: Array<{ id: string; top: number }> = [];
const outlineItemRefs = new Map<string, HTMLElement>();
let rafId: number | null = null;
let scrollTarget: HTMLElement | null = null;
let resizeDebounceTimer: ReturnType<typeof setTimeout> | null = null;
function setOutlineItemRef(el: HTMLElement | null, id: string) {
if (el) {
outlineItemRefs.set(id, el);
} else {
outlineItemRefs.delete(id);
}
}
function getScrollContainer(): HTMLElement | null {
const fromApi = viewerRef.value?.getScrollContainer?.();
if (fromApi instanceof HTMLElement) return fromApi;
const root = mainRef.value;
if (!root) return null;
const candidates = root.querySelectorAll<HTMLElement>("*");
for (let i = 0; i < candidates.length; i++) {
const el = candidates[i];
if (!el) continue;
const style = getComputedStyle(el);
if (
(style.overflowY === "auto" || style.overflowY === "scroll") &&
el.scrollHeight > el.clientHeight
) {
return el;
}
}
return root;
}
function queryParagraphs(): HTMLElement[] {
const sc = getScrollContainer();
const roots: ParentNode[] = [];
if (sc) {
roots.push(sc);
if (sc.shadowRoot) roots.push(sc.shadowRoot);
}
if (mainRef.value) {
roots.push(mainRef.value);
if (mainRef.value.shadowRoot) roots.push(mainRef.value.shadowRoot);
}
for (const root of roots) {
const ps = root.querySelectorAll<HTMLElement>(
".docx-wrapper p, .docx p, article p"
);
if (ps.length) return Array.from(ps);
}
return [];
}
function normalizeText(s: string): string {
return (s || "").replace(/\s+/g, " ").trim();
}
function matchOutlineToDom() {
const items = outlineItems.value;
if (!items.length) {
headingElements.value = [];
headingPositions = [];
return;
}
const paragraphs = queryParagraphs();
if (!paragraphs.length) return;
const matched: Array<{ item: DocxOutlineItem; el: HTMLElement }> = [];
let outlineIdx = 0;
for (let i = 0; i < paragraphs.length && outlineIdx < items.length; i++) {
const p = paragraphs[i];
if (!p) continue;
const pText = normalizeText(p.textContent || "");
if (!pText) continue;
const target = items[outlineIdx];
if (!target) break;
if (
pText === target.text ||
pText.startsWith(target.text) ||
target.text.startsWith(pText)
) {
p.dataset.outlineId = target.id;
matched.push({ item: target, el: p });
outlineIdx++;
}
}
headingElements.value = matched;
refreshHeadingPositions();
attachScrollSpy();
}
function refreshHeadingPositions() {
const sc = getScrollContainer();
const matched = headingElements.value;
if (!sc || !matched.length) {
headingPositions = [];
return;
}
const containerTop = sc.getBoundingClientRect().top;
const containerScroll = sc.scrollTop;
const positions = matched.map(({ item, el }) => ({
id: item.id,
top: el.getBoundingClientRect().top - containerTop + containerScroll,
}));
positions.sort((a, b) => a.top - b.top);
headingPositions = positions;
}
function onScroll() {
if (rafId !== null) return;
rafId = requestAnimationFrame(() => {
rafId = null;
updateActiveHeading();
});
}
function updateActiveHeading() {
const sc = scrollTarget;
if (!sc || !headingPositions.length) return;
const threshold = sc.clientHeight * 0.2;
const target = sc.scrollTop + threshold;
let lo = 0;
let hi = headingPositions.length - 1;
let result = 0;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
const pos = headingPositions[mid];
if (pos && pos.top <= target) {
result = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
const next = headingPositions[result]?.id;
if (next && next !== activeId.value) {
activeId.value = next;
scrollOutlineItemIntoView(next);
emit("active-change", next);
}
}
function scrollOutlineItemIntoView(id: string) {
const el = outlineItemRefs.get(id);
if (!el || !outlineListRef.value) return;
const container = outlineListRef.value;
const elTop = el.offsetTop;
const elBottom = elTop + el.offsetHeight;
const viewTop = container.scrollTop;
const viewBottom = viewTop + container.clientHeight;
if (elTop < viewTop) {
container.scrollTo({ top: Math.max(0, elTop - 8), behavior: "smooth" });
} else if (elBottom > viewBottom) {
container.scrollTo({
top: elBottom - container.clientHeight + 8,
behavior: "smooth",
});
}
}
function attachScrollSpy() {
const sc = getScrollContainer();
if (!sc) return;
if (scrollTarget === sc) return;
detachScrollSpy();
scrollTarget = sc;
sc.addEventListener("scroll", onScroll, { passive: true });
updateActiveHeading();
}
function detachScrollSpy() {
if (scrollTarget) {
scrollTarget.removeEventListener("scroll", onScroll);
scrollTarget = null;
}
if (rafId !== null) {
cancelAnimationFrame(rafId);
rafId = null;
}
}
/** 外部调用:滚动到指定大纲项 */
function scrollToHeading(id: string) {
const sc = getScrollContainer();
if (!sc) return;
const pos = headingPositions.find((p) => p.id === id);
if (pos) {
activeId.value = id;
sc.scrollTo({ top: Math.max(0, pos.top - 16), behavior: "smooth" });
scrollOutlineItemIntoView(id);
return;
}
const matched = headingElements.value.find((h) => h.item.id === id);
if (matched) {
activeId.value = id;
matched.el.scrollIntoView({ block: "start", behavior: "smooth" });
}
}
/** 外部调用:根据 id 获取大纲项 */
function getOutlineItem(id: string): DocxOutlineItem | undefined {
return outlineItems.value.find((i) => i.id === id);
}
/** 外部调用:获取所有大纲项 */
function getOutlineItems(): DocxOutlineItem[] {
return outlineItems.value;
}
function handleOutlineClick(item: DocxOutlineItem) {
emit("heading-click", item);
scrollToHeading(item.id);
}
function handleLoadComplete() {
viewerLoading.value = false;
nextTick(() => {
matchOutlineToDom();
emit("ready", { outline: outlineItems.value });
});
}
function handleZoomChange() {
if (resizeDebounceTimer) clearTimeout(resizeDebounceTimer);
resizeDebounceTimer = setTimeout(() => {
refreshHeadingPositions();
updateActiveHeading();
}, 200);
}
function handleResize() {
if (resizeDebounceTimer) clearTimeout(resizeDebounceTimer);
resizeDebounceTimer = setTimeout(() => {
refreshHeadingPositions();
updateActiveHeading();
}, 200);
}
watch(
() => props.src,
async (v) => {
viewerLoading.value = false;
if (v) {
await load(v, props.filename || undefined);
} else {
headingElements.value = [];
headingPositions = [];
outlineItems.value = [];
buffer.value = null;
}
},
{ immediate: true }
);
// buffer FileViewer loading
watch(buffer, (v) => {
if (v) {
viewerLoading.value = true;
} else {
viewerLoading.value = false;
}
});
watch(outlineVisible, (visible) => {
if (visible) {
nextTick(() => {
refreshHeadingPositions();
updateActiveHeading();
});
}
});
onMounted(() => {
window.addEventListener("resize", handleResize, { passive: true });
});
onBeforeUnmount(() => {
window.removeEventListener("resize", handleResize);
detachScrollSpy();
if (resizeDebounceTimer) clearTimeout(resizeDebounceTimer);
outlineItemRefs.clear();
});
defineExpose({
scrollToHeading,
getOutlineItem,
getOutlineItems,
activeId,
outlineItems,
});
</script>
<style lang="scss" scoped>
.fa-docx-preview {
display: flex;
height: 100%;
width: 100%;
background: #f5f6f8;
overflow: hidden;
}
.outline-sidebar {
display: flex;
flex-direction: column;
width: 260px;
min-width: 260px;
max-width: 260px;
height: 100%;
border-right: 1px solid #e4e7ed;
background: #fff;
transition: width 0.2s ease, min-width 0.2s ease, max-width 0.2s ease;
overflow: hidden;
}
.outline-sidebar.collapsed {
width: 0;
min-width: 0;
max-width: 0;
border-right: none;
}
.outline-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 12px 8px;
border-bottom: 1px solid #ebeef5;
}
.outline-title-wrap {
display: flex;
align-items: center;
gap: 6px;
color: #606266;
}
.outline-title {
font-size: 14px;
font-weight: 600;
color: #303133;
}
.outline-toggle-btn {
padding: 4px;
}
.outline-body {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 4px 0 12px;
}
.outline-list {
list-style: none;
margin: 0;
padding: 0;
}
.outline-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 12px;
cursor: pointer;
font-size: 13px;
line-height: 1.5;
color: #606266;
border-left: 2px solid transparent;
transition: background 0.15s, color 0.15s, border-color 0.15s;
overflow: hidden;
&:hover {
background: #ecf5ff;
color: #409eff;
.outline-item-actions {
opacity: 1;
}
}
&.active {
background: #ecf5ff;
color: #409eff;
border-left-color: #409eff;
font-weight: 600;
}
}
.outline-item-text {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.outline-item-actions {
display: flex;
align-items: center;
gap: 2px;
opacity: 0;
flex-shrink: 0;
margin-left: 4px;
.add-icon-btn {
padding: 2px;
font-size: 14px;
}
}
.outline-level-1 {
padding-left: 16px;
font-weight: 600;
}
.outline-level-2 { padding-left: 28px; }
.outline-level-3 { padding-left: 40px; }
.outline-level-4 {
padding-left: 52px;
font-size: 12px;
}
.outline-level-5 {
padding-left: 64px;
font-size: 12px;
}
.outline-level-6 {
padding-left: 76px;
font-size: 12px;
}
.outline-error {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
padding: 24px 12px;
font-size: 12px;
color: #909399;
}
.outline-expand-btn {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 4px;
width: 28px;
min-width: 28px;
height: 100%;
border: none;
border-right: 1px solid #e4e7ed;
background: #f5f7fa;
cursor: pointer;
color: #606266;
font-size: 11px;
transition: background 0.15s, color 0.15s;
&:hover {
background: #ecf5ff;
color: #409eff;
}
}
.docx-viewer-main {
flex: 1;
min-width: 0;
height: 100%;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.empty-preview {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
</style>

@ -0,0 +1,246 @@
/**
* docx composable
*
* @file-viewer/vue3 使 docx-preview docx <p>
* collectDocumentAnchors
* "标题级" JSZip docx DOMParser
* word/document.xml Heading / outlineLvl
*
* WPS / Word <w:pStyle w:val="..."/> 使 styleId
* "2""3" word/styles.xml styles.xml
* styleId
*/
import { ref, shallowRef, type Ref, type ShallowRef } from "vue";
import JSZip from "jszip";
export interface DocxOutlineItem {
/** 唯一 id同时会作为渲染后 <p> 上的 data-outline-id */
id: string;
/** 标题层级 1-9 */
level: number;
/** 标题文本 */
text: string;
}
export interface UseDocxOutlineResult {
/** 大纲条目(按文档顺序) */
outline: Ref<DocxOutlineItem[]>;
/** 解析得到的 docx ArrayBuffer可直接喂给 <file-viewer :file> 复用,避免二次请求 */
buffer: ShallowRef<ArrayBuffer | null>;
/** 解析中的 loading */
loading: Ref<boolean>;
/** 解析错误 */
error: Ref<Error | null>;
/** 文件名(从 url 推断或外部传入) */
filename: Ref<string>;
/** 加载并解析 docxsrc 可为 urlstring或 ArrayBuffer */
load: (src: string | ArrayBuffer, name?: string) => Promise<void>;
}
const HEADING_STYLE_RE = /^heading[\s_-]?([1-9])$/i;
const HEADING_STYLE_CN_RE = /^标题\s?([1-9])$/;
const W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
function getAttr(el: Element, localName: string): string {
const ns = el.getAttributeNS(W_NS, localName);
if (ns) return ns;
return el.getAttribute(`w:${localName}`) || "";
}
function getHeadingLevelByName(name: string | null | undefined): number {
if (!name) return 0;
let m = HEADING_STYLE_RE.exec(name);
if (m) return Number(m[1]);
m = HEADING_STYLE_CN_RE.exec(name);
if (m) return Number(m[1]);
return 0;
}
function paragraphText(p: Element): string {
const ts = p.getElementsByTagNameNS(W_NS, "t");
let text = "";
for (let i = 0; i < ts.length; i++) {
const node = ts[i];
if (node) text += node.textContent || "";
}
return text.replace(/\s+/g, " ").trim();
}
interface StyleEntry {
styleId: string;
name: string;
basedOn: string;
outlineLvl: number | null;
}
function parseStylesXml(stylesXml: string): Map<string, StyleEntry> {
const doc = new DOMParser().parseFromString(stylesXml, "application/xml");
const styleEls = doc.getElementsByTagNameNS(W_NS, "style");
const map = new Map<string, StyleEntry>();
for (let i = 0; i < styleEls.length; i++) {
const style = styleEls[i];
if (!style) continue;
const type = getAttr(style, "type");
if (type !== "paragraph") continue;
const styleId = getAttr(style, "styleId");
if (!styleId) continue;
const nameEl = style.getElementsByTagNameNS(W_NS, "name")[0];
const name = nameEl ? getAttr(nameEl, "val") : "";
const basedOnEl = style.getElementsByTagNameNS(W_NS, "basedOn")[0];
const basedOn = basedOnEl ? getAttr(basedOnEl, "val") : "";
const outlineLvlEl = style.getElementsByTagNameNS(W_NS, "outlineLvl")[0];
let outlineLvl: number | null = null;
if (outlineLvlEl) {
const val = Number(getAttr(outlineLvlEl, "val"));
if (Number.isFinite(val)) outlineLvl = val;
}
map.set(styleId, { styleId, name, basedOn, outlineLvl });
}
return map;
}
function buildStyleHeadingMap(stylesXml: string): Map<string, number> {
const entries = parseStylesXml(stylesXml);
const resolved = new Map<string, number>();
function resolve(styleId: string, visited: Set<string>): number {
const cached = resolved.get(styleId);
if (cached !== undefined) return cached;
if (visited.has(styleId)) return 0;
const entry = entries.get(styleId);
if (!entry) return 0;
visited.add(styleId);
if (entry.outlineLvl !== null) {
if (entry.outlineLvl >= 0 && entry.outlineLvl <= 8) {
const level = entry.outlineLvl + 1;
resolved.set(styleId, level);
return level;
}
resolved.set(styleId, 0);
return 0;
}
const byName = getHeadingLevelByName(entry.name);
if (byName > 0) {
resolved.set(styleId, byName);
return byName;
}
if (entry.basedOn) {
const inherited = resolve(entry.basedOn, visited);
if (inherited > 0) {
resolved.set(styleId, inherited);
return inherited;
}
}
resolved.set(styleId, 0);
return 0;
}
for (const id of entries.keys()) {
resolve(id, new Set());
}
return resolved;
}
export function parseDocxOutline(
documentXml: string,
styleHeadingMap?: Map<string, number>
): DocxOutlineItem[] {
const doc = new DOMParser().parseFromString(documentXml, "application/xml");
const paragraphs = doc.getElementsByTagNameNS(W_NS, "p");
const items: DocxOutlineItem[] = [];
for (let i = 0; i < paragraphs.length; i++) {
const p = paragraphs[i];
if (!p) continue;
const pPr = p.getElementsByTagNameNS(W_NS, "pPr")[0];
if (!pPr) continue;
let level = 0;
const pStyle = pPr.getElementsByTagNameNS(W_NS, "pStyle")[0];
if (pStyle) {
const styleVal = getAttr(pStyle, "val");
if (styleVal) {
if (styleHeadingMap && styleHeadingMap.has(styleVal)) {
level = styleHeadingMap.get(styleVal) || 0;
} else {
level = getHeadingLevelByName(styleVal);
}
}
}
if (level === 0) {
const outlineLvl = pPr.getElementsByTagNameNS(W_NS, "outlineLvl")[0];
if (outlineLvl) {
const val = Number(getAttr(outlineLvl, "val"));
if (Number.isFinite(val) && val >= 0 && val <= 8) {
level = val + 1;
}
}
}
if (level === 0) continue;
const text = paragraphText(p);
if (!text) continue;
items.push({
id: `docx-outline-${items.length + 1}`,
level,
text,
});
}
return items;
}
export function useDocxOutline(): UseDocxOutlineResult {
const outline = ref<DocxOutlineItem[]>([]);
const buffer = shallowRef<ArrayBuffer | null>(null);
const loading = ref(false);
const error = ref<Error | null>(null);
const filename = ref<string>("");
async function parseBuffer(arrayBuffer: ArrayBuffer, name?: string) {
if (name) filename.value = name;
const zip = await JSZip.loadAsync(arrayBuffer);
const documentFile = zip.file("word/document.xml");
if (!documentFile) {
throw new Error("docx 包内未找到 word/document.xml");
}
const documentXml = await documentFile.async("string");
const stylesFile = zip.file("word/styles.xml");
const stylesXml = stylesFile ? await stylesFile.async("string") : "";
const styleHeadingMap = stylesXml
? buildStyleHeadingMap(stylesXml)
: new Map<string, number>();
outline.value = parseDocxOutline(documentXml, styleHeadingMap);
}
async function load(src: string | ArrayBuffer, name?: string): Promise<void> {
loading.value = true;
error.value = null;
outline.value = [];
buffer.value = null;
try {
if (typeof src === "string") {
const url = src;
if (!name) {
const u = url.split("/").pop() || "";
filename.value = decodeURIComponent(u.split("?")[0] || "document.docx");
} else {
filename.value = name;
}
const resp = await fetch(url);
if (!resp.ok) {
throw new Error(`加载 docx 失败:${resp.status} ${resp.statusText}`);
}
const arrayBuffer = await resp.arrayBuffer();
buffer.value = arrayBuffer;
await parseBuffer(arrayBuffer, filename.value);
} else {
buffer.value = src;
filename.value = name || "document.docx";
await parseBuffer(src, filename.value);
}
} catch (e: any) {
error.value = e instanceof Error ? e : new Error(String(e));
outline.value = [];
} finally {
loading.value = false;
}
}
return { outline, buffer, loading, error, filename, load };
}
Loading…
Cancel
Save