Components Data display

PDF flipbook

Turn the pages of a PDF, inspect a spread, or find a passage by searching the publication.

Live previewGo + JavaScript
Negative Space Open original PDF

Usage

Set Title and PDFURL to a same-origin PDF or a URL that permits cross-origin access. For an instant preview, supply ordered Pages with ImageURL, Title and searchable Text. Optional Alt, Width and Height describe each page image. The reader opens on the cover and uses a spread on wide screens. Drag a page sideways to turn it, or ease it back and release to stay on the same page. You can also use the arrow keys or enter a page number. When reduced motion is enabled, pages change instantly. AllowOpen lets visitors open or drop a PDF from their device and restore the original. Local files stay in the browser. For static hosting, unpack the reader archive next to the JavaScript module.

Register pdf-flipbook with Head and pass its properties to Render. Go setup guide

Open a PDF by URL
Open a PDF by URL
err := mono.UI.Render(w, "pdf-flipbook", mono.Props{
	"Title":     "Field journal",
	"PDFURL":    "/publications/field-journal.pdf",
	"AllowOpen": true,
})
Go usage
Go usage
err := mono.UI.Render(w, "pdf-flipbook", mono.Props{
	"AllowOpen": true,
	"PDFURL":    "../components/publications/negative-space/negative-space.pdf",
	"Pages": []any{
		map[string]any{
			"Alt":      "Cover of Negative Space with a geometric drawing of intersecting concrete walls.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-1.webp",
			"Text":     "MONO STUDIO / FIELD JOURNAL ISSUE 01 Negative Space ARCHITECTURAL STUDIES EIGHT PAGES ON SHADOW AND SCALE 01 / 08",
			"Title":    "Negative Space",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "Opening essay and a contents list of five architectural studies.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-2.webp",
			"Text":     "NEGATIVE SPACE FIELD NOTES MONO STUDIO / FIELD JOURNAL 02 / 08 Start with the gap. At the end of the arcade, two walls stop a step short of meeting. Through that opening a thin patch of sky keeps its shape even as the walls change color. These drawings follow that patch. Each study keeps the building still and moves the eye, from the foot of a column to the underside of a roof. The long arcade 03 An opening in section 04 Light on the return 05 A plan for walking 06 Three edges 07",
			"Title":    "Start with the gap",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "Perspective drawing of a long colonnade, with shadows crossing the floor.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-3.webp",
			"Text":     "NEGATIVE SPACE PERSPECTIVE STUDY MONO STUDIO / FIELD JOURNAL 03 / 08 PLATE 01 / ARCADE The long arcade From the first bay, the columns seem to touch. Walk toward the far wall and the gaps widen one at a time. The darker face of each pier is the clearest measure of the distance between them.",
			"Title":    "The long arcade",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "A roof cutaway shows its thickness and the stair below the opening.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-4.webp",
			"Text":     "NEGATIVE SPACE SECTION STUDY MONO STUDIO / FIELD JOURNAL 04 / 08 An opening in section PLATE 02 / CUT THROUGH THE ROOF The roof is thick enough to hold a shadow of its own. Inside the cut, the narrow bright face records the depth of the slab. Below it, each tread catches a different strip of daylight.",
			"Title":    "An opening in section",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "A row of narrow vertical fins hangs beneath a deep cantilever.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-5.webp",
			"Text":     "NEGATIVE SPACE FACADE STUDY MONO STUDIO / FIELD JOURNAL 05 / 08 Light on the return PLATE 03 / SCREEN A line of thin fins hangs below the overhang. Their outer faces read as a single pale band until the view shifts sideways. Then the dark return of each fin comes into sight.",
			"Title":    "Light on the return",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "Plan of a rectangular courtyard, its entrance, and paired columns.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-6.webp",
			"Text":     "NEGATIVE SPACE PLAN STUDY MONO STUDIO / FIELD JOURNAL 06 / 08 A plan for walking PLATE 04 / COURTYARD AND PASSAGE Follow the passage along the outside wall. At the opening, turn left and step through the second line of masonry. Four pairs of columns set the pace across the courtyard.",
			"Title":    "A plan for walking",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "Three line drawings show a slot between walls, a projected lip, and a window reveal.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-7.webp",
			"Text":     "NEGATIVE SPACE DRAWING EXERCISE MONO STUDIO / FIELD JOURNAL 07 / 08 Three edges The slot Bring two solid blocks close together. Let a single slim opening carry the view. The lip Project the upper plane past the lower one. Trace the line where its shadow ends. The reveal Cut into a wall and leave its thickness visible. Give the inner face a quieter tone.",
			"Title":    "Three edges",
			"Width":    800,
		},
		map[string]any{
			"Alt":      "Closing essay above a cropped detail of the concrete facade.",
			"Height":   1124,
			"ImageURL": "../components/publications/negative-space/page-8.webp",
			"Text":     "NEGATIVE SPACE COLOPHON MONO STUDIO / FIELD JOURNAL 08 / 08 After the turn Fold the drawings shut and look at the nearest doorway. Stand just far enough to one side to see the thickness of the jamb. The first study begins there. NEGATIVE SPACE / ISSUE 01 Original drawings and text by Mono Studio.",
			"Title":    "After the turn",
			"Width":    800,
		},
	},
	"Title": "Negative Space",
})
Rendered HTML
Rendered HTML
<section id="demo-pdf-flipbook" data-mono="pdf-flipbook" data-source="../components/publications/negative-space/negative-space.pdf" data-title="Negative Space" aria-label="Negative Space">
  <div data-book-fallback class="mu-book-fallback">
    <strong>Negative Space</strong>
    <a href="../components/publications/negative-space/negative-space.pdf">Open original PDF</a>
  </div>
  <template data-book-preview>
    <article data-page-title="Negative Space"><img src="../components/publications/negative-space/page-1.webp" alt="Cover of Negative Space with a geometric drawing of intersecting concrete walls." width="800" height="1124"><p>MONO STUDIO / FIELD JOURNAL ISSUE 01 Negative Space ARCHITECTURAL STUDIES EIGHT PAGES ON SHADOW AND SCALE 01 / 08</p></article><article data-page-title="Start with the gap"><img src="../components/publications/negative-space/page-2.webp" alt="Opening essay and a contents list of five architectural studies." width="800" height="1124"><p>NEGATIVE SPACE FIELD NOTES MONO STUDIO / FIELD JOURNAL 02 / 08 Start with the gap. At the end of the arcade, two walls stop a step short of meeting. Through that opening a thin patch of sky keeps its shape even as the walls change color. These drawings follow that patch. Each study keeps the building still and moves the eye, from the foot of a column to the underside of a roof. The long arcade 03 An opening in section 04 Light on the return 05 A plan for walking 06 Three edges 07</p></article><article data-page-title="The long arcade"><img src="../components/publications/negative-space/page-3.webp" alt="Perspective drawing of a long colonnade, with shadows crossing the floor." width="800" height="1124"><p>NEGATIVE SPACE PERSPECTIVE STUDY MONO STUDIO / FIELD JOURNAL 03 / 08 PLATE 01 / ARCADE The long arcade From the first bay, the columns seem to touch. Walk toward the far wall and the gaps widen one at a time. The darker face of each pier is the clearest measure of the distance between them.</p></article><article data-page-title="An opening in section"><img src="../components/publications/negative-space/page-4.webp" alt="A roof cutaway shows its thickness and the stair below the opening." width="800" height="1124"><p>NEGATIVE SPACE SECTION STUDY MONO STUDIO / FIELD JOURNAL 04 / 08 An opening in section PLATE 02 / CUT THROUGH THE ROOF The roof is thick enough to hold a shadow of its own. Inside the cut, the narrow bright face records the depth of the slab. Below it, each tread catches a different strip of daylight.</p></article><article data-page-title="Light on the return"><img src="../components/publications/negative-space/page-5.webp" alt="A row of narrow vertical fins hangs beneath a deep cantilever." width="800" height="1124"><p>NEGATIVE SPACE FACADE STUDY MONO STUDIO / FIELD JOURNAL 05 / 08 Light on the return PLATE 03 / SCREEN A line of thin fins hangs below the overhang. Their outer faces read as a single pale band until the view shifts sideways. Then the dark return of each fin comes into sight.</p></article><article data-page-title="A plan for walking"><img src="../components/publications/negative-space/page-6.webp" alt="Plan of a rectangular courtyard, its entrance, and paired columns." width="800" height="1124"><p>NEGATIVE SPACE PLAN STUDY MONO STUDIO / FIELD JOURNAL 06 / 08 A plan for walking PLATE 04 / COURTYARD AND PASSAGE Follow the passage along the outside wall. At the opening, turn left and step through the second line of masonry. Four pairs of columns set the pace across the courtyard.</p></article><article data-page-title="Three edges"><img src="../components/publications/negative-space/page-7.webp" alt="Three line drawings show a slot between walls, a projected lip, and a window reveal." width="800" height="1124"><p>NEGATIVE SPACE DRAWING EXERCISE MONO STUDIO / FIELD JOURNAL 07 / 08 Three edges The slot Bring two solid blocks close together. Let a single slim opening carry the view. The lip Project the upper plane past the lower one. Trace the line where its shadow ends. The reveal Cut into a wall and leave its thickness visible. Give the inner face a quieter tone.</p></article><article data-page-title="After the turn"><img src="../components/publications/negative-space/page-8.webp" alt="Closing essay above a cropped detail of the concrete facade." width="800" height="1124"><p>NEGATIVE SPACE COLOPHON MONO STUDIO / FIELD JOURNAL 08 / 08 After the turn Fold the drawings shut and look at the nearest doorway. Stand just far enough to one side to see the thickness of the jamb. The first study begins there. NEGATIVE SPACE / ISSUE 01 Original drawings and text by Mono Studio.</p></article>
  </template>
  <div class="mu-book-shell" data-book-enhanced hidden>
    <div class="mu-book-head">
      <div class="mu-book-title"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 4.5c3.4-.9 6.3-.3 9 1.6 2.7-1.9 5.6-2.5 9-1.6v14c-3.5-.8-6.4-.1-9 1.5-2.6-1.6-5.5-2.3-9-1.5zM12 6.2V20"/></svg><span data-book-title>Negative Space</span></div>
      <div class="mu-book-openers">
        <button type="button" data-action="reset" aria-label="Restore original publication" title="Restore original publication" data-book-reset hidden><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 5v6h6M4 10a8 8 0 1 1 1.4 7"/></svg><span>Restore</span></button>
        <button type="button" data-action="open-file" aria-label="Open a PDF file" title="Open a PDF file"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 16V3m-4 4 4-4 4 4M4 14v5a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"/></svg><span>Open PDF</span></button>
        <input type="file" data-book-file accept="application/pdf,.pdf" hidden>
      </div>
    </div>
    <div class="mu-book-stage" data-book-stage tabindex="0" role="group" aria-label="Publication pages">
      <div class="mu-book-spread" data-book-spread></div>
    </div>
    <p class="mu-book-status" data-book-status role="status" aria-live="polite" aria-atomic="true"></p>
    <div class="mu-book-dock" role="group" aria-label="Publication controls">
      <button type="button" data-action="thumbnails" aria-label="Page thumbnails" title="Page thumbnails" aria-controls="demo-pdf-flipbook-panel" aria-expanded="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg></button>
      <i aria-hidden="true"></i>
      <button type="button" data-action="previous" aria-label="Previous page" title="Previous page"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m14.5 5-7 7 7 7"/></svg></button>
      <form class="mu-book-jump" data-book-jump-form>
        <input data-book-jump aria-label="Go to page" inputmode="numeric" type="text" autocomplete="off" value="1">
        <span>/ <span data-book-total>–</span></span>
      </form>
      <button type="button" data-action="next" aria-label="Next page" title="Next page"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m9.5 5 7 7-7 7"/></svg></button>
      <i aria-hidden="true"></i>
      <button type="button" data-action="zoom-out" aria-label="Zoom out" title="Zoom out"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M5 12h14"/></svg></button>
      <button type="button" class="mu-book-fit" data-action="fit" title="Fit page" aria-label="Fit page"><span data-book-zoom>100%</span></button>
      <button type="button" data-action="zoom-in" aria-label="Zoom in" title="Zoom in"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M5 12h14m-7-7v14"/></svg></button>
      <i aria-hidden="true"></i>
      <button type="button" data-action="search" aria-label="Search document" title="Search document" aria-controls="demo-pdf-flipbook-panel" aria-expanded="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/></svg></button>
      <a class="mu-book-download" data-book-download href="../components/publications/negative-space/negative-space.pdf" download title="Download PDF" aria-label="Download PDF"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 3v12m-5-5 5 5 5-5M4 16v4h16v-4"/></svg></a>
      <button type="button" data-action="more" aria-label="More reader tools" title="More reader tools" aria-controls="demo-pdf-flipbook-tools" aria-expanded="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><g fill="currentColor" stroke="none"><circle cx="4" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="20" cy="12" r="1.8"/></g></svg></button>
    </div>
    <section class="mu-book-panel" data-book-panel id="demo-pdf-flipbook-panel" aria-labelledby="demo-pdf-flipbook-panel-title" hidden>
      <header><h3 data-book-panel-title id="demo-pdf-flipbook-panel-title">Pages</h3><button type="button" data-action="close-panel" aria-label="Close panel" title="Close panel"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"/></svg></button></header>
      <input type="search" data-book-query placeholder="Find a word or phrase" aria-label="Search text" hidden>
      <div class="mu-book-results" data-book-results></div>
    </section>
    <section class="mu-book-tools" data-book-tools id="demo-pdf-flipbook-tools" aria-label="Reader tools" hidden>
      <button type="button" data-action="single" aria-label="Single page" title="Single page" aria-pressed="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><rect x="5" y="3" width="14" height="18" rx="1.5"/></svg><span>Single page</span></button>
      <button type="button" data-action="spread" aria-label="Two-page spread" title="Two-page spread" aria-pressed="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 4.5c3.4-.9 6.3-.3 9 1.6 2.7-1.9 5.6-2.5 9-1.6v14c-3.5-.8-6.4-.1-9 1.5-2.6-1.6-5.5-2.3-9-1.5zM12 6.2V20"/></svg><span>Two-page spread</span></button>
      <button type="button" data-action="outline" aria-label="Document bookmarks" title="Document bookmarks"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M8 6h12M8 12h12M8 18h12M3 6h.1M3 12h.1M3 18h.1"/></svg><span>Bookmarks</span></button>
      <button type="button" data-action="fullscreen" aria-label="Toggle fullscreen" title="Toggle fullscreen"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 9V3h6m6 0h6v6m0 6v6h-6m-6 0H3v-6"/></svg><span>Fullscreen</span></button>
    </section>
  </div>
