Compare commits

...

14 Commits

Author SHA1 Message Date
b43baccd62 v2.2.3
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 20:34:27 +00:00
035c6ab621 fix(contentinvoice): Use shared translation.TranslationKey type in DeContentInvoice.translateKey and remove local import 2025-12-11 20:34:27 +00:00
3617caec1f 2.2.2
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 20:06:34 +00:00
9e879893af 2.2.1
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 20:05:08 +00:00
c487ac341e v2.2.0
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 20:00:56 +00:00
393a235526 feat(viewer): Add pagination metadata and thumbnail offset rendering for viewer thumbnails 2025-12-11 20:00:56 +00:00
52b215b9d3 v2.1.1
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 19:16:12 +00:00
34278c4b04 fix(viewer): Improve sidebar resizing UX and update deps 2025-12-11 19:16:12 +00:00
6726969010 v2.1.0
Some checks failed
Default (tags) / security (push) Failing after 0s
Default (tags) / test (push) Failing after 0s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-11 16:56:30 +00:00
8a434d3ba9 feat(viewer): Add smooth zoom and scroll animations to viewer 2025-12-11 16:56:30 +00:00
560f4d667a make scroll listener passive 2025-12-11 15:19:49 +00:00
382af070fc update 2025-12-11 15:14:23 +00:00
de464461e6 add page scrolling 2025-12-11 14:58:19 +00:00
f86aebc00b update 2025-12-11 14:55:20 +00:00
10 changed files with 762 additions and 41 deletions

1
.npmrc
View File

@@ -1 +0,0 @@
registry=https://registry.npmjs.org/

View File

@@ -1,5 +1,41 @@
# Changelog
## 2025-12-11 - 2.2.3 - fix(contentinvoice)
Use shared translation.TranslationKey type in DeContentInvoice.translateKey and remove local import
- Replaced local TranslationKey import with plugins.shared.translation.TranslationKey to ensure type consistency
- Updated DeContentInvoice.translateKey parameter type to reference the shared translation type
- Removed an unused type import from ts_web/elements/contentinvoice.ts
## 2025-12-11 - 2.2.0 - feat(viewer)
Add pagination metadata and thumbnail offset rendering for viewer thumbnails
- Expose per-page pagination metadata (IPagePaginationInfo) from DeDocument during rendering (pageNumber, startOffset, contentLength).
- DeDocument now collects pagination info while paginating and dispatches a 'pagination-complete' CustomEvent with pageCount and paginationInfo (bubbled & composed).
- DeContentInvoice: add renderStartOffset and renderContentLength properties and applyOffsetTrimming to support rendering trimmed content (used for thumbnails).
- DeDocumentViewer: listen for 'pagination-complete', store paginationInfo, and render thumbnail previews by mounting DeContentInvoice instances with precomputed offsets to produce accurate thumbnails.
- Viewer: wire thumbnail generation to use per-page offsets so thumbnails show exactly the content slice for each page.
- Demo data: extended demo invoice items in ts_shared/demoletter.ts to better exercise pagination and thumbnail rendering.
- Remove registry override from .npmrc (previously pointed to registry.npmjs.org).
## 2025-12-11 - 2.1.1 - fix(viewer)
Improve sidebar resizing UX and update deps
- Add smooth width transition for the thumbnail sidebar to improve resize visuals
- Disable viewport CSS transitions while user is actively resizing the sidebar to avoid janky animations
- Mark viewport as resizing in classes so layout updates skip transitions during drag
- Make sidebar resize mousemove listener passive to improve scrolling/interaction performance
- Bump @design.estate/dees-wcctools to ^2.0.0 and @git.zone/tswatch to ^2.3.11
## 2025-12-11 - 2.1.0 - feat(viewer)
Add smooth zoom and scroll animations to viewer
- Introduce smooth zoom animation: new private animateZoomTo(targetZoom, duration) method and zoomAnimationId to track/cancel running animations
- Animate transitions for numeric zoom presets and zoom step changes (handleZoomStep now uses animateZoomTo)
- Cancel ongoing zoom animation when user manipulates the zoom slider
- Make fit-to-width and fit-to-page calculations optionally animate (calculateFitWidth/ calculateFitPage accept animate flag)
- Add animated scrolling helper animateScrollTo for smooth page scrolling when requested (used when smooth=true)
## 2025-12-11 - 2.0.6 - fix(DeDocumentViewer)
Account for toolbar and padding when calculating Fit Page zoom in viewer

View File

