Commit Graph
28 Commits
Author SHA1 Message Date
john-okeefe e448d36641 Fix webtoon pages never loading: drop IntersectionObserver for scroll-driven loading
IO with a shadow-host root never delivered intersections in Chromium
(verified live: pages stayed blank while the section.load→fetch→img
pipeline itself worked fine when probed from outside). Loading is now
driven from the rAF-throttled scroll handler that already tracked the
reading position: a window of [index-2, index+4] loads around the
viewport-center page, with a 'loading' guard against duplicate
in-flight loads. connectedCallback kicks the initial load window.
2026-08-18 08:29:45 -04:00
john-okeefe ea268dffbe Add webtoon (vertical-scroll) renderer for comics
New <foliate-webtoon> custom element: every page stacked in one
scrolling column (max-width 900px centered on wide screens), the
standard long-strip manga reading mode.

- Pages lazy-load through an IntersectionObserver with a 150% root
  margin so they're ready before scrolling into view; placeholders
  carry an estimated min-height until the image loads, then the real
  aspect-ratio — set on the placeholder element — so geometry stays
  stable across unloads and the scrollbar never jumps.
- Pages more than 12 positions from the reading point are unloaded
  (image removed, section blob URL revoked) to bound memory on long
  webtoons; they simply reload if the user scrolls back.
- Relocate events ({reason:'scroll', index, fraction, size:1}) fire on
  rAF-throttled scroll with the viewport-center page as index and the
  visible position within it as fraction — compatible with view.js's
  SectionProgress enrichment, so progress saving/restoring, the
  slider, and the back-stack all work unchanged.
- Renderer contract mirrors fixed-layout: goTo(await {index}) scrolls
  the page into view; next/prev page by ~one screen (view.init()'s
  fresh-start probe is a no-op that reports location); goLeft/goRight
  map to prev/next (vertical flow is direction-independent).
  No zoom/magnifier APIs — the host already gates those on the flow.
- Page images honor --fx-filter from the host for the new
  brightness/contrast/invert controls.

view.js picks the renderer when book.format === 'comic' (now tagged
by makeComicBook) and options.comic.flow === 'webtoon'.
2026-08-18 08:15:59 -04:00
john-okeefe 1c812e8813 Add recenter(): reset pan while keeping the current zoom 2026-08-17 08:40:03 -04:00
john-okeefe 86e234d006 Fix rect hit-test denominator: use the rendered canvas for PDFs
documentElement's screen rect is devicePixelRatio× smaller than the
visible page because pdf.js scales <html> by 1/dpr — using it as the
hit-test denominator made click fractions dpr× too large, so clicks
landed in the wrong place relative to stored (correct) fractions on
any dpr != 1 display. The canvas's post-transform rect is exactly the
visible page and shares the textLayer's transform space.
2026-08-17 08:32:02 -04:00
john-okeefe d0654951b5 Expose the PDF.js document proxy on the book object
book.pdf lets the host drive pdf.js directly (page.getTextContent
for in-book search) without reaching into renderer internals.
2026-08-17 08:02:01 -04:00
john-okeefe 1c0ebf331f Fix rect annotations: host-side overlay instead of in-iframe SVG
The in-iframe SVG overlay was invisible on PDFs for two reasons:

- pdf.js applies transform: scale(1/devicePixelRatio) to the iframe's
  <html>; an overlay inside that document shrinks into the top-left
  corner on any dpr != 1 display. The transform is also applied only
  after the page render, so load-time-injected overlays were sized
  before the scale factor existed.
- Fraction rect geometry itself was correct (selection rects and the
  denominator are both post-transform), but nothing inside the iframe
  can escape its html transform.

Render annotations host-side instead: a div inside the frame's
wrapper element with percentage-positioned children. The wrapper box
always equals the visible page area for both formats — comics (iframe
CSS-scaled inside it) and PDFs (re-rendered at true scale) — so the
overlay is immune to the html transform, zoom re-renders, iframe
scaling, and host pan/zoom, still with zero re-anchoring. The
in-iframe click hit-test is unchanged (it compares fractions against
the same post-transform denominator).
2026-08-17 07:45:52 -04:00
john-okeefe aba68d8723 Rect annotations for fixed-layout: fraction-space overlay + hit-testing
Adds a parallel annotation pipeline for PDF/comic pages (the CFI
overlayer pipeline only exists for the reflowable paginator):