</section>
Go template
Go template
<section id="{{.ID}}" data-mono="pdf-flipbook" data-source="{{.PDFURL}}" data-title="{{or .Title "Publication"}}" aria-label="{{or .Title "PDF flipbook"}}">
  <div data-book-fallback class="mu-book-fallback">
    <strong>{{or .Title "Publication"}}</strong>
    {{if .PDFURL}}<a href="{{.PDFURL}}">Open original PDF</a>{{else}}{{range .Pages}}<a href="{{.ImageURL}}">{{.Title}}</a>{{end}}{{end}}
  </div>
  <template data-book-preview>
    {{range .Pages}}<article data-page-title="{{.Title}}"><img src="{{.ImageURL}}" alt="{{or .Alt .Title}}"{{with .Width}} width="{{.}}"{{end}}{{with .Height}} height="{{.}}"{{end}}><p>{{.Text}}</p></article>{{end}}
  </template>
  <div class="mu-book-shell" data-book-enhanced hidden>
    <div class="mu-book-head">
      <div class="mu-book-title"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 4.5c3.4-.9 6.3-.3 9 1.6 2.7-1.9 5.6-2.5 9-1.6v14c-3.5-.8-6.4-.1-9 1.5-2.6-1.6-5.5-2.3-9-1.5zM12 6.2V20"/></svg><span data-book-title>{{or .Title "Publication"}}</span></div>
      {{if .AllowOpen}}<div class="mu-book-openers">
        <button type="button" data-action="reset" aria-label="Restore original publication" title="Restore original publication" data-book-reset hidden><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 5v6h6M4 10a8 8 0 1 1 1.4 7"/></svg><span>Restore</span></button>
        <button type="button" data-action="open-file" aria-label="Open a PDF file" title="Open a PDF file"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 16V3m-4 4 4-4 4 4M4 14v5a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"/></svg><span>Open PDF</span></button>
        <input type="file" data-book-file accept="application/pdf,.pdf" hidden>
      </div>{{end}}
    </div>
    <div class="mu-book-stage" data-book-stage tabindex="0" role="group" aria-label="Publication pages">
      <div class="mu-book-spread" data-book-spread></div>
    </div>
    <p class="mu-book-status" data-book-status role="status" aria-live="polite" aria-atomic="true"></p>
    <div class="mu-book-dock" role="group" aria-label="Publication controls">
      <button type="button" data-action="thumbnails" aria-label="Page thumbnails" title="Page thumbnails" aria-controls="{{.ID}}-panel" aria-expanded="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/></svg></button>
      <i aria-hidden="true"></i>
      <button type="button" data-action="previous" aria-label="Previous page" title="Previous page"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m14.5 5-7 7 7 7"/></svg></button>
      <form class="mu-book-jump" data-book-jump-form>
        <input data-book-jump aria-label="Go to page" inputmode="numeric" type="text" autocomplete="off" value="1">
        <span>/ <span data-book-total>–</span></span>
      </form>
      <button type="button" data-action="next" aria-label="Next page" title="Next page"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m9.5 5 7 7-7 7"/></svg></button>
      <i aria-hidden="true"></i>
      <button type="button" data-action="zoom-out" aria-label="Zoom out" title="Zoom out"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M5 12h14"/></svg></button>
      <button type="button" class="mu-book-fit" data-action="fit" title="Fit page" aria-label="Fit page"><span data-book-zoom>100%</span></button>
      <button type="button" data-action="zoom-in" aria-label="Zoom in" title="Zoom in"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M5 12h14m-7-7v14"/></svg></button>
      <i aria-hidden="true"></i>
      <button type="button" data-action="search" aria-label="Search document" title="Search document" aria-controls="{{.ID}}-panel" aria-expanded="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 5 5"/></svg></button>
      <a class="mu-book-download" data-book-download href="{{.PDFURL}}" download title="Download PDF" aria-label="Download PDF"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 3v12m-5-5 5 5 5-5M4 16v4h16v-4"/></svg></a>
      <button type="button" data-action="more" aria-label="More reader tools" title="More reader tools" aria-controls="{{.ID}}-tools" aria-expanded="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><g fill="currentColor" stroke="none"><circle cx="4" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="20" cy="12" r="1.8"/></g></svg></button>
    </div>
    <section class="mu-book-panel" data-book-panel id="{{.ID}}-panel" aria-labelledby="{{.ID}}-panel-title" hidden>
      <header><h3 data-book-panel-title id="{{.ID}}-panel-title">Pages</h3><button type="button" data-action="close-panel" aria-label="Close panel" title="Close panel"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"/></svg></button></header>
      <input type="search" data-book-query placeholder="Find a word or phrase" aria-label="Search text" hidden>
      <div class="mu-book-results" data-book-results></div>
    </section>
    <section class="mu-book-tools" data-book-tools id="{{.ID}}-tools" aria-label="Reader tools" hidden>
      <button type="button" data-action="single" aria-label="Single page" title="Single page" aria-pressed="false"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><rect x="5" y="3" width="14" height="18" rx="1.5"/></svg><span>Single page</span></button>
      <button type="button" data-action="spread" aria-label="Two-page spread" title="Two-page spread" aria-pressed="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 4.5c3.4-.9 6.3-.3 9 1.6 2.7-1.9 5.6-2.5 9-1.6v14c-3.5-.8-6.4-.1-9 1.5-2.6-1.6-5.5-2.3-9-1.5zM12 6.2V20"/></svg><span>Two-page spread</span></button>
      <button type="button" data-action="outline" aria-label="Document bookmarks" title="Document bookmarks"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M8 6h12M8 12h12M8 18h12M3 6h.1M3 12h.1M3 18h.1"/></svg><span>Bookmarks</span></button>
      <button type="button" data-action="fullscreen" aria-label="Toggle fullscreen" title="Toggle fullscreen"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 9V3h6m6 0h6v6m0 6v6h-6m-6 0H3v-6"/></svg><span>Fullscreen</span></button>
    </section>
  </div>