@@ -1,6 +1,6 @@
{
"name": "@design.estate/dees-document",
"version": "2.0.6",
"version": "2.2.3",
"private": false,
"description": "A sophisticated framework for dynamically generating and rendering business documents like invoices with modern web technologies, featuring PDF creation, templating, and automation.",
"main": "dist_ts_web/index.js",
@@ -24,7 +24,7 @@
"@design.estate/dees-catalog": "^3.3.0",
"@design.estate/dees-domtools": "^2.3.6",
"@design.estate/dees-element": "^2.1.3",
"@design.estate/dees-wcctools": "^1.3.0",
"@design.estate/dees-wcctools": "^2.0.0",
"@git.zone/tsrun": "^2.0.0",
"@push.rocks/smartfile": "^13.1.0",
"@push.rocks/smartfs": "^1.2.0",
@@ -42,7 +42,7 @@
"@git.zone/tsbuild": "^3.1.2",
"@git.zone/tsbundle": "^2.6.3",
"@git.zone/tstest": "^3.1.3",
"@git.zone/tswatch": "^2.3.10",
"@git.zone/tswatch": "^2.3.11",
"@push.rocks/projectinfo": "^5.0.2"
},
"files": [

29
pnpm-lock.yaml generated
View File

@@ -18,8 +18,8 @@ importers:
specifier: ^2.1.3
version: 2.1.3
'@design.estate/dees-wcctools':
specifier: ^1.3.0
version: 1.3.0
specifier: ^2.0.0
version: 2.0.0
'@git.zone/tsrun':
specifier: ^2.0.0
version: 2.0.0
@@ -67,8 +67,8 @@ importers:
specifier: ^3.1.3
version: 3.1.3(@push.rocks/smartserve@1.4.0)(socks@2.8.7)(typescript@5.9.3)
'@git.zone/tswatch':
specifier: ^2.3.10
version: 2.3.10(@tiptap/pm@2.27.1)
specifier: ^2.3.11
version: 2.3.11(@tiptap/pm@2.27.1)
'@push.rocks/projectinfo':
specifier: ^5.0.2
version: 5.0.2
@@ -304,6 +304,9 @@ packages:
'@design.estate/dees-wcctools@1.3.0':
resolution: {integrity: sha512-+yd8c1gTIKNRQYCvG0xu6Am8dHsRm7ymluX2gnoBQN4aFOpZgIBi/v9CvGyPhTD1p/VRouIBz1wsUCejnwrFCA==}
'@design.estate/dees-wcctools@2.0.0':
resolution: {integrity: sha512-+JXzU/FzOs48NcynbozX0lPfvszhp0mODdZU2ECCTkwOQi+0smhYAlFTUNZ8JcWSLDq3g5HqRMv7XoJELMk4Zw==}
'@emnapi/core@1.7.1':
resolution: {integrity: sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg==}
@@ -509,8 +512,8 @@ packages:
resolution: {integrity: sha512-t+/cKV21JHK8X7NGAmihs5M/eMm+V+jn4R5rzfwGG97WJFAcP5qE1Os9VYtyZw3tx/NZXA2yA4abo/ELluTuRA==}
hasBin: true
'@git.zone/tswatch@2.3.10':
resolution: {integrity: sha512-88bdzD15mYoG0T0AUTg8ATNkV/dN5ecqfiYcQRX1gJHmLrE2yqymFGkb0W0/xWgpcRakc08V+wRbSI7pqg+EOQ==}
'@git.zone/tswatch@2.3.11':
resolution: {integrity: sha512-FJWOsPQ9i0INn1i7uqMD0ECrZ6bwwGQC8oFDEx9PLcaS+qHpGsYj3P9UscpW1N78P+6Yd1WFUfBh9sUQiKm+KA==}
hasBin: true
'@happy-dom/global-registrator@15.11.7':
@@ -5002,6 +5005,18 @@ snapshots:
- supports-color
- vue
'@design.estate/dees-wcctools@2.0.0':
dependencies:
'@design.estate/dees-domtools': 2.3.6
'@design.estate/dees-element': 2.1.3
'@push.rocks/smartdelay': 3.0.5
lit: 3.3.1
transitivePeerDependencies:
- '@nuxt/kit'
- react
- supports-color
- vue
'@emnapi/core@1.7.1':
dependencies:
'@emnapi/wasi-threads': 1.1.0
@@ -5230,7 +5245,7 @@ snapshots:
- utf-8-validate
- vue
'@git.zone/tswatch@2.3.10(@tiptap/pm@2.27.1)':
'@git.zone/tswatch@2.3.11(@tiptap/pm@2.27.1)':
dependencies:
'@api.global/typedserver': 7.11.1(@tiptap/pm@2.27.1)
'@git.zone/tsbundle': 2.6.3

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@design.estate/dees-document',
version: '2.0.6',
version: '2.2.3',
description: 'A sophisticated framework for dynamically generating and rendering business documents like invoices with modern web technologies, featuring PDF creation, templating, and automation.'
}