- addRectAnnotation({key, index, rects, color}) /
  removeRectAnnotation(key): rects are page-fraction [x,y,w,h]
  quads, stored per key and rendered into a full-bleed SVG injected
  into the page iframe. The SVG uses viewBox 0 0 100 100 with
  preserveAspectRatio none, so fraction rects stay aligned through
  iframe CSS-zoom (comics), the host transform-based pan/zoom, and
  PDF hi-res re-renders (pdf.js rebuilds canvas/textLayer but not
  body children) — no re-anchoring hooks needed anywhere.
- Frames carry their section index; annotations re-render into each
  freshly created iframe (#showSpread destroys and recreates frames
  on every spread change).
- Clicks are hit-tested against the fraction rects (in iframe
  coordinate space, denominator = img or documentElement bounding
  rect so PDF's devicePixelRatio transform cancels) and emit
  show-rect-annotation with host-space popover coordinates. Skipped
  while a text selection is active so drag-selecting text doesn't
  pop the editor.
- Comic page img is now display:block so the document box equals
  the image box (no inline-baseline gap inflating denominators).
2026-08-16 12:44:22 -04:00
john-okeefe e9e61d885b Touch gestures for fixed-layout: pinch-zoom, pan, swipe paging, double-tap
- Single finger: pan while zoomed; horizontal swipe pages at fit
  (direction mapped through next()/prev() so RTL manga reads
  correctly); drag on PDF text still defers to selection via the
  existing smart-detection (realTarget).
- Two fingers: pinch-zoom around the midpoint (through the shared
  zoom machinery, so PDF re-render scheduling works) plus
  midpoint-pan; lifts back to single-finger pan when one lifts.
- Double-tap: zoom 2.5x at the point / reset to fit.
- Touch events forwarded from page iframes with converted
  coordinates; preventDefault only when the engine actually consumes
  the gesture so native selection/taps stay intact.
- touch-action: none on :host and in comic/pdf page documents so the
  browser does not fight the gesture engine inside iframes.
2026-08-14 15:54:00 -04:00
john-okeefe 29bc958c26 Add 'text' interaction mode for PDF (selection-only, no smart detection)
'select' keeps smart behavior (drag text to select, drag blank to
pan); 'text' always defers to the text/annotation layer so drags
never pan — for users who want pure selection. Shift still force-pans
in both modes; 'pan' remains force-pan.
2026-08-14 14:24:41 -04:00
john-okeefe d4d87a94f8 Avoid redundant render when setting spread before first display 2026-08-13 12:46:11 -04:00
john-okeefe eb9ae699d7 Restore config.pdfjsPath override and options plumbing
Reverts the pdf.js/view.js API change that removed the exported
'config' (pdfjsPath) and the makePDF/open options parameter.
bookhoard overrides config.pdfjsPath to point at its own served
/static/vendor/pdfjs/ assets, so the override + options must stay.
Keep the unrelated external-link href fix in view.js.
2026-08-13 12:43:56 -04:00
john-okeefe d9b1d5d18f Smart PDF pan/select + reactive spread toggle
- In select mode, only defer to the text/annotation layer when the
  pointer is actually on text or a link; otherwise start panning.
  Lets PDF pages be dragged on blank space while keeping text
  selection. Shift and explicit 'pan' mode still force-pan.
- Make the 'spread' attribute reactive: extract #computeSpreads(),
  add #setSpread() which re-groups while preserving the current page.
2026-08-13 12:37:13 -04:00
john-okeefe d016b27752 Fix PDF.js vendor path glob and reformat with consistent style
- Change pdfjsPath template from 'vendor/pdfjs/' to
  './vendor/pdfjs/' so the relative glob resolves correctly
  when the module is bundled with Vite
- Reformat entire file: 2-space indentation, double quotes, semicolons,
  trailing commas, parenthesized arrow function parameters, and aligned
  multi-line call arguments for consistency with the rest of the codebase
2026-04-22 16:28:36 -04:00
john-okeefe 48feeeacad Smooth scroll zoom with rAF accumulation and debounced PDF re-rendering
Previously, each wheel event immediately called #updateFrameScales which
re-renders PDF canvases via onZoom on every tick. This caused visible
jank because canvas re-rendering is expensive and blocks the main thread.

Two improvements:

1. rAF accumulation: wheel events now accumulate zoom deltas and apply
   them once per animation frame via requestAnimationFrame, coalescing
   rapid scroll events into a single transform update. Reduced zoomStep
   from 0.1 to 0.05 for finer granularity.

2. PDF zoom debouncing: during active scroll-zoom, PDF iframes are
   visually scaled via CSS transform without calling onZoom (no canvas
   re-render). After zoom settles (150ms timeout), onZoom is called to
   re-render the canvas at the final resolution for crisp text. The
   #pdfLastRenderedScale field tracks what resolution the canvas was
   last rendered at so CSS scaling is relative to the rendered state.

   Comics continue to call #updateFrameScales every frame since their
   zoom is just a cheap CSS transform with no canvas work.

Timeouts are cleared on page turn, resize, and destroy to prevent
stale re-renders.
2026-04-18 23:52:50 -04:00
john-okeefe fa790c2abb Fix zoom percentage to track relative to fit-page scale
The zoom percentage display had two bugs:
1. Scroll-zoom never updated the status bar percentage because the
   'zoom' event listener was registered inside the magnifier-toggle
   click handler (only added on click, and re-added on each click).
2. After reset (fit-page), the status bar showed '100%' but the
   zoom-in button treated the current scale as 1.0 (absolute), not
   the fit-page scale (e.g. 0.3). This caused a wild zoom jump
   from '100%' to '120%' that was actually a 4x visual change.

Fix by introducing a #baseScale field that captures the fit-page or
fit-width scale whenever the component renders in auto-fit mode. The
new currentScale getter exposes the actual transform scale, and
zoomPercent expresses it as a percentage of baseScale. All zoom-in/
zoom-out handlers (buttons and keyboard) now use currentScale instead
of getAttribute('zoom') || 1, and all percentage displays use
zoomPercent. The zoom event listener is registered once at setup
rather than inside the magnifier toggle handler.

Also removes all diagnostic console.log statements from fixed-layout.js
and reader.js.
2026-04-18 23:04:48 -04:00
john-okeefe 6b39eb3e27 style: reformat epub.js with consistent 2-space indentation, semicolons, and double quotes
No functional changes. Normalizes epub.js to match the formatting style
used throughout the rest of the codebase (2-space indentation, ASI
semicolons, double-quoted strings, trailing commas in multiline).
2026-04-18 23:04:35 -04:00
john-okeefe 285b6711da Fix keyboard 0 not resetting zoom in fixed-layout books
When pressing 0 to reset zoom, the code was calling
removeAttribute('zoom') on the renderer, which removed the DOM
attribute but left the internal zoom/transform state stale. This meant
subsequent zoom operations would compound on the old hidden state.

Replace with the new resetZoom() method that properly clears the
numeric zoom and triggers a clean re-render.
2026-04-18 22:34:10 -04:00
john-okeefe 7ec14df593 Fix panning bugs in FixedLayout zoom/pan mode
Several interrelated fixes for the drag/pan behavior when zoomed in:

- Add dedicated #onResize() handler: numeric zoom rescales frames in
  place (preserving pan position) while fit-page/fit-width does a full
  re-render. Replaces the old bare #render() in the ResizeObserver.

- Add resetZoom() public method that clears the numeric zoom state and
  re-renders, replacing the old removeAttribute('zoom') pattern which
  left stale internal state.

- Guard spread-side sync in #handleMouseUp with !this.#portrait so
  dual-frame logic only runs in landscape spreads, preventing incorrect
  side-switching in portrait mode.

- Guard #updateTransform spread offset with !portrait for the same
  reason — portrait layouts don't have left/right frames.

- Fix #handleMouseDown to return false when declining drag (select mode
  in PDFs) and return true when starting a drag, so the iframe event
  proxy can correctly decide whether to preventDefault.