</section>
Component CSS
Component CSS
[data-mono="pdf-flipbook"] {
  --book-ground: #e7e7e7;
  --book-line: #d1d1d1;
  --book-shadow: 0 8px 24px #0000000f, 0 2px 5px #0000000a;
  --book-mono: ui-monospace, SFMono-Regular, Consolas, monospace;
  width: 100%;
  background: var(--book-ground);
  color: #171717;
  border-radius: .5rem;
  container-type: inline-size;
}
.mu-book-fallback { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; justify-content: space-between; padding: 1rem; }
.mu-book-fallback a { color: inherit; text-decoration: underline; }
.mu-book-shell { position: relative; display: flex; flex-direction: column; align-items: stretch; isolation: isolate; min-width: 0; }
.mu-book-head { display: flex; align-items: center; justify-content: space-between; gap: .7rem; padding: .85rem 1rem 0; z-index: 1; }
.mu-book-title, .mu-book-openers { display: flex; align-items: center; gap: .5rem; min-width: 0; }
.mu-book-title { font-weight: 600; font-size: .86rem; letter-spacing: -.02em; }
.mu-book-title span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.mu-book-title svg { flex: none; }
.mu-book-shell :where(button, .mu-book-download) {
  display: inline-flex; align-items: center; justify-content: center; gap: .4rem;
  min-width: 2.1rem; min-height: 2.1rem; border: 0; padding: .3rem;
  background: transparent; color: #202020; line-height: 1; border-radius: .4rem; text-decoration: none;
}
.mu-book-shell :is(button, .mu-book-download):hover:where(:not(:disabled)), .mu-book-shell button[aria-expanded="true"] { background: #ececec; }
.mu-book-openers button { background: #fafafa; padding: .35rem .65rem; font-size: .78rem; border: 1px solid var(--book-line); white-space: nowrap; }
.mu-book-openers svg { width: .9rem; height: .9rem; }
.mu-book-stage {
  position: relative; min-width: 0; height: clamp(23rem, 62cqi, 34rem);
  padding: 1.3rem clamp(.65rem, 2.8%, 2.2rem) 1.5rem; overflow: auto;
  touch-action: pan-y pinch-zoom; overscroll-behavior: contain; scrollbar-width: thin;
}
.mu-book-stage:focus-visible { outline-offset: -3px; }
.mu-book-stage[data-zoomed] { touch-action: pan-x pan-y pinch-zoom; cursor: grab; }
.mu-book-stage[data-zoomed]:active { cursor: grabbing; }
[data-dragover] > .mu-book-shell::after {
  content: "Drop PDF to open"; position: absolute; z-index: 5; inset: .5rem;
  display: grid; place-items: center; border: 2px dashed #444; border-radius: .5rem;
  background: #fafafaf0; color: #171717; font-weight: 600; pointer-events: none;
}
.mu-book-spread {
  position: relative; display: flex; align-items: center; justify-content: center;
  width: max-content; height: max-content; min-width: 100%; min-height: 100%;
}
.mu-book-page {
  position: relative; flex: none; display: block; margin: 0; background: white;
  box-shadow: 0 9px 17px #00000019, 0 1px 2px #00000029; overflow: hidden;
}
:is(.mu-book-page,.mu-book-surface) > :is(img,canvas) { display: block; width: 100%; height: 100%; max-width: none; object-fit: contain; user-select: none; -webkit-user-drag: none; }
.mu-book-spread:has(.mu-book-page + .mu-book-page) > .mu-book-page::after,
.mu-book-surface[data-gutter]::after {
  content: ""; position: absolute; inset: 0; pointer-events: none;
  background: linear-gradient(90deg, transparent 93%, #00000015 99%, #00000038);
}
.mu-book-spread:has(.mu-book-page + .mu-book-page) > .mu-book-page + .mu-book-page::after,
.mu-book-surface[data-gutter="left"]::after { background: linear-gradient(90deg, #0000002d, #0000000d 3%, transparent 7%); }
.mu-book-spread[data-turn] > .mu-book-page { opacity: 0; }
.mu-book-turn {
  position: absolute; inset: 0; z-index: 2; pointer-events: none; user-select: none;
  perspective: 90rem;
}
.mu-book-surface {
  position: absolute; overflow: hidden; background: #fff;
  box-shadow: 0 9px 17px #00000019, 0 1px 2px #00000029;
}
.mu-book-hinge, .mu-book-sheet { position: absolute; transform-style: preserve-3d; will-change: transform; }
.mu-book-hinge { top: 0; left: 0; z-index: 1; }
.mu-book-sheet { transform-origin: left center; }
.mu-book-turn[data-direction="back"] .mu-book-sheet { transform-origin: right center; }
.mu-book-front, .mu-book-back { inset: 0; backface-visibility: hidden; -webkit-backface-visibility: hidden; }
.mu-book-back { transform: rotateY(180deg); }
.mu-book-fold-shade {
  position: absolute; z-index: 1; inset: 0; opacity: 0;
  background: linear-gradient(90deg, #0004, #0001 28%, #fff2 68%, #0002);
}
.mu-book-back .mu-book-fold-shade,
.mu-book-turn[data-direction="back"] .mu-book-fold-shade { transform: scaleX(-1); }
.mu-book-turn[data-direction="back"] .mu-book-back .mu-book-fold-shade { transform: none; }
.mu-book-dock {
  z-index: 1; align-self: center; display: flex; align-items: center; justify-content: center;
  gap: .1rem; padding: .3rem; margin: 0 .4rem .85rem;
  background: #fff; border: 1px solid #d3d3d3; border-radius: .68rem; box-shadow: var(--book-shadow);
}
.mu-book-dock > i { flex: none; width: 1px; height: 1.12rem; margin-inline: .15rem; background: #dedede; }
.mu-book-dock :is(button, a):disabled { opacity: .32; }
.mu-book-jump { display: flex; gap: .25rem; align-items: center; margin: 0; color: #595959; }
.mu-book-jump, .mu-book-fit { font: .7rem/1.1 var(--book-mono); font-variant-numeric: tabular-nums; }
.mu-book-jump input { width: 2.25rem; min-height: 1.9rem; padding: .2rem; border: 1px solid #d4d4d4; border-radius: .3rem; text-align: center; background: white; }
.mu-book-shell .mu-book-fit { font: .69rem var(--book-mono); min-width: 2.75rem; }
.mu-book-status { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.mu-book-status:is([data-state="error"],[data-state="loading"]) {
  z-index: 2; left: 50%; top: 42%; transform: translate(-50%, -50%); width: max-content; max-width: 88%; height: auto; clip-path: none;
  padding: .65rem 1rem; border-radius: .45rem; background: #191919; color: white; box-shadow: var(--book-shadow); font-size: .85rem;
}
.mu-book-panel, .mu-book-tools {
  z-index: 4; position: absolute; bottom: 4.05rem; background: #fff; border: 1px solid #c8c8c8;
  border-radius: .65rem; box-shadow: 0 10px 28px #0002; overflow: auto; scrollbar-width: thin;
}
.mu-book-panel {
  left: .85rem; display: flex; flex-direction: column; gap: .6rem; width: min(18.5rem, calc(100% - 1.7rem));
  padding: .7rem; max-height: calc(100% - 5rem);
}
.mu-book-panel header { display: flex; justify-content: space-between; align-items: center; }
.mu-book-panel h3 { font-size: .92rem; font-weight: 650; }
.mu-book-panel input { width: 100%; min-height: 2.2rem; border: 1px solid #aaa; border-radius: .35rem; padding: .45rem .6rem; background: #fff; }
.mu-book-results { min-height: 0; overflow-y: auto; font-size: .85rem; scrollbar-width: thin; }
.mu-book-results:has(.mu-book-thumb) { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: .4rem; }
.mu-book-results .mu-book-thumb { display: flex; flex-direction: column; min-width: 0; width: 100%; gap: .35rem; padding: .35rem; font: .68rem var(--book-mono); }
.mu-book-thumb :is(img,canvas) { display: block; width: 100%; height: 5.5rem; object-fit: contain; }
.mu-book-results [aria-current="page"] { box-shadow: inset 0 0 0 1.5px #191919; }
.mu-book-results .mu-book-result { width: 100%; display: block; text-align: start; padding: .55rem; font-size: .82rem; line-height: 1.45; white-space: normal; }
.mu-book-result strong, .mu-book-result small { display: block; }
.mu-book-result-nav { display: flex; flex-wrap: wrap; align-items: center; gap: .2rem; grid-column: 1 / -1; padding-bottom: .4rem; }
.mu-book-result-count { width: 100%; padding: .2rem .5rem; color: #535353; font: .68rem/1.4 var(--book-mono); }
.mu-book-result-nav .mu-book-result { width: auto; min-height: 1.9rem; border: 1px solid var(--book-line); font-size: .72rem; }
.mu-book-tools { display: grid; right: .85rem; width: 12rem; padding: .35rem; }
.mu-book-tools button { justify-content: flex-start; gap: .65rem; min-height: 2.35rem; padding: .4rem .55rem; font-size: .83rem; }
.mu-book-tools [aria-pressed="true"] { background: #efefef; font-weight: 650; }
[data-mono="pdf-flipbook"]:is(:fullscreen,[data-fullscreen]) { position: fixed; z-index: 9999; inset: 0; width: 100%; height: 100dvh; max-width: none; border-radius: 0; }
[data-mono="pdf-flipbook"]:is(:fullscreen,[data-fullscreen]) .mu-book-shell { height: 100%; }
[data-mono="pdf-flipbook"]:is(:fullscreen,[data-fullscreen]) .mu-book-stage { flex: 1; min-height: 0; }
@container (max-width: 28rem) {
  .mu-book-head { padding: .65rem .55rem 0; }
  .mu-book-stage { height: clamp(20rem, 118cqi, 29rem); padding: 1rem .55rem; }
  .mu-book-dock { flex-wrap: wrap; gap: 0; padding: .2rem; }
  .mu-book-dock > i { display: none; }
  .mu-book-dock :is(button, .mu-book-download) { min-width: 1.75rem; padding: .2rem; }
  .mu-book-jump input { width: 1.8rem; }
  .mu-book-panel, .mu-book-tools { bottom: 4.8rem; }
  .mu-book-openers { gap: .2rem; }
}
JavaScript module
JavaScript module
const clamp = (value, min, max) => Math.max(min, Math.min(max, value));

function node(tag, className, text) {
  const element = document.createElement(tag);
  if (className) element.className = className;
  if (text !== undefined) element.textContent = text;
  return element;
}

function panelButton(text, action) {
  const button = node('button', 'mu-book-result', text);
  button.type = 'button';
  button.addEventListener('click', action);
  return button;
}

function visiblePages(page, count, paired) {
  if (!paired || page === 1) return [page];
  const first = page - page % 2;
  return first + 1 <= count ? [first, first + 1] : [first];
}

// Both faces use the actual decoded page media. The old leaf wrappers stay in
// the spread so its layout and accessible page descriptions survive the turn.
function createPageTurn(spread, nextLeaves, forward) {
  const oldLeaves = [...spread.children].filter(leaf => leaf.classList.contains('mu-book-page'));
  if (!oldLeaves.length || !nextLeaves.length) return null;
  const box = spread.getBoundingClientRect();
  const outgoing = oldLeaves.map(leaf => {
    const r = leaf.getBoundingClientRect();
    return {leaf, left:r.left-box.left, top:r.top-box.top, width:r.width, height:r.height};
  });
  const incoming = nextLeaves.map(leaf => ({
    leaf, width:parseFloat(leaf.style.width), height:parseFloat(leaf.style.height)
  }));
  let left = (box.width - incoming.reduce((sum, p) => sum+p.width, 0)) / 2;
  for (const p of incoming) {
    p.left = left;
    p.top = (box.height - p.height) / 2;
    left += p.width;
  }
  const from = forward ? outgoing.at(-1) : outgoing[0];
  const to = forward ? incoming[0] : incoming.at(-1);
  if (!(from.width > 0 && from.height > 0 && to.width > 0 && to.height > 0)) return null;
  const firstHinge = from.left + (forward ? 0 : from.width);
  const lastHinge = to.left + (forward ? to.width : 0);
  const overlay = node('div', 'mu-book-turn');
  overlay.setAttribute('aria-hidden', 'true');
  overlay.dataset.direction = forward ? 'forward' : 'back';
  const mediaToRestore = [];

  function surface(page, kind, gutter, duplicate = false) {
    const pane = node('div', 'mu-book-surface ' + kind);
    if (gutter) pane.dataset.gutter = gutter;
    const media = page.leaf.querySelector('img,canvas');
    if (media && !duplicate) {
      mediaToRestore.push([page.leaf, media]);
      pane.append(media);
    } else if (media instanceof HTMLCanvasElement) {
      // In single view the destination is visible beneath its turning face.
      // Only this temporary underlay needs a bitmap, at display resolution.
      const copy = node('canvas');
      copy.width = Math.max(1, Math.round(page.width));
      copy.height = Math.max(1, Math.round(page.height));
      copy.getContext('2d')?.drawImage(media, 0, 0, copy.width, copy.height);
      pane.append(copy);
    } else if (media) {
      pane.append(media.cloneNode(false));
    }
    return pane;
  }

  function underlay(page, gutter, duplicate) {
    const pane = surface(page, 'mu-book-underlay', gutter, duplicate);
    Object.assign(pane.style, {left:page.left+'px', top:page.top+'px',
      width:page.width+'px', height:page.height+'px'});
    overlay.append(pane);
    return pane;
  }

  const single = incoming.length === 1 && outgoing.length === 1;
  const oldStill = outgoing.length > 1
    ? underlay(forward ? outgoing[0] : outgoing.at(-1), forward ? 'right' : 'left')
    : null;
  const newStill = incoming.length > 1
    ? underlay(forward ? incoming.at(-1) : incoming[0], forward ? 'left' : 'right')
    : single ? underlay(to, '', true) : null;

  const hinge = node('div', 'mu-book-hinge');
  const sheet = node('div', 'mu-book-sheet');
  Object.assign(sheet.style, {width:from.width+'px', height:from.height+'px',
    left:(forward ? 0 : -from.width)+'px', top:(-from.height/2)+'px'});
  const front = surface(from, 'mu-book-front', outgoing.length > 1 && (forward ? 'left' : 'right'));
  const back = surface(to, 'mu-book-back', incoming.length > 1 && (forward ? 'right' : 'left'));
  const frontShade = node('div', 'mu-book-fold-shade');
  const backShade = node('div', 'mu-book-fold-shade');
  front.append(frontShade);
  back.append(backShade);
  sheet.append(front, back);
  hinge.append(sheet);
  overlay.append(hinge);
  spread.append(overlay);
  spread.setAttribute('data-turn', overlay.dataset.direction);
  let frame = 0;
  const sign = forward ? -1 : 1;
  const mix = (a, b, p) => a+(b-a)*p;

  function seek(progress) {
    const p = clamp(progress, 0, 1), lift = Math.sin(Math.PI*p);
    const spine = mix(firstHinge, lastHinge, p);
    const y = mix(from.top+from.height/2, to.top+to.height/2, p);
    hinge.style.transform = 'translate3d('+spine+'px,'+y+'px,0)';
    sheet.style.transform = 'rotateY('+(sign*180*p)+'deg) skewY('+(sign*lift*1.15)+'deg) '+
      'scale('+mix(1,to.width/from.width,p)+','+mix(1,to.height/from.height,p)+')';
    frontShade.style.opacity = lift;
    backShade.style.opacity = lift;
    if (oldStill) {
      oldStill.style.transform = 'translateX('+(spine-firstHinge)+'px)';
      oldStill.style.opacity = Math.min(1,(1-p)*8);
    }
    if (newStill) {
      if (!single) newStill.style.transform = 'translateX('+(spine-lastHinge)+'px)';
      newStill.style.opacity = Math.min(1,p*8);
    }
  }

  function settle(progress, target, done) {
    cancelAnimationFrame(frame);
    const distance = Math.abs(target-progress);
    if (distance < .002) { seek(target); done(); return; }
    const duration = 540*Math.sqrt(distance);
    const start = performance.now();
    // From rest, ease into motion. A released drag continues immediately.
    const fromRest = progress === 0 || progress === 1;
    function tick(now) {
      const t = clamp((now-start)/duration, 0, 1);
      const eased = fromRest ? t*t*(3-2*t) : 1-(1-t)**3;
      seek(mix(progress,target,eased));
      if (t < 1) frame = requestAnimationFrame(tick);
      else { frame = 0; done(); }
    }
    frame = requestAnimationFrame(tick);
  }

  function remove() {
    cancelAnimationFrame(frame);
    for (const [leaf, media] of mediaToRestore) leaf.prepend(media);
    mediaToRestore.length = 0;
    if (overlay.parentNode === spread) {
      overlay.remove();
      spread.removeAttribute('data-turn');
    }
  }

  seek(0);
  return {seek, settle, remove};
}

export function mount(root) {
  const find = key => root.querySelector('[data-book-' + key + ']');
  const stage = find('stage');
  const spread = find('spread');
  if (!stage || !spread) return;

  const previews = [...(find('preview')?.content.querySelectorAll('article') || [])];
  const sourceURL = root.dataset.source || '';
  const defaultTitle = root.dataset.title || find('title')?.textContent || 'Publication';
  const jump = find('jump');
  const download = find('download');
  const originalDownload = download?.getAttribute('href') || sourceURL;
  const fileInput = find('file');
  const tools = find('tools');
  const panel = find('panel');
  const results = find('results');
  const query = find('query');
  const status = find('status');
  const reset = find('reset');
  const buttons = [...root.querySelectorAll('[data-action]')];
  const more = buttons.find(button => button.dataset.action === 'more');
  const motion = matchMedia('(prefers-reduced-motion: reduce)');

  let pdf = null;
  let localURL = '';
  let count = previews.length;
  let page = 1;
  let zoom = 1;
  let mode = 'auto';
  let panelName = '';
  let returnFocus = null;
  let loadTask, panelTask;
  let resizeFrame = 0, gestureFrame = 0, queryTimer = 0;
  let drag, activeTurn;
  let shownPages = [], layoutKey = '';
  let thumbStart = 1;
  let dragDepth = 0;

  function announce(text, state = 'ready') {
    if (status) {
      status.dataset.state = state;
      if (status.textContent !== text) status.textContent = text;
    }
  }

  const paired = () => mode === 'spread' || (mode === 'auto' && stage.clientWidth >= 640);
  const displayed = () => count ? visiblePages(page, count, paired()) : [];

  function update() {
    const pages = displayed();
    root.dataset.layout = paired() ? 'spread' : 'single';
    root.style.setProperty('--book-zoom', zoom);
    stage.toggleAttribute('data-zoomed', zoom > 1);
    if (jump) {
      jump.max = count;
      jump.value = count ? page : '';
      jump.disabled = !count;
    }
    if (find('total')) find('total').textContent = count || '—';
    if (find('zoom')) find('zoom').textContent = Math.round(zoom * 100) + '%';
    for (const button of buttons) {
      const action = button.dataset.action;
      if (action === 'previous') button.disabled = !count || pages[0] === 1;
      if (action === 'next') button.disabled = !count || pages.at(-1) === count;
      if (action === 'zoom-in') button.disabled = !count || zoom >= 3;
      if (action === 'zoom-out') button.disabled = !count || zoom <= 1;
      if (['fit', 'thumbnails', 'search', 'outline'].includes(action)) button.disabled = !count;
      if (action === 'auto') button.setAttribute('aria-pressed', String(mode === 'auto'));
      if (action === 'single' || action === 'spread') button.setAttribute('aria-pressed', String(root.dataset.layout === action));
      if (['thumbnails','search','outline'].includes(action)) button.setAttribute('aria-expanded', String(panelName === action));
    }
    for (const button of results?.querySelectorAll('[data-book-target]') || []) {
      if (pages.includes(Number(button.dataset.bookTarget))) button.setAttribute('aria-current', 'page');
      else button.removeAttribute('aria-current');
    }
  }

  function cancelTurn() {
    cancelAnimationFrame(gestureFrame);
    gestureFrame = 0;
    drag = null;
    if (!activeTurn) return;
    const turn = activeTurn;
    activeTurn = null;
    turn.controller.abort();
    turn.visual?.remove();
    if (turn.leaves) retainLeaves(turn.leaves);
    stage.removeAttribute('aria-busy');
  }

  function sampleInfo(number) {
    const article = previews[number - 1];
    const img = article?.querySelector('img');
    return {
      title: article?.dataset.pageTitle || 'Page ' + number,
      image: img,
      text: article?.querySelector('p')?.textContent || '',
      width: Number(img?.getAttribute('width')) || 3,
      height: Number(img?.getAttribute('height')) || 4,
    };
  }

  // Retain at most two fit-to-view spreads, with a shared decoded-pixel budget.
  // Keeping the detached leaves lets a return turn reuse the actual PDF canvases.
  const cachedSpreads = new Map();
  const leafGroups = new WeakMap();
  const pixelBudget = 4 * 1024 * 1024;
  let cacheGeneration = 0;
  let warming;

  function spreadKey(pages) {
    return [cacheGeneration, pages.join('-'), paired(), zoom, stage.clientWidth,
      stage.clientHeight, Math.min(window.devicePixelRatio || 1, 2)].join('/');
  }

  function retainLeaves(leaves) {
    const group = leafGroups.get(leaves?.[0]);
    if (!group || group.generation !== cacheGeneration || group.pixels > pixelBudget ||
        group.leaves.some(leaf => leaf.isConnected)) return;
    cachedSpreads.delete(group.key);
    cachedSpreads.set(group.key, group);
    let pixels = 0;
    for (const entry of cachedSpreads.values()) pixels += entry.pixels;
    while (cachedSpreads.size > 2 || pixels > pixelBudget) {
      const oldest = cachedSpreads.values().next().value;
      cachedSpreads.delete(oldest.key);
      pixels -= oldest.pixels;
    }
  }

  function stopWarming() {
    if (!warming) return;
    warming.cancelTimer();
    warming.controller.abort();
    warming = null;
  }

  function clearPageCache() {
    stopWarming();
    cacheGeneration++;
    cachedSpreads.clear();
  }

  async function buildLeaves(pages, key, signal, background = false) {
    signal.throwIfAborted();
    const book = pdf;
    const generation = cacheGeneration;
    const fit = zoom === 1;
    const density = Math.min(window.devicePixelRatio || 1, 2);
    if (background && !book && pages.reduce((sum, number) => {
      const info = sampleInfo(number);
      return sum + info.width * info.height;
    }, 0) > pixelBudget) return [];
    const sizes = await Promise.all(pages.map(async number => {
      if (book) return book.size(number);
      const info = sampleInfo(number);
      if (!info.image) return info;
      // Images cloned inside template.content belong to an inert document.
      const image = document.importNode(info.image, false);
      image.loading = 'eager';
      image.decoding = 'async';
      image.draggable = false;
      const cancelDecode = () => {
        image.removeAttribute('srcset');
        image.removeAttribute('src');
      };
      signal.addEventListener('abort', cancelDecode, {once:true});
      try {
        // Keep a broken preview's alternative and allow subsequent pages to open.
        await image.decode?.().catch(() => {});
      } finally {
        signal.removeEventListener('abort', cancelDecode);
      }
      const specified = Number(image.getAttribute('width')) > 0 && Number(image.getAttribute('height')) > 0;
      return {...info, image, width:specified ? info.width : image.naturalWidth || info.width,
        height:specified ? info.height : image.naturalHeight || info.height};
    }));
    signal.throwIfAborted();
    const style = getComputedStyle(stage);
    const innerWidth = Math.max(1, stage.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight));
    const innerHeight = Math.max(1, stage.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom));
    const ratios = sizes.map(size => size.width / size.height);
    const halfCover = paired() && count > 1 && pages.length === 1;
    const totalRatio = ratios.reduce((sum, ratio) => sum + ratio, 0) * (halfCover ? 2 : 1);
    const height = Math.min(innerHeight, innerWidth / totalRatio) * zoom;
    const widths = ratios.map(ratio => Math.max(1, Math.floor(height * ratio)));
    if (background && book && widths.reduce((sum, width) => sum + width * height * density ** 2, 0) > pixelBudget) return [];

    let pixels = 0;
    const leaves = await Promise.all(pages.map(async (number, i) => {
      const leaf = node('div', 'mu-book-page');
      leaf.setAttribute('role', 'group');
      leaf.setAttribute('aria-label', 'Page ' + number + ' of ' + count);
      leaf.style.width = widths[i] + 'px';
      leaf.style.height = Math.max(1, Math.floor(height)) + 'px';
      if (book) {
        const canvas = node('canvas');
        canvas.setAttribute('aria-hidden', 'true');
        leaf.append(canvas);
        await book.render(number, canvas, {width:Math.min(widths[i], 1800), pixelRatio:density, signal});
        pixels += canvas.width * canvas.height;
      } else {
        const {image, text} = sizes[i];
        if (image) {
          leaf.append(image);
          pixels += image.naturalWidth * image.naturalHeight;
        }
        if (text) leaf.append(node('span', 'mu-sr-only', text));
      }
      return leaf;
    }));
    signal.throwIfAborted();
    if (fit) leafGroups.set(leaves[0], {key, generation, pixels, leaves});
    return leaves;
  }

  function warmPages(pages) {
    if (!pages?.length || zoom !== 1) return;
    const key = spreadKey(pages);
    if (cachedSpreads.has(key) || warming?.key === key) return;
    stopWarming();
    const job = warming = {key, controller:new AbortController(), cancelTimer() {}};
    const start = () => {
      if (warming !== job) return;
      job.promise = buildLeaves(pages, key, job.controller.signal, true);
      job.promise.then(leaves => {
        if (warming === job) retainLeaves(leaves);
      }, () => {}).finally(() => { if (warming === job) warming = null; });
    };
    if (window.requestIdleCallback) {
      const id = window.requestIdleCallback(start, {timeout:350});
      job.cancelTimer = () => window.cancelIdleCallback(id);
    } else {
      const id = setTimeout(start, 60);
      job.cancelTimer = () => clearTimeout(id);
    }
  }

  async function prepareLeaves(pages, signal) {
    signal.throwIfAborted();
    if (!pages.length) return [];
    const key = spreadKey(pages);
    let leaves;
    if (warming?.key === key && warming.promise) {
      // Promote a prefetch already painting this spread, including its cancellation.
      const job = warming;
      warming = null;
      const abort = () => job.controller.abort();
      signal.addEventListener('abort', abort, {once:true});
      try { leaves = await job.promise; }
      finally { signal.removeEventListener('abort', abort); }
    } else {
      stopWarming();
    }
    signal.throwIfAborted();
    const cached = cachedSpreads.get(key);
    cachedSpreads.delete(key);
    if (!leaves?.length) {
      leaves = cached?.leaves || await buildLeaves(pages, key, signal);
    }
    signal.throwIfAborted();
    const book = pdf;
    if (book) {
      // Screen-reader text is independent of painting and must not delay the turn.
      leaves.forEach((leaf, i) => {
        if (leaf.querySelector('.mu-sr-only')) return;
        const label = node('span', 'mu-sr-only');
        leaf.append(label);
        book.text(pages[i]).catch(() => '').then(text => {
          if (pdf === book) label.textContent = text || 'Scanned page. Open the original PDF for additional reading options.';
        });
      });
    }
    return leaves;
  }

  function neighbor(pages, forward) {
    const n = forward ? pages.at(-1) + 1 : pages[0] - 1;
    return n >= 1 && n <= count ? visiblePages(n, count, paired()) : [];
  }

  function finishTurn(turn) {
    if (turn !== activeTurn) return;
    turn.visual?.remove();
    activeTurn = null;
    if (turn.end === 1) {
      const previous = [...spread.children];
      spread.replaceChildren(...turn.leaves);
      retainLeaves(previous);
      shownPages = turn.pages;
    } else {
      retainLeaves(turn.leaves);
    }
    stage.removeAttribute('aria-busy');
    // Repeated navigation updates the destination while the sheet is in flight.
    if (displayed().join() !== shownPages.join()) syncView();
    else {
      announce('Page ' + shownPages.join('–') + ' of ' + count + '.');
      if (zoom === 1) warmPages(neighbor(shownPages, turn.forward));
    }
  }

  function settle(turn, end) {
    turn.end = end;
    if (turn.visual && !motion.matches) {
      turn.visual.settle(turn.progress, end, () => finishTurn(turn));
    } else if (turn.leaves) {
      finishTurn(turn);
    } else if (!end) {
      cancelTurn();
    }
  }

  function beginTurn(pages, forward, animate, held = false) {
    const turn = {pages, forward, progress:0, end:held ? null : 1, controller:new AbortController()};
    activeTurn = turn;
    stage.setAttribute('aria-busy', 'true');
    prepareLeaves(pages, turn.controller.signal).then(leaves => {
      if (turn !== activeTurn) return;
      turn.leaves = leaves;
      if (animate && zoom === 1 && !motion.matches) {
        turn.visual = createPageTurn(spread, leaves, forward);
        turn.visual?.seek(turn.progress);
      }
      if (turn.end !== null) settle(turn, turn.end);
    }).catch(() => {
      if (turn !== activeTurn) return;
      cancelTurn();
      if (shownPages.length) page = shownPages[0];
      update();
      announce('This page could not be displayed. Open or download the PDF to read it.', 'error');
    });
    return turn;
  }

  function syncView(animate = true) {
    const key = [paired(), zoom, stage.clientWidth, stage.clientHeight].join('/');
    if (key !== layoutKey) {
      cancelTurn();
      clearPageCache();
      shownPages = [];
      layoutKey = key;
    }
    const pages = displayed();
    if (!pages.length) { spread.replaceChildren(); return; }
    if (activeTurn) {
      // Let a visible turn land; replace a superseded render before it starts.
      if (activeTurn.visual || activeTurn.end === null || activeTurn.pages.join() === pages.join()) return;
      cancelTurn();
    }
    if (pages.join() === shownPages.join()) return;
    const forward = !shownPages.length || pages[0] > shownPages[0];
    beginTurn(pages, forward, animate && shownPages.length > 0);
  }

  function go(number) {
    if (!count || !Number.isFinite(number)) return;
    if (drag?.turn) cancelTurn();
    const previous = displayed().join();
    page = clamp(Math.round(number), 1, count);
    update();
    if (previous !== displayed().join()) stage.scrollTop = stage.scrollLeft = 0;
    syncView();
  }

  function step(delta) {
    const pages = displayed();
    if (pages.length) go(delta > 0 ? pages.at(-1) + 1 : pages[0] - 1);
  }

  function setZoom(next) {
    zoom = clamp(next, 1, 3);
    update();
    syncView(false);
    if (zoom === 1) stage.scrollTop = stage.scrollLeft = 0;
  }

  function hideTools() {
    if (tools) tools.hidden = true;
    more?.setAttribute('aria-expanded', 'false');
  }

  function closePanel(restore = false) {
    panelTask?.abort();
    clearTimeout(queryTimer);
    if (panel) panel.hidden = true;
    panelName = '';
    if (results) results.replaceChildren();
    if (restore) returnFocus?.focus({preventScroll:true});
    update();
  }

  function makePageLink(label, n) {
    const button = panelButton(label, () => { go(n); closePanel(); stage.focus({preventScroll:true}); });
    button.dataset.bookTarget = n;
    return button;
  }

  function showThumbs(signal) {
    const fragment = document.createDocumentFragment();
    const first = thumbStart;
    const last = Math.min(count, first + 11);
    const thumbCanvas = [];
    for (let n = first; n <= last; n++) {
      const item = makePageLink('Page ' + n, n);
      item.classList.add('mu-book-thumb');
      if (pdf) {
        const canvas = node('canvas');
        canvas.setAttribute('aria-hidden', 'true');
        item.prepend(canvas);
        thumbCanvas.push([n, canvas]);
      } else {
        const img = sampleInfo(n).image?.cloneNode(false);
        if (img) { img.alt = ''; img.loading = 'lazy'; item.prepend(img); }
      }
      fragment.append(item);
    }
    if (count > 12) {
      const controls = node('div', 'mu-book-result-nav');
      for (const [label, change, disabled] of [['Previous thumbnails',-12,first === 1],['More thumbnails',12,last === count]]) {
        const button = panelButton(label, () => { thumbStart += change; refreshPanel(); });
        button.disabled = disabled;
        controls.append(button);
      }
      fragment.append(controls);
    }
    results.replaceChildren(fragment);
    update();
    const book = pdf;
    (async () => {
      for (const [n, canvas] of thumbCanvas) {
        if (signal.aborted) return;
        try { await book.render(n, canvas, {width:100, pixelRatio:1, signal}); }
        catch { if (!signal.aborted) canvas.remove(); }
      }
    })();
  }

  async function showSearch(signal) {
    const needle = query.value.trim().toLocaleLowerCase();
    if (!needle) { results.textContent = 'Enter a word or phrase.'; return; }
    results.textContent = 'Searching…';
    const matches = [];
    for (let n = 1; n <= count; n++) {
      if (signal.aborted) return;
      const text = pdf ? await pdf.text(n) : sampleInfo(n).title + ' ' + sampleInfo(n).text;
      if (signal.aborted) return;
      const at = text.toLocaleLowerCase().indexOf(needle);
      if (at < 0) continue;
      matches.push({page:n, label:'Page ' + n + ' · ' + text.slice(Math.max(0, at - 28), at + needle.length + 65)});
    }
    if (signal.aborted) return;
    if (!matches.length) { results.textContent = 'No matching pages.'; return; }
    let selected = Math.max(0, matches.findIndex(match => match.page >= page));
    function list(move = 0) {
      selected = (selected + move + matches.length) % matches.length;
      if (move) go(matches[selected].page);
      const nav = node('div', 'mu-book-result-nav');
      nav.append(node('p', 'mu-book-result-count', (selected + 1) + ' / ' + matches.length + ' matching pages'));
      if (matches.length > 1) {
        nav.append(panelButton('Previous match', () => list(-1)), panelButton('Next match', () => list(1)));
      }
      const start = selected - selected % 12;
      const items = matches.slice(start, start + 12).map(hit => makePageLink(hit.label, hit.page));
      results.replaceChildren(nav, ...items);
      update();
      if (move) nav.querySelectorAll('button')[move < 0 ? 0 : 1]?.focus({preventScroll:true});
    }
    list();
  }

  async function refreshPanel() {
    panelTask?.abort();
    const signal = (panelTask = new AbortController()).signal;
    if (!panelName) return;
    try {
      if (panelName === 'thumbnails') { showThumbs(signal); return; }
      if (panelName === 'search') { await showSearch(signal); return; }
      results.textContent = 'Loading contents…';
      const entries = pdf ? await pdf.outline() : previews.map((_,i) => ({title:sampleInfo(i+1).title, page:i+1}));
      if (signal.aborted) return;
      const links = entries.filter(entry => entry.page >= 1 && entry.page <= count).map(entry => makePageLink(entry.title, entry.page));
      if (links.length) results.replaceChildren(...links);
      else results.textContent = 'This document has no bookmarks.';
      update();
    } catch {
      if (!signal.aborted) results.textContent = 'These results could not be loaded.';
    }
  }

  function openPanel(name, trigger) {
    hideTools();
    if (!panel || !results || !count) return;
    if (panelName === name) { closePanel(true); return; }
    returnFocus = trigger.closest('[data-book-tools]') ? more : trigger;
    panelName = name;
    panel.hidden = false;
    panel.dataset.panel = name;
    find('panel-title').textContent = {thumbnails:'Pages',search:'Search',outline:'Contents'}[name];
    query.hidden = name !== 'search';
    thumbStart = 1 + Math.floor((page-1)/12)*12;
    refreshPanel();
    update();
    (name === 'search' ? query : panel.querySelector('[data-action="close-panel"]'))?.focus({preventScroll:true});
  }

  function adopt(book, fileURL, title, local) {
    cancelTurn();
    clearPageCache();
    closePanel();
    hideTools();
    if (localURL) URL.revokeObjectURL(localURL);
    if (pdf && pdf !== book) pdf.dispose();
    pdf = book;
    localURL = fileURL;
    count = pdf?.pageCount || previews.length;
    page = 1;
    zoom = 1;
    shownPages = [];
    layoutKey = '';
    spread.replaceChildren();
    stage.scrollTop = stage.scrollLeft = 0;
    stage.removeAttribute('aria-busy');
    if (find('title')) find('title').textContent = title;
    if (reset) reset.hidden = !local;
    if (download) {
      const href = localURL || originalDownload;
      download.hidden = !href;
      if (href) download.href = href;
      if (local) download.download = title;
      else download.setAttribute('download', '');
    }
    update();
    syncView(false);
    announce(count ? title + '. ' + count + ' pages.' : 'Open a PDF to begin.', count ? 'ready' : 'loading');
  }

  async function load(source, local) {
    loadTask?.abort();
    const task = loadTask = new AbortController();
    stage.setAttribute('aria-busy','true');
    announce('Opening PDF…', 'loading');
    try {
      const {openPDF} = await import('./reader/adapter.js');
      if (task.signal.aborted) return;
      const next = await openPDF(source, {signal:task.signal});
      if (task.signal.aborted) { next.dispose(); return; }
      loadTask = null;
      adopt(next, local ? URL.createObjectURL(source) : '', local ? source.name : defaultTitle, local);
    } catch {
      if (!task.signal.aborted) {
        loadTask = null;
        stage.removeAttribute('aria-busy');
        announce('Could not open this PDF. Choose an accessible, unlocked PDF or try the original document link.', 'error');
      }
    }
  }

  function restoreSample() {
    loadTask?.abort();
    loadTask = null;
    if (previews.length || !sourceURL) adopt(null, '', defaultTitle, false);
    else load(sourceURL, false);
  }

  function markFullscreen(active) {
    root.toggleAttribute('data-fullscreen', active);
    const button = buttons.find(b => b.dataset.action === 'fullscreen');
    button?.setAttribute('aria-pressed', String(active));
  }

  async function fullscreen() {
    hideTools();
    if (document.fullscreenElement === root) { await document.exitFullscreen(); return; }
    if (root.hasAttribute('data-fullscreen')) { markFullscreen(false); return; }
    try {
      if (!root.requestFullscreen) throw new Error();
      await root.requestFullscreen();
    } catch { markFullscreen(true); }
  }

  root.addEventListener('fullscreenchange', () => {
    markFullscreen(document.fullscreenElement === root);
  });

  root.addEventListener('click', event => {
    const button = event.target.closest('[data-action]');
    if (!button || button.disabled) return;
    switch (button.dataset.action) {
      case 'previous': step(-1); break;
      case 'next': step(1); break;
      case 'zoom-in': setZoom(zoom+.25); break;
      case 'zoom-out': setZoom(zoom-.25); break;
      case 'fit': setZoom(1); break;
      case 'open-file': fileInput?.click(); break;
      case 'reset': restoreSample(); break;
      case 'thumbnails': case 'search': case 'outline': openPanel(button.dataset.action, button); break;
      case 'close-panel': closePanel(true); break;
      case 'more':
        if (!tools) break;
        if (!panel.hidden) closePanel();
        tools.hidden = !tools.hidden;
        more?.setAttribute('aria-expanded', String(!tools.hidden));
        break;
      case 'single': case 'spread': case 'auto':
        mode = button.dataset.action; hideTools(); update(); syncView(false); more?.focus({preventScroll:true}); break;
      case 'fullscreen': fullscreen(); break;
    }
  });

  function jumpToPage() {
    if (/^\d+$/.test(jump.value.trim()) && Number.isFinite(Number(jump.value))) go(Number(jump.value));
    else jump.value = count ? page : '';
  }
  find('jump-form')?.addEventListener('submit', event => { event.preventDefault(); jumpToPage(); });
  jump?.addEventListener('change', jumpToPage);
  query?.addEventListener('input', () => {
    panelTask?.abort();
    clearTimeout(queryTimer);
    queryTimer = setTimeout(refreshPanel, 160);
  });
  fileInput?.addEventListener('change', () => {
    if (fileInput.files[0]) load(fileInput.files[0], true);
    fileInput.value = '';
  });
  root.addEventListener('dragenter', event => {
    if (!fileInput || !event.dataTransfer?.types.includes('Files')) return;
    event.preventDefault();
    dragDepth++;
    root.setAttribute('data-dragover','');
  });
  root.addEventListener('dragover', event => { if (fileInput && event.dataTransfer?.types.includes('Files')) event.preventDefault(); });
  root.addEventListener('dragleave', () => { if (dragDepth && !--dragDepth) root.removeAttribute('data-dragover'); });
  root.addEventListener('drop', event => {
    if (!fileInput || !event.dataTransfer?.types.includes('Files')) return;
    event.preventDefault();
    dragDepth = 0;
    root.removeAttribute('data-dragover');
    if (event.dataTransfer.files[0]) load(event.dataTransfer.files[0], true);
  });

  root.addEventListener('keydown', event => {
    if (event.key === 'Escape') {
      if (!panel?.hidden) closePanel(true);
      else if (!tools?.hidden) { hideTools(); more?.focus(); }
      else if (!document.fullscreenElement) markFullscreen(false);
      return;
    }
    if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || event.target.closest('input,textarea,select,[contenteditable="true"]')) return;
    if (['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key) && zoom > 1) {
      event.preventDefault();
      stage.scrollBy(event.key === 'ArrowLeft' ? -85 : event.key === 'ArrowRight' ? 85 : 0, event.key === 'ArrowUp' ? -85 : event.key === 'ArrowDown' ? 85 : 0);
    } else if (['ArrowLeft','ArrowRight','Home','End'].includes(event.key)) {
      event.preventDefault();
      if (event.key === 'Home') go(1);
      else if (event.key === 'End') go(count);
      else step(event.key === 'ArrowRight' ? 1 : -1);
    }
  });

  stage.addEventListener('pointerdown', event => {
    if (!event.isPrimary || event.button !== 0 || event.target.closest('button,a,input,[data-book-panel],[data-book-tools]')) return;
    // Native touch panning also supports pinch to zoom. Mouse users can grab the zoomed spread.
    if (zoom > 1 && event.pointerType === 'touch') return;
    drag = {id:event.pointerId, x:event.clientX, y:event.clientY, lastX:event.clientX, lastTime:event.timeStamp,
      velocity:0, left:stage.scrollLeft, top:stage.scrollTop, leaf:event.target.closest('.mu-book-page')};
    stage.setPointerCapture(event.pointerId);
  });
  function trackPointer(event) {
    if (drag?.id !== event.pointerId) return;
    const dx = event.clientX - drag.x, dy = event.clientY - drag.y;
    if (zoom > 1) { stage.scrollTo(drag.left - dx, drag.top - dy); return; }
    if (!drag.turn) {
      if (activeTurn || !shownPages.length || Math.abs(dx) < 8 || drag.vertical) return;
      if (Math.abs(dx) <= Math.abs(dy) * 1.2) { drag.vertical = true; return; }
      const forward = dx < 0;
      const pages = neighbor(shownPages, forward);
      if (!pages.length) return;
      const leaf = forward ? spread.lastElementChild : spread.firstElementChild;
      drag.width = Math.max(1, leaf.getBoundingClientRect().width);
      drag.turn = beginTurn(pages, forward, true, true);
    }
    const turn = drag.turn;
    if (turn !== activeTurn || turn.end !== null) return;
    const elapsed = event.timeStamp - drag.lastTime;
    if (elapsed > 0 && event.clientX !== drag.lastX) {
      drag.velocity = (event.clientX - drag.lastX) / elapsed;
      drag.lastX = event.clientX;
      drag.lastTime = event.timeStamp;
    }
    turn.progress = clamp((turn.forward ? -dx : dx) / drag.width, 0, 1);
    if (!gestureFrame) gestureFrame = requestAnimationFrame(() => {
      gestureFrame = 0;
      if (activeTurn === turn && turn.end === null) turn.visual?.seek(turn.progress);
    });
  }
  stage.addEventListener('pointermove', trackPointer);
  stage.addEventListener('pointerup', event => {
    if (drag?.id !== event.pointerId) return;
    trackPointer(event);
    const gesture = drag, turn = gesture.turn;
    const dx = event.clientX - gesture.x, dy = event.clientY - gesture.y;
    drag = null;
    if (zoom > 1 || gesture.vertical) return;
    if (turn && activeTurn === turn) {
      const speed = event.timeStamp - gesture.lastTime < 100 ? gesture.velocity * (turn.forward ? -1 : 1) : 0;
      const commit = turn.progress >= .3 || (turn.progress * gesture.width > 22 && speed > .45);
      if (commit) {
        page = turn.forward ? turn.pages[0] : turn.pages.at(-1);
        update();
      }
      settle(turn, commit ? 1 : 0);
    } else if (Math.abs(dx) > 32 && Math.abs(dx) > Math.abs(dy) * 1.2) {
      // A second swipe can request the next sheet while the first is landing.
      step(dx < 0 ? 1 : -1);
    } else if (Math.abs(dx) < 6 && Math.abs(dy) < 6 && gesture.leaf) {
      const rect = spread.getBoundingClientRect(), pages = displayed();
      step(pages[0] === 1 ? 1 : pages.at(-1) === count ? -1 : event.clientX >= rect.left + rect.width / 2 ? 1 : -1);
    }
  });
  function cancelGesture(event) {
    if (drag?.id !== event.pointerId) return;
    const turn = drag.turn;
    drag = null;
    if (turn && activeTurn === turn) settle(turn, 0);
  }
  stage.addEventListener('lostpointercapture', cancelGesture);
  stage.addEventListener('pointercancel', cancelGesture);

  motion.addEventListener('change', () => {
    if (!motion.matches || !activeTurn?.visual) return;
    const turn = activeTurn;
    turn.visual.remove();
    turn.visual = null;
    if (turn.end !== null) finishTurn(turn);
  });

  new ResizeObserver(() => {
    cancelAnimationFrame(resizeFrame);
    resizeFrame = requestAnimationFrame(() => { update(); syncView(false); });
  }).observe(stage);
  find('enhanced')?.removeAttribute('hidden');
  if (find('fallback')) find('fallback').hidden = true;
  update();
  restoreSample();
}
Use the HTML in a static site

Copy the rendered HTML above. Download these assets into the same folder as your page, then add the tags below to its head.

Shared CSS Component CSS Ready-to-use module

To read PDFs in the browser, extract the PDF reader archive beside the module. Keep the reader/ folder intact. The reader loads when a document requires it.

HTML head
<link rel="stylesheet" href="./base.css">
<link rel="stylesheet" href="./pdf-flipbook.css">
<script type="module" src="./pdf-flipbook.js"></script>

Copy into your project

Run this command from the Mono checkout. Set -out to the component directory in your application.

Terminal
go run ./cmd/mono-ui add -out ./components pdf-flipbook
Example properties (JSON)
example.json
{
  "AllowOpen": true,
  "PDFURL": "../components/publications/negative-space/negative-space.pdf",
  "Pages": [
    {
      "Alt": "Cover of Negative Space with a geometric drawing of intersecting concrete walls.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-1.webp",
      "Text": "MONO STUDIO / FIELD JOURNAL ISSUE 01 Negative Space ARCHITECTURAL STUDIES EIGHT PAGES ON SHADOW AND SCALE 01 / 08",
      "Title": "Negative Space",
      "Width": 800
    },
    {
      "Alt": "Opening essay and a contents list of five architectural studies.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-2.webp",
      "Text": "NEGATIVE SPACE FIELD NOTES MONO STUDIO / FIELD JOURNAL 02 / 08 Start with the gap. At the end of the arcade, two walls stop a step short of meeting. Through that opening a thin patch of sky keeps its shape even as the walls change color. These drawings follow that patch. Each study keeps the building still and moves the eye, from the foot of a column to the underside of a roof. The long arcade 03 An opening in section 04 Light on the return 05 A plan for walking 06 Three edges 07",
      "Title": "Start with the gap",
      "Width": 800
    },
    {
      "Alt": "Perspective drawing of a long colonnade, with shadows crossing the floor.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-3.webp",
      "Text": "NEGATIVE SPACE PERSPECTIVE STUDY MONO STUDIO / FIELD JOURNAL 03 / 08 PLATE 01 / ARCADE The long arcade From the first bay, the columns seem to touch. Walk toward the far wall and the gaps widen one at a time. The darker face of each pier is the clearest measure of the distance between them.",
      "Title": "The long arcade",
      "Width": 800
    },
    {
      "Alt": "A roof cutaway shows its thickness and the stair below the opening.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-4.webp",
      "Text": "NEGATIVE SPACE SECTION STUDY MONO STUDIO / FIELD JOURNAL 04 / 08 An opening in section PLATE 02 / CUT THROUGH THE ROOF The roof is thick enough to hold a shadow of its own. Inside the cut, the narrow bright face records the depth of the slab. Below it, each tread catches a different strip of daylight.",
      "Title": "An opening in section",
      "Width": 800
    },
    {
      "Alt": "A row of narrow vertical fins hangs beneath a deep cantilever.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-5.webp",
      "Text": "NEGATIVE SPACE FACADE STUDY MONO STUDIO / FIELD JOURNAL 05 / 08 Light on the return PLATE 03 / SCREEN A line of thin fins hangs below the overhang. Their outer faces read as a single pale band until the view shifts sideways. Then the dark return of each fin comes into sight.",
      "Title": "Light on the return",
      "Width": 800
    },
    {
      "Alt": "Plan of a rectangular courtyard, its entrance, and paired columns.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-6.webp",
      "Text": "NEGATIVE SPACE PLAN STUDY MONO STUDIO / FIELD JOURNAL 06 / 08 A plan for walking PLATE 04 / COURTYARD AND PASSAGE Follow the passage along the outside wall. At the opening, turn left and step through the second line of masonry. Four pairs of columns set the pace across the courtyard.",
      "Title": "A plan for walking",
      "Width": 800
    },
    {
      "Alt": "Three line drawings show a slot between walls, a projected lip, and a window reveal.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-7.webp",
      "Text": "NEGATIVE SPACE DRAWING EXERCISE MONO STUDIO / FIELD JOURNAL 07 / 08 Three edges The slot Bring two solid blocks close together. Let a single slim opening carry the view. The lip Project the upper plane past the lower one. Trace the line where its shadow ends. The reveal Cut into a wall and leave its thickness visible. Give the inner face a quieter tone.",
      "Title": "Three edges",
      "Width": 800
    },
    {
      "Alt": "Closing essay above a cropped detail of the concrete facade.",
      "Height": 1124,
      "ImageURL": "../components/publications/negative-space/page-8.webp",
      "Text": "NEGATIVE SPACE COLOPHON MONO STUDIO / FIELD JOURNAL 08 / 08 After the turn Fold the drawings shut and look at the nearest doorway. Stand just far enough to one side to see the thickness of the jamb. The first study begins there. NEGATIVE SPACE / ISSUE 01 Original drawings and text by Mono Studio.",
      "Title": "After the turn",
      "Width": 800
    }
  ],
  "Title": "Negative Space"
}