View File

@@ -237,6 +237,86 @@ export const demoLetter: plugins.tsclass.finance.TInvoice = {
vatPercentage: 0,
position: 20,
},
{
name: "Consulting Services",
unitQuantity: 5,
unitNetPrice: 150,
unitType: "hours",
vatPercentage: 19,
position: 21,
},
{
name: "Development Work",
unitQuantity: 12,
unitNetPrice: 120,
unitType: "hours",
vatPercentage: 19,
position: 22,
},
{
name: "Project Management",
unitQuantity: 3,
unitNetPrice: 180,
unitType: "hours",
vatPercentage: 19,
position: 23,
},
{
name: "Technical Support",
unitQuantity: 8,
unitNetPrice: 90,
unitType: "hours",
vatPercentage: 7,
position: 24,
},
{
name: "Documentation",
unitQuantity: 4,
unitNetPrice: 75,
unitType: "hours",
vatPercentage: 7,
position: 25,
},
{
name: "Code Review",
unitQuantity: 6,
unitNetPrice: 110,
unitType: "hours",
vatPercentage: 19,
position: 26,
},
{
name: "Testing & QA",
unitQuantity: 10,
unitNetPrice: 95,
unitType: "hours",
vatPercentage: 19,
position: 27,
},
{
name: "Infrastructure Setup",
unitQuantity: 2,
unitNetPrice: 250,
unitType: "hours",
vatPercentage: 19,
position: 28,
},
{
name: "Training Session",
unitQuantity: 4,
unitNetPrice: 200,
unitType: "hours",
vatPercentage: 7,
position: 29,
},
{
name: "Maintenance Package",
unitQuantity: 1,
unitNetPrice: 500,
unitType: "units",
vatPercentage: 19,
position: 30,
},
],
};

View File

@@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@design.estate/dees-document',
version: '2.0.6',
version: '2.2.3',
description: 'A sophisticated framework for dynamically generating and rendering business documents like invoices with modern web technologies, featuring PDF creation, templating, and automation.'
}

View File