- Only preventDefault on iframe mousemove when actively dragging or
  magnifier is enabled, allowing normal text selection to work.

- Store zoom level in #zoom during #zoomByRatio and dispatch zoom event
  instead of writing back to the DOM attribute.

- Add debug console.log statements to zoomByRatio and handleWheel for
  tracing transform calculations.
2026-04-18 22:34:03 -04:00
john-okeefe 170352bc71 Fix interaction-mode toggle default icon and tooltip
The toggle button was defaulting to 'Pan Mode' with a plus-icon path,
but the actual default interaction mode is 'select' (the cursor/arrow).
Update the tooltip to 'Select Mode' and replace the SVG path with an
arrow/cursor shape so the icon matches the active mode at startup.
2026-04-18 22:32:44 -04:00
john-okeefe d5b2e3deda Add magnifier, interaction mode toggle, and zoom percentage display
Magnifier (fixed-layout.js):
- Rewrite magnifier to use CSS background-image for comics (blob URLs
  from iframe img elements) and canvas drawImage for PDFs. Replaces
  broken iframe.cloneNode approach that created empty sandboxed clones.
- Detect which iframe is under the cursor by checking bounding rects,
  so magnifier works on both left and right panes.
- Forward mousemove events from iframe documents to handleMagnifierMove
  so the magnifier follows the cursor inside iframes.
