Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
259 changes: 232 additions & 27 deletions dist/docx-preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -9313,7 +9313,7 @@ section.${c}>ol>li::before {
if (this.options.responsive) {
styleText += `
.${c}-wrapper { padding: 8px; }
section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing: border-box; }
section.${c}:not([data-docxjs-thumbnail]) { width: auto !important; max-width: 100%; min-width: 0; box-sizing: border-box; }
.${c} img { max-width: 100%; height: auto; }
.${c} table { max-width: 100%; table-layout: auto; }
@media (max-width: 768px) {
Expand Down Expand Up @@ -11749,6 +11749,16 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
}
return null;
}
function cloneWithout(root, shouldSkip) {
const clone = root.cloneNode(false);
for (let i = 0; i < root.childNodes.length; i++) {
const child = root.childNodes[i];
if (!shouldSkip(child)) {
clone.appendChild(cloneWithout(child, shouldSkip));
}
}
return clone;
}
function ensureStyle(doc, className, activeClassName) {
const head = doc.head;
if (!head)
Expand All @@ -11765,8 +11775,11 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
margin: 0.5rem auto;
cursor: pointer;
outline: none;
user-select: none;
-webkit-user-select: none; /* Safari */
}
.${className}-thumbnail:focus-visible .${className}-thumbnail-preview {
.${className}-thumbnail:not(.${activeClassName}):hover .${className}-thumbnail-preview,
.${className}-thumbnail:not(.${activeClassName}):focus-visible .${className}-thumbnail-preview {
box-shadow: 0 0 0 2px #4a90e2, 0 0 10px rgba(0, 0, 0, 0.5);
}
.${className}-thumbnail-preview {
Expand All @@ -11776,6 +11789,8 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
box-sizing: content-box;
border: 2px solid transparent;
position: relative;
display: inherit;
flex-direction: inherit;
}
.${className}-thumbnail-label {
font-size: 0.75rem;
Expand All @@ -11787,6 +11802,20 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
.${activeClassName} .${className}-thumbnail-preview {
border-color: #4a90e2;
}
.${className}-thumbnail-loading {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.${className}-thumbnail-spinner {
width: 18px;
height: 18px;
border: 2px solid rgba(0,0,0,.15);
border-top-color: #4a90e2;
border-radius: 50%;
}
`;
head.appendChild(style);
}
Expand Down Expand Up @@ -11824,7 +11853,7 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
}];
}
const cs = win?.getComputedStyle(section);
if (cs && cs.position === 'static') {
if (cs?.position === 'static') {
section.style.position = 'relative';
}
const pages = [];
Expand Down Expand Up @@ -11853,6 +11882,36 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
}
return pages;
}
function createThumbnailContent(preview, section, topOffset, width, pageWidth) {
const clone = cloneWithout(section, node => node instanceof Element &&
node.hasAttribute("data-docxjs-page-anchor"));
clone.setAttribute('aria-hidden', 'true');
clone.setAttribute('data-docxjs-thumbnail', '');
clone.removeAttribute('id');
clone.style.boxShadow = 'none';
clone.style.margin = '0';
clone.style.flexShrink = '0';
let scale = 1;
if (pageWidth > 0) {
clone.style.width = `${pageWidth}px`;
scale = width / pageWidth;
}
const translate = -topOffset * scale;
clone.style.transform = `translateY(${translate}px) scale(${scale})`;
clone.style.transformOrigin = '0 0';
preview.replaceChildren(clone);
}
function isFullyVisible(thumb, root) {
const thumbRect = thumb.getBoundingClientRect();
const doc = thumb.ownerDocument;
const viewport = root?.getBoundingClientRect() ?? {
top: 0,
bottom: doc.defaultView?.innerHeight ??
doc.documentElement.clientHeight,
};
return (thumbRect.top >= viewport.top &&
thumbRect.bottom <= viewport.bottom);
}
function renderThumbnails(mainContainer, thumbnailContainer, options) {
const width = options?.width ?? 120;
const showPageNumbers = options?.showPageNumbers ?? true;
Expand All @@ -11863,7 +11922,7 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
ensureStyle(mainContainer.ownerDocument, className, activeClassName);
thumbnailContainer.innerHTML = '';
const sections = Array.from(mainContainer.querySelectorAll(`section.${className}`));
const splitterRan = mainContainer.querySelector(`section[${VISUAL_PAGE_MARKER}]`) !== null;
const splitterRan = sections.some(section => section.hasAttribute(VISUAL_PAGE_MARKER));
const pages = [];
for (const section of sections) {
const sectionPages = splitterRan
Expand All @@ -11874,8 +11933,94 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
}
}
const pairs = [];
const renderQueue = [];
let rendering = false;
let cancelScheduledRender;
const scheduleRender = (callback) => {
if ("requestIdleCallback" in globalThis) {
const id = requestIdleCallback(callback, { timeout: 250 });
return () => cancelIdleCallback(id);
}
const id = requestAnimationFrame(callback);
return () => cancelAnimationFrame(id);
};
const enqueue = (preview) => {
if (renderQueue.includes(preview)) {
return;
}
renderQueue.push(preview);
processQueue();
};
const processQueue = () => {
if (rendering || !renderQueue.length) {
return;
}
rendering = true;
const preview = renderQueue.shift();
if (!preview.isConnected) {
rendering = false;
processQueue();
return;
}
const page = pages[Number(preview.dataset.pageIndex)];
cancelScheduledRender = scheduleRender(() => {
cancelScheduledRender = undefined;
createThumbnailContent(preview, page.section, page.topOffset, width, page.pageWidth);
delete preview.dataset.rendered;
delete preview.dataset.pageIndex;
rendering = false;
processQueue();
});
};
let thumbObserver = null;
const thumbnailScrollRoot = findScrollingAncestor(thumbnailContainer);
const IO = (win ?? globalThis).IntersectionObserver;
if (IO) {
thumbObserver = new IO((entries) => {
for (const entry of entries) {
const preview = entry.target;
const thumb = preview.firstElementChild;
if (!entry.isIntersecting) {
if (thumb) {
thumb.style.display = "none";
}
continue;
}
if (thumb) {
thumb.style.display = "";
continue;
}
if (preview.dataset.rendered !== "false") {
continue;
}
const loading = doc.createElement("div");
loading.className = `${className}-thumbnail-loading`;
const spinner = doc.createElement("div");
spinner.className = `${className}-thumbnail-spinner`;
spinner.animate([
{ transform: "rotate(0deg)" },
{ transform: "rotate(360deg)" },
], {
duration: 800,
iterations: Infinity,
easing: "linear",
});
loading.appendChild(spinner);
preview.appendChild(loading);
preview.dataset.rendered = "";
enqueue(preview);
}
}, {
root: thumbnailScrollRoot,
rootMargin: "200px 0px",
threshold: 0
});
}
let suppressAutoScroll = false;
const fragment = doc.createDocumentFragment();
const scrollRoot = findScrollingAncestor(mainContainer);
for (let i = 0; i < pages.length; i++) {
const { section, scrollTarget, topOffset, pageWidth, pageHeight } = pages[i];
const { scrollTarget, pageWidth, pageHeight } = pages[i];
const pageNum = i + 1;
const thumb = doc.createElement('div');
thumb.className = `${className}-thumbnail`;
Expand All @@ -11885,12 +12030,6 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
thumb.dataset.page = String(pageNum);
const preview = doc.createElement('div');
preview.className = `${className}-thumbnail-preview`;
const clone = section.cloneNode(true);
clone.setAttribute('aria-hidden', 'true');
clone.removeAttribute('id');
clone.style.boxShadow = 'none';
clone.style.margin = '0';
clone.style.flexShrink = '0';
let scale = 1;
let previewHeight = 0;
if (pageWidth > 0) {
Expand All @@ -11901,10 +12040,8 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
if (previewHeight > 0) {
preview.style.height = `${previewHeight}px`;
}
const translate = -topOffset * scale;
clone.style.transform = `translateY(${translate}px) scale(${scale})`;
clone.style.transformOrigin = '0 0';
preview.appendChild(clone);
preview.dataset.pageIndex = String(i);
preview.dataset.rendered = "false";
thumb.appendChild(preview);
if (showPageNumbers) {
const label = doc.createElement('div');
Expand All @@ -11913,40 +12050,93 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
thumb.appendChild(label);
}
const goTo = () => {
suppressAutoScroll = true;
scrollTarget.scrollIntoView({ behavior: 'smooth', block: 'start' });
};
thumb.addEventListener('click', goTo);
thumb.addEventListener('keydown', (ev) => {
const ke = ev;
if (ke.key === 'Enter' || ke.key === ' ') {
ke.preventDefault();
if (ev.key === 'Enter' || ev.key === ' ') {
ev.preventDefault();
goTo();
}
});
thumbnailContainer.appendChild(thumb);
fragment.appendChild(thumb);
thumbObserver?.observe(preview);
pairs.push({ scrollTarget, thumb });
}
thumbnailContainer.appendChild(fragment);
const scrollTarget = scrollRoot ?? doc;
let scrollEndTimer;
const onScrollEnd = () => {
suppressAutoScroll = false;
scrollEndTimer = undefined;
};
const onScroll = () => {
if (scrollEndTimer !== undefined) {
clearTimeout(scrollEndTimer);
}
scrollEndTimer = setTimeout(onScrollEnd, 100);
};
let removeScrollListener;
if ("onscrollend" in scrollTarget) {
scrollTarget.addEventListener("scrollend", onScrollEnd, { passive: true });
removeScrollListener = () => scrollTarget.removeEventListener("scrollend", onScrollEnd);
}
else {
scrollTarget.addEventListener("scroll", onScroll, { passive: true });
removeScrollListener = () => scrollTarget.removeEventListener("scroll", onScroll);
}
let observer = null;
const IO = win?.IntersectionObserver ??
globalThis.IntersectionObserver;
let activeThumbnail = -1;
if (IO && pairs.length > 0) {
const scrollRoot = findScrollingAncestor(mainContainer);
const visibility = new Map();
let activeIdx = -1;
observer = new IO((entries) => {
let needsUpdate = false;
for (const entry of entries) {
visibility.set(entry.target, entry.intersectionRatio);
const r = entry.intersectionRatio;
const target = entry.target;
visibility.set(target, r);
if (needsUpdate) {
continue;
}
const activeTarget = pairs[activeIdx].scrollTarget;
if (activeIdx === -1 ||
activeTarget === target ||
r > (visibility.get(activeTarget) ?? 0)) {
needsUpdate = true;
}
}
if (!needsUpdate) {
return;
}
let bestIdx = -1;
let bestRatio = -1;
for (let i = 0; i < pairs.length; i++) {
for (let i = 0, bestRatio = 0; i < pairs.length; i++) {
const r = visibility.get(pairs[i].scrollTarget) ?? 0;
if (r > bestRatio) {
bestRatio = r;
bestIdx = i;
}
}
for (let i = 0; i < pairs.length; i++) {
pairs[i].thumb.classList.toggle(activeClassName, i === bestIdx && bestRatio > 0);
if (bestIdx !== activeIdx) {
if (activeIdx !== -1) {
pairs[activeIdx].thumb.classList.remove(activeClassName);
}
if (bestIdx !== -1) {
pairs[bestIdx].thumb.classList.add(activeClassName);
}
activeIdx = bestIdx;
}
if (bestIdx !== activeThumbnail && bestIdx >= 0) {
activeThumbnail = bestIdx;
const { thumb } = pairs[bestIdx];
if (!suppressAutoScroll && !isFullyVisible(thumb, thumbnailScrollRoot)) {
thumb.scrollIntoView({
behavior: "smooth",
block: "nearest",
inline: "nearest"
});
}
}
}, {
root: scrollRoot,
Expand All @@ -11958,11 +12148,26 @@ section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing
}
return {
dispose() {
removeScrollListener();
if (scrollEndTimer !== undefined) {
clearTimeout(scrollEndTimer);
scrollEndTimer = undefined;
}
if (cancelScheduledRender !== undefined) {
cancelScheduledRender();
cancelScheduledRender = undefined;
}
if (observer) {
observer.disconnect();
observer = null;
}
if (thumbObserver) {
thumbObserver.disconnect();
thumbObserver = null;
}
thumbnailContainer.innerHTML = '';
renderQueue.length = 0;
rendering = false;
for (const section of sections) {
section.querySelectorAll('[data-docxjs-page-anchor]').forEach(n => n.remove());
}
Expand Down
2 changes: 1 addition & 1 deletion dist/docx-preview.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
},
"devDependencies": {
"@playwright/test": "^1.59.1",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-terser": "^1.0.0",
"@rollup/plugin-typescript": "^12.1.4",
"diff": "^8.0.2",
"jsdom": "^29.1.1",
Expand Down
2 changes: 1 addition & 1 deletion src/html-renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1667,7 +1667,7 @@ section.${c}>ol>li::before {
// single-character column on a phone.
styleText += `
.${c}-wrapper { padding: 8px; }
section.${c} { width: auto !important; max-width: 100%; min-width: 0; box-sizing: border-box; }
section.${c}:not([data-docxjs-thumbnail]) { width: auto !important; max-width: 100%; min-width: 0; box-sizing: border-box; }
.${c} img { max-width: 100%; height: auto; }
.${c} table { max-width: 100%; table-layout: auto; }
@media (max-width: 768px) {
Expand Down
Loading