@@ -15,7 +15,6 @@ import {
import * as plugins from "../plugins.js";
import { dedocumentSharedStyle } from "../style.js";
import type { TranslationKey } from "../../ts_shared/translation.js";
declare global {
interface HTMLElementTagNameMap {
@@ -49,6 +48,13 @@ export class DeContentInvoice extends DeesElement {
})
accessor documentSettings: plugins.shared.interfaces.IDocumentSettings;
// Offset-based rendering properties for thumbnails
@property({ type: Number })
accessor renderStartOffset: number = null;
@property({ type: Number })
accessor renderContentLength: number = null;
constructor() {
super();
domtools.DomTools.setupDomTools();
@@ -296,7 +302,7 @@ export class DeContentInvoice extends DeesElement {
}
}
public translateKey(key: TranslationKey): string {
public translateKey(key: plugins.shared.translation.TranslationKey): string {
return plugins.shared.translation.translate(
this.documentSettings.languageCode,
key
@@ -307,7 +313,29 @@ export class DeContentInvoice extends DeesElement {
_changedProperties: Map<string | number | symbol, unknown>
) {
super.firstUpdated(_changedProperties);
this.attachInvoiceDom();
await this.attachInvoiceDom();
// Apply offset-based trimming if specified (used for thumbnails)
if (this.renderStartOffset !== null && this.renderContentLength !== null) {
await this.applyOffsetTrimming();
}
}
/**
* Apply pre-computed pagination offsets for thumbnail rendering
*/
private async applyOffsetTrimming(): Promise<void> {
// Trim from start
if (this.renderStartOffset > 0) {
await this.trimStartToOffset(this.renderStartOffset);
}
// Trim from end to match content length
let currentLength = await this.getContentLength();
while (currentLength > this.renderContentLength) {
await this.trimEndByOne();
currentLength = await this.getContentLength();
}
}
private renderPaymentTerms(): TemplateResult {

View File

@@ -26,6 +26,12 @@ import { DeContentInvoice } from "./contentinvoice.js";
import { demoFunc } from "./document.demo.js";
export interface IPagePaginationInfo {
pageNumber: number;
startOffset: number;
contentLength: number;
}
declare global {
interface HTMLElementTagNameMap {
"dedocument-dedocument": DeDocument;
@@ -142,10 +148,12 @@ export class DeDocument extends DeesElement {
null;
public latestRenderedLetterData: plugins.tsclass.business.TLetter = null;
public cleanupStore: any[] = [];
public paginationInfo: IPagePaginationInfo[] = [];
public async renderDocument() {
this.latestDocumentSettings = this.documentSettings;
this.latestRenderedLetterData = this.letterData;
this.paginationInfo = [];
const cleanUpStoreCurrentRender = [];
const cleanUpStoreNextRender = [];
@@ -198,7 +206,16 @@ export class DeDocument extends DeesElement {
newPageOverflows = await newPage.checkOverflow();
}
currentContentOffset = await currentContent.getContentLength();
const pageStartOffset = overallContentOffset;
overallContentOffset = overallContentOffset + currentContentOffset;
// Track pagination info for this page
this.paginationInfo.push({
pageNumber: pageCounter,
startOffset: pageStartOffset,
contentLength: currentContentOffset,
});
if (trimmed === 0) {
complete = true;
}
@@ -234,6 +251,16 @@ export class DeDocument extends DeesElement {
}
}
this.adjustDePageScaling();
// Emit event with pagination info for thumbnails
this.dispatchEvent(new CustomEvent('pagination-complete', {
detail: {
pageCount: pageCounter,
paginationInfo: this.paginationInfo,
},
bubbles: true,
composed: true,
}));
}
async updated(

View File

@@ -11,7 +11,9 @@ import {
type TemplateResult,
} from "@design.estate/dees-element";
import { demoFunc } from "./viewer.demo.js";
import { DeDocument } from "./document.js";
import { DeDocument, type IPagePaginationInfo } from "./document.js";
import "./page.js"; // Import DePage for thumbnail rendering
import "./contentinvoice.js"; // Import DeContentInvoice for thumbnail content
import "@design.estate/dees-catalog";
@@ -88,6 +90,28 @@ export class DeDocumentViewer extends DeesElement {
@state()
accessor displayZoom: number = 100;
@state()
accessor currentPageDisplay: string = "1 / 1";
// Sidebar state
@state()
accessor showThumbnails: boolean = true;
@state()
accessor sidebarWidth: number = 140;
@state()
accessor isResizingSidebar: boolean = false;
@state()
accessor thumbnailPages: number[] = [];
@state()
accessor paginationInfo: IPagePaginationInfo[] = [];
// Zoom animation
private zoomAnimationId: number | null = null;
public static styles = [
cssManager.defaultStyles,
css`
@@ -104,6 +128,125 @@ export class DeDocumentViewer extends DeesElement {
--dropdown-shadow: ${cssManager.bdTheme("0 4px 16px rgba(0,0,0,0.15)", "0 4px 16px rgba(0,0,0,0.4)")};
--slider-track: ${cssManager.bdTheme("#ddd", "#444")};
--slider-fill: ${cssManager.bdTheme("#0066cc", "#4d9fff")};
--sidebar-min-width: 100px;
--sidebar-max-width: 300px;
}
/* Sidebar Styles */
.sidebar {
position: absolute;
left: 0;
top: var(--toolbar-height);
bottom: 0;
background: var(--toolbar-bg);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-right: 1px solid var(--toolbar-border);
display: flex;
flex-direction: column;
z-index: 50;
box-sizing: border-box;
transition: width 0.2s ease;
}
.sidebar--collapsed {
width: 0 !important;
overflow: hidden;
border-right: none;
}
.sidebar--resizing {
transition: none !important;
user-select: none;
}
.sidebar__header {
padding: 10px 12px;
font-size: 11px;
font-weight: 600;
color: var(--text-secondary);
border-bottom: 1px solid var(--toolbar-border);
text-transform: uppercase;
letter-spacing: 0.5px;
flex-shrink: 0;
}
.sidebar__thumbnails {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
padding: 8px;
display: flex;
flex-direction: column;
gap: 12px;
}
.thumbnail {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
cursor: pointer;
padding: 4px;
border-radius: 6px;
transition: background 0.15s ease;
flex-shrink: 0;
}
.thumbnail:hover {
background: var(--button-hover);
}
.thumbnail--active {
background: var(--button-active);
}
.thumbnail--active .thumbnail__preview {
outline: 2px solid var(--accent-color);
outline-offset: 2px;
}
.thumbnail__preview {
width: 100%;
aspect-ratio: 210 / 297;
background: ${cssManager.bdTheme("#fff", "#2a2a2a")};
box-shadow: ${cssManager.bdTheme("0 1px 4px rgba(0,0,0,0.15)", "0 1px 4px rgba(0,0,0,0.4)")};
border-radius: 2px;
overflow: hidden;
position: relative;
}
.thumbnail__label {
font-size: 11px;
color: var(--text-secondary);
font-weight: 500;
}
.sidebar__resize-handle {
position: absolute;
top: 0;
right: -4px;
bottom: 0;
width: 8px;
cursor: ew-resize;
background: transparent;
z-index: 60;
}
.sidebar__resize-handle::after {
content: '';
position: absolute;
top: 0;
left: 3px;
bottom: 0;
width: 2px;
background: transparent;
transition: background 0.15s ease;
}
.sidebar__resize-handle:hover::after,
.sidebar--resizing .sidebar__resize-handle::after {
background: var(--accent-color);
}
.maincontainer {
@@ -194,7 +337,7 @@ export class DeDocumentViewer extends DeesElement {
color: var(--text-primary);
font-size: 13px;
font-weight: 500;
min-width: 80px;
width: 90px; /* Fixed width to prevent reflow - fits "Fit Width" */
justify-content: space-between;
transition: all 0.15s ease;
}
@@ -322,6 +465,25 @@ export class DeDocumentViewer extends DeesElement {
gap: 2px;
}
.fit-buttons {
display: flex;
align-items: center;
gap: 2px;
}
.page-nav {
display: flex;
align-items: center;
gap: 2px;
}
.page-indicator {
font-size: 12px;
color: var(--text-secondary);
min-width: 45px;
text-align: center;
}
.spacing-slider-container {
display: flex;
align-items: center;
@@ -391,6 +553,15 @@ export class DeDocumentViewer extends DeesElement {
overflow-y: scroll;
overflow-x: auto;
overscroll-behavior: contain;
transition: left 0.2s ease;
}
.viewport--resizing {
transition: none !important;
}
.viewport--with-sidebar {
left: var(--current-sidebar-width, 140px);
}
.viewport--centered {
@@ -407,12 +578,25 @@ export class DeDocumentViewer extends DeesElement {
.spacing-slider-container {
display: none;
}
/* Collapse sidebar by default on tablet */
.sidebar {
width: 0 !important;
}
.sidebar--collapsed {
width: 0 !important;
}
.viewport--with-sidebar {
left: 0 !important;
}
`),
// Phone styles
cssManager.cssForPhone(css`
.zoom-slider-container {
display: none;
}
.fit-buttons {
display: none;
}
.spacing-label {
display: none;
}
@@ -428,13 +612,31 @@ export class DeDocumentViewer extends DeesElement {
.controls__section {
gap: 2px;
}
/* Hide sidebar and toggle on phone */
.sidebar {
display: none !important;
}
.sidebar-toggle {
display: none !important;
}
.viewport--with-sidebar {
left: 0 !important;
}
`),
];
public render(): TemplateResult {
const viewportClasses = [
"viewport",
this.zoomMode !== "auto" ? "viewport--centered" : "",
this.showThumbnails ? "viewport--with-sidebar" : "",
this.isResizingSidebar ? "viewport--resizing" : "",
].filter(Boolean).join(" ");
return html`
<div class="maincontainer">
<div class="viewport ${this.zoomMode !== "auto" ? "viewport--centered" : ""}">
<div class="maincontainer" style="--current-sidebar-width: ${this.sidebarWidth}px;">
${this.renderSidebar()}
<div class="${viewportClasses}">
${this.letterData
? html`
<dedocument-dedocument
@@ -455,9 +657,86 @@ export class DeDocumentViewer extends DeesElement {
`;
}
private renderSidebar(): TemplateResult {
const sidebarClasses = [
"sidebar",
!this.showThumbnails ? "sidebar--collapsed" : "",
this.isResizingSidebar ? "sidebar--resizing" : "",
].filter(Boolean).join(" ");
const thumbnailScale = this.getThumbnailScale();
const currentPage = this.getCurrentPage();
return html`
<div class="${sidebarClasses}" style="width: ${this.sidebarWidth}px;">
<div class="sidebar__header">Pages</div>
<div class="sidebar__thumbnails">
${this.thumbnailPages.map((_, i) => {
const pageInfo = this.paginationInfo[i];
return html`
<div
class="thumbnail ${currentPage === i + 1 ? "thumbnail--active" : ""}"
@click=${() => this.scrollToPage(i + 1)}
>
<div
class="thumbnail__preview"
style="--thumbnail-scale: ${thumbnailScale};"
>
<div style="
width: ${plugins.shared.A4_WIDTH}px;
height: ${plugins.shared.A4_HEIGHT}px;
transform: scale(${thumbnailScale});
transform-origin: top left;
pointer-events: none;
">
<dedocument-page
.letterData=${this.letterData}
.documentSettings=${this.documentSettings}
.pageNumber=${i + 1}
.pageTotalNumber=${this.thumbnailPages.length}
>${pageInfo ? html`
<dedocument-contentinvoice
.letterData=${this.letterData as unknown as plugins.tsclass.finance.TInvoice}
.documentSettings=${this.documentSettings}
.renderStartOffset=${pageInfo.startOffset}
.renderContentLength=${pageInfo.contentLength}
></dedocument-contentinvoice>
` : null}</dedocument-page>
</div>
</div>
<span class="thumbnail__label">${i + 1}</span>
</div>
`;
})}
</div>
<div
class="sidebar__resize-handle"
@mousedown=${this.startSidebarResize}
></div>
</div>
`;
}
private getThumbnailScale(): number {
const previewWidth = this.sidebarWidth - 24; // Account for padding
return previewWidth / plugins.shared.A4_WIDTH;
}
private renderZoomControls(): TemplateResult {
return html`
<div class="controls__section">
<!-- Sidebar Toggle Button -->
<button
class="controls__button sidebar-toggle ${this.showThumbnails ? "controls__button--active" : ""}"
@click=${() => this.toggleThumbnails()}
title="Toggle Thumbnails"
>
<dees-icon icon="lucide:panelLeft"></dees-icon>
</button>
<div class="controls__divider sidebar-toggle"></div>
<!-- Zoom Out Button -->
<button
class="controls__button"
@@ -501,6 +780,29 @@ export class DeDocumentViewer extends DeesElement {
<div class="controls__divider"></div>
<!-- Fit Buttons -->
<div class="fit-buttons">
<!-- Fit Width Button -->
<button
class="controls__button ${this.zoomMode === "fit-width" ? "controls__button--active" : ""}"
@click=${() => this.handleZoomPreset("fit-width")}
title="Fit Width"
>
<dees-icon icon="lucide:arrowLeftRight"></dees-icon>
</button>
<!-- Fit Page Button -->
<button
class="controls__button ${this.zoomMode === "fit-page" ? "controls__button--active" : ""}"
@click=${() => this.handleZoomPreset("fit-page")}
title="Fit Page"
>
<dees-icon icon="lucide:expand"></dees-icon>
</button>
</div>
<div class="controls__divider"></div>
<!-- Zoom Slider -->
<div class="zoom-slider-container">
<input
@@ -553,6 +855,27 @@ export class DeDocumentViewer extends DeesElement {
<div class="controls__divider"></div>
<!-- Page Navigation -->
<div class="page-nav">
<button
class="controls__button"
@click=${() => this.handlePreviousPage()}
title="Previous Page"
>
<dees-icon icon="lucide:chevronUp"></dees-icon>
</button>
<span class="page-indicator">${this.currentPageDisplay}</span>
<button
class="controls__button"
@click=${() => this.handleNextPage()}
title="Next Page"
>
<dees-icon icon="lucide:chevronDown"></dees-icon>
</button>
</div>
<div class="controls__divider"></div>
<!-- Print Button -->
<button
class="controls__button"
@@ -604,31 +927,69 @@ export class DeDocumentViewer extends DeesElement {
this.updateDisplayZoom();
} else if (value === "fit-width") {
// Calculate zoom to fit page width to viewport width
this.calculateFitWidth();
this.calculateFitWidth(true);
} else if (value === "fit-page") {
// Calculate zoom to fit entire page in viewport
this.calculateFitPage();
this.calculateFitPage(true);
} else {
this.zoomLevel = value;
this.displayZoom = value;
// Animate to numeric preset
this.animateZoomTo(value);
}
}
private handleZoomStep(delta: number): void {
const current = this.zoomLevel ?? this.displayZoom;
const newZoom = Math.min(400, Math.max(25, current + delta));
this.zoomLevel = newZoom;
this.displayZoom = newZoom;
this.animateZoomTo(newZoom);
this.zoomMode = newZoom;
}
private handleZoomSlider(e: Event): void {
// Cancel any running animation when user takes manual control
if (this.zoomAnimationId !== null) {
cancelAnimationFrame(this.zoomAnimationId);
this.zoomAnimationId = null;
}
const value = parseInt((e.target as HTMLInputElement).value, 10);
this.zoomLevel = value;
this.displayZoom = value;
this.zoomMode = value;
}
/**
* Animate zoom level to target value
* @param targetZoom - Target zoom percentage
* @param duration - Animation duration in ms (default: 200)
*/
private animateZoomTo(targetZoom: number, duration: number = 200): void {
// Cancel any existing animation
if (this.zoomAnimationId !== null) {
cancelAnimationFrame(this.zoomAnimationId);
}
const startZoom = this.zoomLevel ?? this.displayZoom;
const startTime = performance.now();
const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);
const animate = (currentTime: number) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easeOutCubic(progress);
const currentZoom = startZoom + (targetZoom - startZoom) * easedProgress;
this.zoomLevel = Math.round(currentZoom);
this.displayZoom = this.zoomLevel;
if (progress < 1) {
this.zoomAnimationId = requestAnimationFrame(animate);
} else {
this.zoomAnimationId = null;
}
};
this.zoomAnimationId = requestAnimationFrame(animate);
}
private handleSpacingPreset(value: number): void {
this.pageGap = value;
}
@@ -637,6 +998,65 @@ export class DeDocumentViewer extends DeesElement {
this.pageGap = parseInt((e.target as HTMLInputElement).value, 10);
}
// ============================================
// SIDEBAR METHODS
// ============================================
private startSidebarResize(e: MouseEvent): void {
e.preventDefault();
this.isResizingSidebar = true;
const startX = e.clientX;
const startWidth = this.sidebarWidth;
const onMouseMove = (moveEvent: MouseEvent) => {
const delta = moveEvent.clientX - startX;
const newWidth = Math.min(300, Math.max(100, startWidth + delta));
this.sidebarWidth = newWidth;
};
const onMouseUp = () => {
this.isResizingSidebar = false;
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseup", onMouseUp);
document.body.style.cursor = "";
document.body.style.userSelect = "";
};
document.addEventListener("mousemove", onMouseMove, { passive: true });
document.addEventListener("mouseup", onMouseUp);
document.body.style.cursor = "ew-resize";
document.body.style.userSelect = "none";
}
private updateThumbnailPages(): void {
const pageCount = this.getPageCount();
if (pageCount !== this.thumbnailPages.length) {
this.thumbnailPages = Array.from({ length: pageCount }, (_, i) => i);
}
}
private handlePreviousPage(): void {
const current = this.getCurrentPage();
if (current > 1) {
this.scrollToPage(current - 1);
}
}
private handleNextPage(): void {
const current = this.getCurrentPage();
const total = this.getPageCount();
if (current < total) {
this.scrollToPage(current + 1);
}
}
private updatePageIndicator(): void {
const current = this.getCurrentPage();
const total = this.getPageCount();
this.currentPageDisplay = `${current} / ${total || 1}`;
}
private async handlePrint(): Promise<void> {
// Create a print-specific container - hidden on screen, visible only in print
const printContainer = document.createElement("div");
@@ -723,19 +1143,24 @@ export class DeDocumentViewer extends DeesElement {
setTimeout(cleanup, 100);
}
private calculateFitWidth(): void {
private calculateFitWidth(animate: boolean = false): void {
const viewport = this.shadowRoot?.querySelector(".viewport");
if (!viewport) return;
// Account for padding and scrollbar width
const viewportWidth = viewport.clientWidth - 32 - 16;
const scale = viewportWidth / plugins.shared.A4_WIDTH;
const targetZoom = Math.round(scale * 100);
this.zoomLevel = Math.round(scale * 100);
this.displayZoom = this.zoomLevel;
if (animate) {
this.animateZoomTo(targetZoom);
} else {
this.zoomLevel = targetZoom;
this.displayZoom = targetZoom;
}
}
private calculateFitPage(): void {
private calculateFitPage(animate: boolean = false): void {
const viewport = this.shadowRoot?.querySelector(".viewport");
if (!viewport) return;
@@ -750,9 +1175,14 @@ export class DeDocumentViewer extends DeesElement {
const scaleByHeight = viewportHeight / plugins.shared.A4_HEIGHT;
const scaleByWidth = viewportWidth / plugins.shared.A4_WIDTH;
const scale = Math.min(scaleByHeight, scaleByWidth);
const targetZoom = Math.round(scale * 100);
this.zoomLevel = Math.round(scale * 100);
this.displayZoom = this.zoomLevel;
if (animate) {
this.animateZoomTo(targetZoom);
} else {
this.zoomLevel = targetZoom;
this.displayZoom = targetZoom;
}
}
private updateDisplayZoom(): void {
@@ -771,8 +1201,16 @@ export class DeDocumentViewer extends DeesElement {
super.updated(changedProperties);
if (changedProperties.has("letterData")) {
// Update display zoom after document renders
setTimeout(() => this.updateDisplayZoom(), 100);
// Update display zoom, page indicator, and thumbnails after document renders
setTimeout(() => {
this.updateDisplayZoom();
this.updatePageIndicator();
this.updateThumbnailPages();
}, 100);
// Additional delay to ensure all pages are rendered
setTimeout(() => {
this.updateThumbnailPages();
}, 500);
}
}
@@ -791,9 +1229,19 @@ export class DeDocumentViewer extends DeesElement {
setTimeout(() => this.updateDisplayZoom(), 200);
}
// Handle viewport resize to update display zoom in auto mode
// Listen for pagination-complete event from DeDocument
this.addEventListener('pagination-complete', (e: CustomEvent) => {
this.paginationInfo = e.detail.paginationInfo;
const pageCount = e.detail.pageCount;
if (pageCount !== this.thumbnailPages.length) {
this.thumbnailPages = Array.from({ length: pageCount }, (_, i) => i);
}
});
// Handle viewport resize and scroll
const viewport = this.shadowRoot?.querySelector(".viewport");
if (viewport) {
// Resize observer for zoom updates
const resizeObserver = new ResizeObserver(() => {
if (this.zoomMode === "auto" || this.zoomMode === "fit-width") {
this.updateDisplayZoom();
@@ -801,7 +1249,22 @@ export class DeDocumentViewer extends DeesElement {
});
resizeObserver.observe(viewport);
this.registerGarbageFunction(() => resizeObserver.disconnect());
// Scroll listener for page indicator and thumbnail highlighting
const scrollHandler = () => {
this.updatePageIndicator();
// Trigger re-render to update active thumbnail
this.requestUpdate();
};
viewport.addEventListener("scroll", scrollHandler, { passive: true });
this.registerGarbageFunction(() => viewport.removeEventListener("scroll", scrollHandler));
}
// Initial page indicator and thumbnail update
setTimeout(() => {
this.updatePageIndicator();
this.updateThumbnailPages();
}, 300);
}
// ============================================
@@ -896,27 +1359,100 @@ export class DeDocumentViewer extends DeesElement {
* @param smooth - Whether to use smooth scrolling (default: true)
*/
public scrollToPage(pageNumber: number, smooth: boolean = true): void {
const viewport = this.shadowRoot?.querySelector(".viewport");
const doc = this.shadowRoot?.querySelector("dedocument-dedocument");
if (!doc) return;
if (!viewport || !doc) return;
const pages = doc.shadowRoot?.querySelectorAll("dedocument-page");
if (!pages || pages.length === 0) return;
const targetIndex = Math.min(Math.max(0, pageNumber - 1), pages.length - 1);
const targetPage = pages[targetIndex];
const targetPage = pages[targetIndex] as HTMLElement;
if (targetPage) {
targetPage.scrollIntoView({
behavior: smooth ? "smooth" : "instant",
block: "start",
});
// Calculate scroll position relative to viewport
// Account for the document's position within the viewport
const docRect = doc.getBoundingClientRect();
const pageRect = targetPage.getBoundingClientRect();
const pageOffsetFromDoc = pageRect.top - docRect.top;
// Scroll to the page position with fast custom animation
if (smooth) {
this.animateScrollTo(viewport, pageOffsetFromDoc, 250);
} else {
viewport.scrollTop = pageOffsetFromDoc;
}
}
}
/**
* Animate scroll to target position
* @param element - The scrollable element
* @param targetTop - Target scroll position
* @param duration - Animation duration in ms (default: 150)
*/
private animateScrollTo(element: Element, targetTop: number, duration: number = 150): void {
const startTop = element.scrollTop;
const distance = targetTop - startTop;
const startTime = performance.now();
const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3);
const step = (currentTime: number) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easeOutCubic(progress);
element.scrollTop = startTop + distance * easedProgress;
if (progress < 1) {
requestAnimationFrame(step);
}
};
requestAnimationFrame(step);
}
/**
* Trigger the print dialog
*/
public async print(): Promise<void> {
await this.handlePrint();
}
/**
* Toggle the thumbnails sidebar visibility
*/
public toggleThumbnails(): void {
this.showThumbnails = !this.showThumbnails;
}
/**
* Set whether the thumbnails sidebar is visible
* @param visible - Whether the sidebar should be visible
*/
public setThumbnailsVisible(visible: boolean): void {
this.showThumbnails = visible;
}
/**
* Get whether the thumbnails sidebar is visible
*/
public getThumbnailsVisible(): boolean {
return this.showThumbnails;
}
/**
* Set the sidebar width
* @param width - Width in pixels (100-300)
*/
public setSidebarWidth(width: number): void {
this.sidebarWidth = Math.min(300, Math.max(100, width));
}
/**
* Get the current sidebar width
*/
public getSidebarWidth(): number {
return this.sidebarWidth;
}
}