- Add background-repeat: no-repeat to lens styles.
- Add zoomMagnifierEnabled getter for external state checks.

Interaction mode toggle (PDF only):
- Add 'interaction-mode' observed attribute with 'select'/'pan' values.
- In select mode (default for PDFs): mouse events pass through for text
  selection; Shift+drag enables panning as a fallback.
- In pan mode: drag-to-pan works as normal.
- Comic books always use pan mode (no text to select).
- Auto-detect PDF via #isPDF flag set in #showSpread from onZoom presence.
- Add isPDF getter so reader.js can show/hide the toggle button.
- Add toggle button in reader.html, hidden by default, shown for PDFs
  via the view 'load' event.
- Escape key dismisses the magnifier.

Zoom percentage display (reader.js):
- Dispatch 'zoom' CustomEvent from #zoomByRatio with the new scale.
- Listener in reader.js updates the percentage display on scroll zoom.

Also includes minor formatting (line wrapping) in #goLeft/#goRight.
2026-04-18 00:39:15 -04:00
john-okeefe 3173cf038d Fix zoom reset (press 0) not disabling frame-to-frame navigation
When removeAttribute('zoom') was called, parseFloat(null) produced NaN,
and typeof NaN === 'number' is true in JS, so #goLeft/#goRight still
entered the zoomed-in dual-pane navigation branch.

Root cause fix: handle null value in attributeChangedCallback by setting
#zoom to undefined before the parseFloat path.

Defense in depth: add isNaN() guards to the zoom checks in #goLeft and
#goRight, matching the pattern already used in #render().
2026-04-17 22:46:04 -04:00
john-okeefe 9c1a007298 Center on focused frame instead of full spread when zoomed in
When a numeric zoom is active and both panes have content, #render()
now centers on the frame indicated by #side rather than centering the
entire spread. This means on page turns the view starts on the correct
frame (left for LTR, right for RTL) instead of the middle of the spread.

For fit-page/fit-width and single-pane views, centering behavior is
unchanged.
2026-04-17 22:33:18 -04:00
john-okeefe 016b93d987 Add image-rendering: high-quality to comic book pages
Ensures browsers use highest-quality interpolation when scaling
raster comic book images during zoom. No effect on browsers that
don't support this value (they fall back to default bilinear).
2026-04-17 21:46:45 -04:00
john-okeefe a369c54b14 Refactor FixedLayout zoom/pan from scroll-based to transform-based model
Replace the overflow:auto + scrollTo zoom approach with a CSS transform
model to fix the scroll-to-zoom cursor targeting bug in dual-pane layouts.

Root cause: flex centering (justify-content:center) and overflow:auto
conflict -- when content fits, flex positions it; when zoomed (overflow),
scrollLeft=0 jumps to the left edge. The zoom-to-cursor formula used
scrollLeft as reference without accounting for the centering offset,
causing systematic drift toward the right pane.

Changes:
- Host CSS: overflow:hidden, display:block, position:relative
- New #wrapper div with transform:translate(x,y) for pan positioning
- New #transform = { x, y, scale } as single source of truth
- #zoomByRatio(cx,cy,ratio) uses panzoom formula: x = cx - ratio*(cx - x)
- #render() centers via transform.x/y = (hostSize - contentSize) / 2
- #updateFrameScales() handles iframe size/scale separately from centering
- Simplified drag: tracks startTX/startTY, updates transform directly
- Simplified attributeChangedCallback: detects external vs internal zoom
  changes and zooms from viewport center for external ones
- Remove all scrollLeft/scrollTop/scrollTo usage
- Remove marginBlock:auto, long-press drag detection, debug console.logs
- Preserve external API: zoom attribute, dragOffset, toggleMagnifier(),
  load/relocate events
2026-04-17 21:33:41 -04:00
john-okeefe bd98d7e185 Add scroll position and source context to zoom/pan event data in FixedLayout
This commit enhances the FixedLayout component by including additional
contextual information when zoom or pan operations occur:

- scrollLeft and scrollTop: Current scroll position of the viewport
- source: Origin of the zoom/pan action (e.g., mouse wheel, pinch zoom, button)
- leftWidth: Width of the left page/panel in dual-page layouts

These parameters provide downstream handlers with complete state information
needed to implement sophisticated zoom behaviors, such as:
- Preserving scroll position during zoom operations
- Differentiating between user-initiated and programmatic zoom changes
- Handling asymmetric layouts with different panel widths

This change is part of the ongoing zoom control implementation for
fixed-layout e-books.
2026-04-17 16:59:26 -04:00
john-okeefe 60332911e6 Fix right iframe zoom and improve pan/drag behavior in fixed-layout e-books
This commit addresses several issues with zoom and pan functionality,
particularly when zooming from the right iframe in a two-page spread:

- Add source iframe tracking to wheel and mouse events
  * Pass frameId parameter through frame creation pipeline
  * Tag events with sourceIframe and sourceFrame properties
  * Enable proper cursor position calculation regardless of event source

- Fix zoom cursor calculation for two-page spreads
  * Calculate cursor position relative to spread viewport, not individual pages
  * Simplify scroll position calculation to work uniformly for both left and right pages
  * Add debug logging for cursor calculation verification

- Improve drag/pan behavior across zoom modes
  * Add draggable state property to control drag availability
  * Handle fit-page mode differently with dragOffset tracking
  * Direct scroll manipulation for zoom levels above 1
  * Add console logging for ignored drag scenarios

- Prevent native image drag interference
  * Set draggable="false" on all images in iframe documents
  * Disable user select and webkit drag on images
  * Prevent default behavior on iframe mouse events

These changes ensure that zoom operations work correctly from both left and
right iframes, maintaining proper cursor focus and scroll position.
2026-04-17 16:56:18 -04:00
john-okeefe 5b822b682b Fix drag offset calculation and scrolling behavior in FixedLayout component
This commit fixes several issues with the drag functionality in the FixedLayout
component to ensure smooth and accurate dragging behavior:

Changes:
- Initialize dragOffset to (0, 0) instead of scroll position when drag starts
- Fix drag offset calculation direction (changed from -= to +=)
- Add proper scroll position updates during drag operations
- Ensure dragOffset is reset to (0, 0) when drag completes

The previous implementation was incorrectly initializing dragOffset with the
current scroll position, which caused the drag offset to compound with scroll
position and led to incorrect rendering. The new approach starts drag offset
at zero and directly updates the scroll position during drag operations.

This ensures that:
1. Drag movements are accurately tracked relative to the drag start point
2. Scroll position is properly synchronized with drag movements
3. Drag state is cleanly reset when drag operations complete
2026-04-17 11:02:26 -04:00
john-okeefe 3f9ab7528b Implement zoom control functionality for fixed-layout e-books
This commit adds comprehensive zoom control capabilities for fixed-layout
e-book content, allowing users to zoom in, out, and reset zoom levels for
better readability and content inspection.

Key features added:
- Zoom control UI with +/- buttons and percentage display
- Keyboard shortcuts for zoom operations (Ctrl/Cmd +, -, 0)
- Mouse wheel zoom with Ctrl/Cmd modifier key
- Drag-to-pan functionality when zoomed in
- Smooth zoom transitions and state management
- Zoom constraints (min/max limits) to prevent over-zooming

Changes include:
- FixedLayout: Enhanced with zoom state management, drag handlers,
  and keyboard/mouse event listeners for intuitive zoom control
- Reader UI: Added zoom control toolbar with visual feedback
- FixedLayout renderer integration with reader zoom controls

The zoom controls provide a seamless experience for users who need to
examine fixed-layout content more closely or adjust content size for
their preferred reading experience.
2026-04-16 21:37:54 -04:00