Commit Graph
100 Commits
Author SHA1 Message Date
thePR0M3TH3ANandClaude Opus 5 90ce6def59 Add archive & rebroadcast for relay migration
A salvage tool in Settings. Sweeps every Artstr design still readable,
saves the signed events to a JSON bundle, and re-publishes them to the
current relays so designs survive a relay going dark.

Reads as widely as possible: the user's relays plus the old defaults,
deliberately including relays marked dead, since one unreachable from
this network may answer from another and a dying relay is exactly the
one holding events worth rescuing.

Signed in, it also sweeps the signer's own events by author, which is
the only way to reach private and premium designs - those carry
randomised d-tags and no public tag. The pubkey is requested from the
signer directly rather than read from state.community.myPubkey: a
connected extension does not populate that, and during testing the tool
reported "0 of mine" while the key in fact had 233 authored designs, 18
of them encrypted. Every private design would have been skipped.

Two rules the tool will not bend, because getting them wrong is worse
than not running:

- Retractions are honoured. A blanket `#k: 30078` deletion filter came
  back with 670 unrelated kind-5 events from across the network, all of
  which would have been rebroadcast; the lookup is now scoped to the
  authors actually collected and further filtered to deletions that
  target this archive. Those go out first, so a relay learns a design
  was withdrawn before anything can put an older copy back.
- Only the newest revision of each addressable design is sent.

Publishing uses one socket per relay - publishToRelays opens a fresh
connection per event, which for 230 events across 6 relays would be
~1400 connections and immediate rate-limiting. Each event is awaited
individually with a bounded in-flight window and a single retry on
rate-limit, so every one is accounted as accepted / rejected /
unanswered.

That last part took three attempts. Fire-and-forget with an
idle-timeout completion check kept closing the socket on the unsent
tail once designs ran to megabytes and acknowledgements lagged the
sends - runs reported 26, 46 and 202 acceptances out of 230 while
claiming success. Verified against a local mock relay that simulates
rate-limiting: 230/230 accepted, 0 unanswered, relay-side counts
matching exactly, and end-to-end 238 found / 230 sent / 230 accepted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-02 12:13:13 -04:00
thePR0M3TH3ANandClaude Opus 5 51b06a3052 Stop the community browser coming up empty
Three separate causes, one symptom.

1. Pixel-art import mode leaked its filters. Opening "Browse
   community..." from the pixel tool set the feed type filter to
   pixelart across every tab, and nothing ever put it back - closing
   the modal without picking a design left the ordinary community
   browser pinned to pixel art for the rest of the session, and left
   _pixelArtImportMode on, so the next design clicked anywhere got
   imported as a layer instead of opening. The mode now snapshots the
   user's own filters on entry and restores them on exit.

   The modal is closed from thirteen different places with no single
   close function to hook, so exit is driven by a MutationObserver on
   the modal's class list. Import mode cannot outlive the modal no
   matter which path closed it, including call sites added later.

2. Relay timeouts were never recorded as failures. queryRelays' timeout
   path called finish(false) without markRelayFailure, so a relay that
   accepts the socket and then goes silent never cooled down - it was
   re-queried on every single request and cost the full timeout each
   time. Only relays that errored or closed were ever penalised.

3. The default relay set had one working relay out of five. Measured
   against a casewrap query: damus refused the socket, nostr.band never
   answered, primal and snort returned a single event each. The entire
   feed rested on nos.lol, so one bad day there and the browser looks
   empty. Defaults are now chosen by measurement - nos.lol, nostr.mom,
   relay.nostr.net and nostr.oxtr.dev each returned a full page, with
   damus and primal kept on for publishing reach. Anyone still carrying
   the old list verbatim is migrated on load and their stale relay
   health cleared; anyone who edited their relays keeps their own.

Verified after the change: the feed pulls 89 designs in ~1.1s, damus is
correctly skipped while cooling down, and a cleared-storage first load
populates straight away.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-02 11:40:57 -04:00
thePR0M3TH3ANandClaude Opus 5 f8869368c9 Keep the background when importing delta-encoded GIFs
Frames after the first came in with the background punched out. The
cause is a common exporter pattern: mark the unchanged background as
the frame's transparent index so each frame compresses down to just
what moved, then tag every frame disposal 2. Those two are
contradictory - disposal 2 ("restore to background") is implemented as
a clear to transparent by every browser, which wipes the very pixels
the delta relies on showing through. The reported file also declares
its background colour as an unrelated cyan palette slot, so honouring
the spec literally is no better.

Suppress the disposal-2 clear in exactly one case: a full-canvas frame
in an animation whose first frame was fully opaque. Such a file
demonstrably has a baked-in background, so "restore to background"
cannot coherently mean "erase to nothing".

Both conditions are load-bearing, and each has a regression test:

- full-canvas only, so sprite erasure - disposal 2 on a small frame
  rect, the case the method genuinely exists for - still clears and
  leaves no trail over an opaque background;
- opaque-first-frame only, so animations on real transparency keep it.
  That includes our own exporter's output, which also writes
  full-canvas disposal-2 frames: without this condition a sprite
  re-imported from an Artstr GIF trailed its previous position.

Verified on the reported 640x640 40-frame GIF (every frame now solid,
100% opaque, black background intact) and on the transparent-background
Artstr icon animation (corners still transparent on every frame).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-02 11:14:36 -04:00
thePR0M3TH3ANandClaude Opus 5 8702043abf Import animated GIFs into the pixel editor
Add an inline GIF89a decoder - the mirror of the existing encoder, so
still no vendored dependency - and wire it into "From image / GIF...".
Every frame of an animated GIF becomes a frame in the pixel editor. A
browser <img> only ever exposes frame 0 to canvas, so decoding is the
only route to the rest; the decoder covers LZW, interlacing, local
colour tables, transparency and all three disposal methods.

The whole animation is quantized against one shared palette (per-frame
palettes made colours shimmer and burned through the 256-entry cap),
playback FPS is derived from the median GIF frame delay, and a Frames
control samples long animations down evenly. Frame count and working
resolution are bounded so a large GIF cannot exhaust memory, and
whatever gets dropped is reported rather than silently truncated.

Fix the reported pixel-editor import bugs:

- Dead canvas. applyLayout() tore the pixel editor down before its
  "layout unchanged" early return, and only the render() at the end
  rebuilds a standalone one - so clicking Pixel art while already in
  Pixel art left the grid on screen with nothing behind it and
  painting, the palette and import all silently did nothing.
- Locked W/H with no explanation, and a multi-image batch forced to the
  New frame target could never set dimensions at all. Batches can now
  target Whole sprite, and the lock states why and how to change it.
- Cover/Fit/Stretch previews were indistinguishable: the pixelized
  canvas rendered at its natural size (32 CSS px in a 250px box). Both
  panes now fill the box, and the source pane is framed exactly as the
  conversion frames it, so the two read as before/after.
- Photos were point-sampled on the way down, which threw away almost
  the whole image and read as noise. Area-average via progressive
  halving, switching to nearest at 1:1 and integer ratios so pixel-art
  sources stay crisp and import exactly.

Also fixed while verifying:

- Standalone pixel work was lost on refresh - pixelCommitIfStandalone()
  mutates state without calling render(), which is what writes the
  autosave. persistAutosave() existed for this case but was never
  called here.
- The quantizer always split to the requested colour count, padding
  small palettes with duplicate dead entries that cost event-size
  budget. It now keeps the source's exact colours when there are fewer
  than requested.
- sanitizePixelArtBlob truncated imported palettes at 64 though the
  model allows 256 (cells past the cut rendered transparent) and
  dropped per-frame durations.
- Stale grid-size pill after a resize, zoom not refitting when the grid
  grows, and a dead pixelImportFromImage() pointing at a nonexistent
  element.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-02 11:02:40 -04:00
thePR0M3TH3AN 20c769a97d Clarify premium creator ownership labels 2026-07-04 17:10:48 -04:00
thePR0M3TH3AN 00abaeb602 Alert creators when premium epoch refresh is needed 2026-07-04 16:42:14 -04:00
thePR0M3TH3AN b980215f15 Add creator premium epoch refresh action 2026-07-04 16:39:42 -04:00
thePR0M3TH3AN 37d871431b Make premium claim windows manual close by default 2026-07-04 16:34:23 -04:00
thePR0M3TH3AN e0e7755cf5 Document Premium 2.0 purchase flow 2026-07-04 16:16:03 -04:00
thePR0M3TH3AN bc35dd2cff Harden NWC split-zap timeout recovery 2026-07-04 16:08:28 -04:00
thePR0M3TH3AN 0729bce549 Add Premium 2.0 partial payment resume UI 2026-07-04 15:47:39 -04:00
thePR0M3TH3AN c9a8f63335 Add Premium 2.0 admin policy publishing tool 2026-07-04 15:44:16 -04:00
thePR0M3TH3AN d04a24d2e2 Add Premium 2.0 purchase repair workflow 2026-07-04 15:39:31 -04:00
thePR0M3TH3AN 8226e9a9ae Add Premium 2.0 legacy vault migration 2026-07-04 15:28:39 -04:00
thePR0M3TH3AN 0724709b0f Add Premium 2.0 private copy retry recovery 2026-07-04 15:20:48 -04:00
thePR0M3TH3AN d9f9084be6 Enforce Premium 2.0 claim windows 2026-07-04 15:16:20 -04:00
thePR0M3TH3AN 9c079dc402 Add Premium 2.0 admin policy publish stamping 2026-07-04 15:14:35 -04:00
thePR0M3TH3AN 170756f722 Wire Premium 2.0 private copy unlock path 2026-07-04 15:03:16 -04:00
thePR0M3TH3AN 92c41442dc Plan and scaffold Premium 2.0 purchase copies 2026-07-04 14:55:02 -04:00
thePR0M3TH3ANandClaude Opus 4.7 18dbe54a59 feat(book): J4.e — real PDF text for threaded text frames
PDF export now emits selectable + searchable PDF text on top of the
threaded-frame raster, the same way the existing reflow-entry path
does. Result: text in threaded frames is searchable in any PDF
viewer, copy-pasteable, and accessibility-tree-visible — not just
pixels.

What changed:

- _drawFrameLinesToCanvas accepts optional textOps + fontWarnings
  args. When provided, each rendered line gets pushed as a textOp
  describing {text, fontKey, sizePt, color, align, leftIn, widthIn,
  topInchesFromTrim}. Unsupported font families (anything outside
  pdf-lib's standard 14) are collected into fontWarnings.
- Empty / whitespace-only lines skipped (no glyphs to emit).
- renderBookDesignedPageToCanvas accepts textOps + fontWarnings and
  threads them to _drawFrameLinesToCanvas.
- exportBookToPdf populates textOps for designed pages too — same
  pattern the reflow branch already used. The existing pdf-lib
  drawText loop after the PNG embed handles both paths since the
  op shape is identical.

Limitations:
- Bold / italic per-line not yet supported — typography stores
  family + size + color + alignment + line-height + paragraph gap,
  but not weight or style flags. Adding weight: 'bold' / italic to
  the typography schema is a small follow-up.
- Only the 14 standard PDF fonts get real-text emission. Custom
  families fall back to raster-only (with a fontWarning surfaced
  in the export status).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-05 09:03:24 -04:00
thePR0M3TH3ANandClaude Opus 4.7 75fc29533e fix(book): J3-data — sweep the last inline nextFrame readers
Two stragglers from the migration commit:

- _bookPortOnClick read layer.nextFrame?.frameId to decide whether
  the click should break a thread. Now reads from the thread
  collection via _findThreadForFrame + _frameIndexInThread.
- The out-port tooltip read layer.nextFrame.frameId for the
  '⌗xxxxxx' destination hint. Switched to the pre-computed nextRef
  variable (already derived from threads[] earlier in the function).
- addBookTextFrame no longer initializes 'nextFrame: null' on new
  layers — that field is gone. Thread membership comes from
  book.threads[]; new frames are solo until linked.

After this sweep, no runtime code path reads layer.nextFrame. Only
the one-time migrator still touches it (intentional — it converts
legacy inline data into the collection then deletes the field).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-05 09:01:32 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ee77820284 refactor(book): J3-data — threading moves from inline layer fields to book.threads[]
Source of truth for thread topology is now book.threads[] — a
top-level collection on the book manifest. Each thread:
  { id, sourceChapter, frames: [{ target, frameId }, ...] }

Layers no longer carry layer.nextFrame or layer.sourceChapter; the
thread collection is the canonical store. Aligns with the spec's
'events as linked files' model: thread graphs live in the manifest,
visible to the recipient, round-trippable.

What changed:

- New thread API: setFrameOutgoing, clearFrameOutgoing,
  setFrameSourceChapter, _findThreadForFrame, _frameIndexInThread.
  All write helpers handle the rebalancing dance (splitting threads,
  re-stitching, dropping empty single-frame threads).
- One-time migrator migrateBookThreadingToCollection — runs from
  ensureBookState on every state restore. Idempotent. Converts any
  legacy inline nextFrame / sourceChapter into book.threads[] then
  deletes the inline fields. Existing books migrate transparently
  the first time they're opened after the upgrade.
- _bookCollectThreadChain: now reads thread directly from
  book.threads[]. The backward / forward walk over inline links is
  gone — much simpler.
- _bookFrameChainContains: same — reads from threads.
- All readers updated to ask threads[] for the answer:
  _attachBookFramePorts (link state + chip), the editor canvas text
  painter, the tile thumbnail / PDF canvas pipeline, the Chapters
  tab Place button + Place helper, the inspector dropdowns +
  diagnostic status.
- All writers updated to call the new helpers instead of writing
  to layer.nextFrame / layer.sourceChapter:
    _completeBookPortLink → setFrameOutgoing
    _breakBookFrameLink   → clearFrameOutgoing
    inspector outgoing dropdown → setFrameOutgoing / clearFrameOutgoing
    inspector incoming dropdown → clearFrameOutgoing on old + setFrameOutgoing for new
    inspector chapter dropdown → setFrameSourceChapter
    Chapters-tab Place button + _placeChapterIntoSelectedFrame
    chip × clear button → setFrameSourceChapter(null)
- bookManifestPayload + bookPayload (whole-book JSON) include
  threads[]. Load path restores them.

The migrator + dual support means: legacy books in autosave/JSON/
Nostr round-trip cleanly. New writes go straight to threads[].

Cleaner manifest schema, smaller layer payloads, and the right
shape before merging to main.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-05 09:00:21 -04:00
thePR0M3TH3ANandClaude Opus 4.7 3d74689eb0 feat(book): J4.d.2 — per-frame typography + 144 dpi tile rendering
Two paired improvements:

1. Pages-overview tile thumbnails now render at 144 dpi instead of
   72. At typical grid widths (~150 px tiles) the 72 dpi raster
   shrank text to ~3 px tall — illegible. 144 dpi quadruples the
   pixel count per tile (~16 ms → ~60 ms per tile on the work I
   profiled informally) but text becomes readable. A content-hash
   cache is the next perf step if grids get large.

2. Text-frame typography is now per-frame, not per-thread. Each
   frame in the chain can override font / size / line-height /
   alignment / color / paragraph gap. The head's typography is the
   fallback when a frame doesn't set its own.

   - _paginateParagraphsIntoFrames reads typography fresh on every
     frame advance (and at paragraph start) so size differences flow
     correctly — when text crosses into a 14pt frame from a 10pt
     frame, line heights adjust mid-flow.
   - Painters (_paintFrameLines DOM + _drawFrameLinesToCanvas
     canvas) receive each frame's own typography rather than the
     head's.
   - Inspector typography controls are now editable on every frame
     (not just the head). Writes go to layer.typography on the
     selected frame. The status hint distinguishes head ('Applies
     to this frame. The head\\'s typography is also the chain\\'s
     fallback.') from mid-thread ('Applies to this frame only —
     overrides the head\\'s default.').

Known limitation: when a paragraph spills across a typography
boundary, the spilled lines were wrapped at the source frame's
width. They place + render at the destination's typography but
keep the source frame's line breaks. Re-wrap-on-advance is J4.d.3.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-05 08:47:10 -04:00
thePR0M3TH3ANandClaude Opus 4.7 4e60c020b0 fix(book): bumper padding under page-edit bar; reverts during print/export
The floating bar (Back · Publish · Proof PDF · Cover JSON etc) sits
absolute at top:10px and overlapped the top edge of the sheet
underneath. Added 60px top padding to .previewShell when the bar is
visible (editing-book-page OR editing-book-cover) so the sheet lands
below the bar.

Both @media print and body.exporting revert the padding back to the
24px default AND hide the bar entirely, so canvas exports and
browser-print outputs aren't offset by the on-screen clearance.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-05 08:25:15 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ce1e1a783b fix(book): chain walk dropped frames past 2 — separate seen sets per direction
_bookCollectThreadChain shared a single 'seen' set between the
backward and forward walks. For a chain A → B → C started from C,
the backward walk visited B then A, leaving seen = {B.id, A.id}.
The forward walk from head A then tried to push B, but found B in
seen and broke immediately — returning chain [A] instead of
[A, B, C].

Symptom: cross-page flow worked for any 2-frame chain (forward
walk only had one node to visit), but broke as soon as the chain
hit 3 frames. The user repro 'A on page 1 → B on page 1 → C on
page 2 doesn't flow' matched exactly.

Fix: use separate seen sets per walk direction. Each starts with
the relevant endpoint (layer for backward, head for forward) and
detects same-direction cycles without bleeding into the other.

Affects every consumer of _bookCollectThreadChain: editor canvas
text rendering (_attachBookFramePorts), tile thumbnails
(renderBookDesignedPageToCanvas via the J4.c.2 hook), PDF export
(same path), and the text-frame inspector's chain / line-count
diagnostic.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 22:29:18 -04:00
thePR0M3TH3ANandClaude Opus 4.7 cbfed8702b diag(book): surface chain + line distribution in the text-frame inspector
When a text-frame is selected in a thread, the status line now shows
the actual paginator output:

  Frame 2 of 3 in this thread · 12 lines here; chain: [18 · 12 · 5]

That makes it obvious whether the chain walk found every frame and
how many lines landed in each. If the chain shows length 2 when the
user expects 3, the chain walk dropped a frame (probably a stale
nextFrame ref). If the chain looks right but line counts are wrong
in the 3rd frame, the bug is in the paginator.

Also logs a console.warn + appends '⚠ outgoing link is broken' to
the status when this frame's outgoing nextFrame ref points at a
frameId that doesn't exist in state.layers (deleted frame /
deleted page).

Diagnostic-only — no behavior change. Helps pin down the
'cross-page flow stops after 2 frames' bug.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 22:19:19 -04:00
thePR0M3TH3ANandClaude Opus 4.7 3d41eaaf7f fix(book): tile thumbnails now use the PDF-export canvas pipeline
Replaces the DOM-based preview helper for designed-page tiles with
renderBookDesignedPageToCanvas at 72 dpi. That's the SAME function
the PDF export + Reader Mode use, so the tile is guaranteed to
match the print output. No more drift on:

- Linked-design layers (async resolve was inconsistent in the DOM
  preview path)
- z-order between threaded text and overlapping layers
- Clip paths (DOM preview used a different clip serialiser)
- Group transforms
- Master text-frame outlines (already filtered in J6, but worth
  noting they're handled by the canvas path too)
- Master layer underlay z-ordering
- Token substitution in master text (canvas path runs
  applyBookTokensToLayers)

Each tile:
- Stage 1 (sync): paint the spec background colour so the grid
  doesn't shift while canvases render.
- Stage 2 (async): renderBookDesignedPageToCanvas → canvas.toDataURL
  → swap in as <img>. Guarded by isConnected so late completions
  don't overwrite a re-rendered tile.

Trade-off: each tile spins up its own async render. For typical
book sizes (10-100 pages) this is fast enough. A future cache by
(entry.id + content-hash) could skip re-rasterising unchanged
pages on every grid repaint.

The old _paintThreadedFramesOnThumb helper is now dead code
(canvas renderer handles threaded text internally) but left in
place; cleanup deferred.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 22:08:13 -04:00
thePR0M3TH3ANandClaude Opus 4.7 e6e1ef17f5 feat(book): Manifest Links panel in Document settings
Adds an InDesign-style 'Links panel' to the book's Document settings
modal — every external event the book references, with status.

Each row shows:
- Icon (🏷 cover · 🎨 master · 📐 page · 📄 chapter · 📚 manifest)
- Label + truncated coord (kind:pubkey…:dTag)
- Status pill:
    resolved  — sidecar data is in state (layers loaded / markdown
                fetched)
    🔒 private — encrypted ref (decrypt happens at resolve time)
    unresolved — ref set but no data fetched yet (try Refresh)
    unpublished — surface has layers but no Nostr ref (publish to
                  mint an event)
    local draft / empty — chapter content without a ref
- Actions: 📋 copy naddr to clipboard · ↻ force re-fetch this
  sidecar via resolveBookSidecars(..., { force: true })

Plus a 'Refresh all' button under the list that forces a full
re-resolve and repaints the panel when done.

Counts shown in the section header summary so you can see at a
glance how many references are resolved vs. pending.

Closes the loop on the Manifest Links design the user asked for —
this is the read-only view of what the casewrap-book event points
at, alongside the chip / refresh affordances that have been on the
sidebar and tile rows since D1.7.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 22:02:45 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ff0b7348f2 feat(book): direct manifest import — from Nostr (naddr) or local JSON
Closes the loop on the manifest pattern. Two new buttons in the
book sidebar:

- 📥 Import book from Nostr… — paste an naddr / nevent at a
  casewrap-book event. The function resolves the event, tries
  NIP-44 / NIP-04 decryption (so private books work), feeds the
  payload through loadProjectFromText's existing book branch,
  injects the publish ref so future Publish replaces in place,
  then surfaces resolveBookSidecars summary (X / Y resolved, N
  failed) into #bookResolveStatus when it settles.

- 📁 Import book from JSON… — file picker that accepts the
  whole-book JSON Save Project writes (templateMode='book' +
  top-level book field). Same downstream path as Nostr import;
  also kicks off the resolver so any chapter-by-textRef refs
  populate.

Both reuse the existing book branch of loadProjectFromText (line
30441) — no new state-restore code; just clearer entry points for
discovery. Community-browser-driven loads still work; this is the
direct-paste / direct-file affordance the user couldn't find before.

Status reporting comes through #bookResolveStatus (the hint line
that already shows '↻ Refresh from Nostr' results) so users can
see progress without opening DevTools.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 21:59:06 -04:00
thePR0M3TH3ANandClaude Opus 4.7 a0e6329480 fix(book): Pages overview tile thumbnails — accurate to printed output
Three causes of inaccuracy in the thumbnail rendering, all addressed:

1. Bleed offset. Layer x/y are stored sheet-relative (include bleed
   inches). The tile canvas is sized trim-only (matches what gets
   printed). Result: every layer rendered shifted right + down by
   bleed/trim ≈ 2% for US Trade. Now offset each layer by -bleed when
   composing the tile preview — same translation
   renderBookDesignedPageToCanvas uses for PDF export.

2. Text-frame outlines. The dashed text-frame border is an authoring
   affordance, not a print element. The designed-page tile path now
   filters out shape layers with kind='text-frame' before passing to
   the preview helper (same filter the reflow-tile path already used
   on masters). Threaded chapter text still paints over the bare
   frame area via _paintThreadedFramesOnThumb.

3. Aspect ratio. Tiles defaulted to 2:3 in CSS — fine for US Trade
   6×9 but distorted for Square 8×8, A4, etc. Each tile now sets
   aspect-ratio inline from the book's actual trim dimensions.

Tiles should now match the PDF output much more closely.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 21:44:46 -04:00
thePR0M3TH3ANandClaude Opus 4.7 97597f1e3d feat(book): J4.d — line-by-line overflow + frame typography (strip markdown)
Two architectural shifts to match how design tools (InDesign, Affinity
Publisher, Scribus) handle threaded text.

1. Content vs presentation split. Chapter markdown is flattened to
   plain paragraphs on import — headings, bold, italics, list
   bullets, blockquote marks all stripped. The author writes in
   markdown because it's a good authoring format; the designer
   applies presentation on the frame, not in the source.

2. Line-by-line spill. The block-based engine moved whole paragraphs
   to the next frame when they didn't fit, leaving gaps at the
   bottom of each frame. The new engine wraps each paragraph against
   the current frame's width using its typography, then places
   lines one at a time — when the frame is full, the NEXT line
   continues in the next frame. Paragraphs break across frames
   gracefully.

What changed:

- _flattenChapterToParagraphs(md) strips markdown to plain text,
  collapsing whitespace and preserving paragraph breaks.
- _getFrameTypography(layer) returns the frame's typography (font,
  size, line height, alignment, color, paragraph spacing) with sane
  defaults.
- _paginateParagraphsIntoFrames(paragraphs, chain, typography) is
  the new line-based paginator. Wraps each paragraph using the
  active frame's inner width, fills the frame to height, advances
  to the next frame, repeats. Returns per-frame line buckets +
  hasMoreText flag for overset detection.
- _paintFrameLines / _drawFrameLinesToCanvas — DOM + Canvas2D
  rasterisers for the new format. Replace _paintFrameBlocks and
  _drawFrameBlocksToCanvas in the three render paths (editor,
  tile thumbnails, PDF export).
- addBookTextFrame seeds new frames with default typography
  (Georgia 11pt, 1.5 line-height, 0.1in paragraph gap, left align,
  near-black).
- Text-frame inspector adds a 'Typography' section: font, size,
  color, line height, paragraph spacing, alignment. Editing on
  the head propagates to the whole thread. Mid-thread frames show
  the read-only inherited values.

Existing reflow entries (chapters in book.pages used the
non-threaded way) still flow through the legacy block engine —
that path is untouched.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 21:39:37 -04:00
thePR0M3TH3ANandClaude Opus 4.7 be9a33a44c feat(book): text-frame inspector in the right panel — discoverable threading
Replaces the port-click dance as the primary path for threading +
chapter placement. Whenever a text-frame layer is the primary
selection in book mode, a new #bookTextFrameOptions section appears
in the right-side #toolOptions panel with:

- Status line: 'Frame N of M in this thread' / 'Solo frame' /
  '(Head — chapter source goes here)'.
- Chapter source dropdown — every reflow entry in book.pages. Only
  enabled when the selected frame is the head of its thread;
  mid-thread frames inherit and show a hint to that effect.
- Incoming-from dropdown — every other text frame in the book that
  could safely link TO this one (no cycle). Selecting one sets the
  source frame's nextFrame to point here; selecting (none) clears
  whatever was linking in.
- Outgoing-to dropdown — every other text frame this one could
  safely link to. Selecting one sets this frame's nextFrame;
  selecting (none) breaks the link.

Both dropdowns share _enumerateBookTextFrames, which labels each
candidate by its surface ('Page 3', 'Master · Standard interior') +
its ⌗frameId. Cycle detection reuses _bookFrameChainContains so the
dropdown only shows safe candidates.

Force-shows the outer #toolOptions panel when the inspector is
visible — the default toggling in syncToolPaletteUI hides it for
the Select tool, but with a text-frame selected we want the
inspector regardless of active tool.

Port-click + Chapters-tab 'Place' button still work as alternative
paths. The dropdown panel is the discoverable one.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 21:09:48 -04:00
thePR0M3TH3ANandClaude Opus 4.7 81dd6bf6b6 fix(book): text-frame ports were eating resize handles + drag/select events
Three reported bugs, one root cause: the in/out ports sat at the
top-left and bottom-right CORNERS of every text-frame layer —
exactly where the lh-nw and lh-se resize handles live — AND their
pointerdown bubbled to the freeLayer's startLayerDrag handler.

Symptoms:
- Couldn't resize a text frame (corner handles hidden under the
  larger-z-index ports).
- Couldn't click an in/out port to thread (the port's pointerdown
  started a layer drag, the click never fired).
- Couldn't 'Place chapter into selected frame' (the chapter button
  needs a selected frame, and selection requires a click that
  wasn't being shadowed by drag).

Fixes:
- Move ports OUTSIDE the layer's bounding box on the top edge
  (in port) and bottom edge (out port), centered. New tab shape
  with a dashed connector to the frame edge so the affordance
  reads. Both well clear of the 8 corner/edge/rotation handles.
- Bump the frameId badge to sit just above the layer (top-right,
  -16px) so it doesn't visually conflict with the in port.
- Add pointerdown + mousedown handlers on both ports AND on the
  source-chapter chip + its X clear button that stopPropagation.
  Drag handler no longer kidnaps the click.

Resize, select, link, and place-chapter all flow correctly now.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:59:28 -04:00
thePR0M3TH3ANandClaude Opus 4.7 b6b00c09f1 docs: J4.c.3 status note + implementation status table
Reader Mode reuses renderBookDesignedPageToCanvas, which the J4.c.2
commit already updated to render threaded chapter text. So J4.c.3
is implicit — no code change needed beyond what J4.c.2 shipped.

Adds an 'Implementation status' table to the spec so anyone reading
the doc later can map phase labels to actual commits + see what
still pends.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:35:56 -04:00
thePR0M3TH3ANandClaude Opus 4.7 10d9e51155 feat(book): J4.c.2 — threaded text exports to PDF on designed pages
renderBookDesignedPageToCanvas now walks page layers after the
master + page layers are drawn, finds text frames whose thread head
holds a placed chapter, paginates via _paginateChapterIntoThread,
and rasterises each frame's slice onto the export canvas at the
frame's coordinates.

New helper _drawFrameBlocksToCanvas — stripped-down counterpart to
the block-painting loop in renderBookReflowPhysicalPageToCanvas.
Handles paragraphs, headings, lists, blockquotes, code blocks, hr,
and plain text — same things the editor's _paintFrameBlocks paints
to DOM. Tables in threaded frames + real-PDF textOps emission (for
selectable text in the PDF) are deferred to a J4.b2 cleanup.

PDF output should now contain the threaded chapter text where the
user authored their frames, not just the dashed text-frame outline.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:34:46 -04:00
thePR0M3TH3ANandClaude Opus 4.7 9d8be7e0fe feat(book): J4.c.1 — threaded text shows in Pages overview tile thumbnails
After a designed-page tile is painted, walk its text-frame layers,
identify any that hold a placed chapter via their thread chain, and
paint each frame's paginated slice as an overlay at the frame's
position in the thumb canvas. Same _paintFrameBlocks helper the
editor uses, sized to the frame's bounding box.

The tile thumbnail now reflects the real text flow — author a
chapter, place it on a page-1 head frame, and the Pages overview
shows the first chunk of the chapter text in that frame; the
linked frame on page 2 shows the next chunk.

Still pending: PDF export and Reader Mode walk reflow entries the
old way (J4.c.2 / J4.c.3).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:33:26 -04:00
thePR0M3TH3ANandClaude Opus 4.7 282f5df4f3 feat(book): J4.b — variable-geometry thread pagination
Lets a thread have frames of different sizes and have text wrap
correctly in each. The chain {frame1: 6×4, frame2: 4×6, frame3:
6×6} now line-breaks at frame1's 6″ width, then at frame2's 4″
width, then at frame3's 6″ width — no clipping in the narrow
frame, no excess gutter in the wide one.

What changed:

- paginateChapter accepts opts.startTokenIndex and opts.maxPages.
  The token loop honors both: starts from the given index, stops
  after the page count is met, and returns result.endTokenIndex
  so the caller knows where to resume.
- _paginateChapterIntoThread walks the chain frame-by-frame,
  calling paginateChapter once per frame with that frame's
  geometry + the running token cursor. Each frame contributes its
  own one page to the chain.
- Overset detection switched from a page-count comparison to a
  token-cursor comparison (paginated.hasMoreText). More accurate
  with variable geometry where page count ≠ frame count.

Limitations still standing:
- PDF export, Reader Mode, and tile thumbnails still walk
  book.pages reflow entries the old way — J4.c.
- Tokens are re-lexed and re-measured per frame today. For long
  chains this is N × token-count work; cache by chain+chapter
  if it becomes a perf problem.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:31:57 -04:00
thePR0M3TH3ANandClaude Opus 4.7 2d7e757308 feat(book): J4 — thread-aware pagination, text flows through linked frames
Hooks up the threading wiring so chapter text actually pours through
the frame chain you authored in J3 + J5.

What changed:

- paginateChapter now accepts opts.frameOverride = { x, y, w, h,
  padding }. When provided, it skips the master-frame lookup and
  uses the override directly. Existing callers (master-driven
  pagination) keep working unchanged because the override is opt-in.
- New _paginateChapterIntoThread(headLayer, book) — builds a
  synthetic call to paginateChapter using the head frame's geometry,
  returns the pages + the resolved chain.
- New _paintFrameBlocks(el, page, frameW, frameH, padding) — paints
  one paginated page directly into a freeLayer wrapper. Like
  paintReflowPageOverlay but coordinates are frame-local instead of
  page-local.
- In _attachBookFramePorts: when a chip is being shown (chapter
  placed on the thread's head), paginate + paint the slice for THIS
  frame. If the chapter overruns the chain, the last frame gets a
  red ⊞ OVERSET badge. If the chapter is shorter than the chain,
  extra frames get a muted '(thread continues — chapter ended
  upstream)' placeholder.

You can now: thread frames, place a chapter on the head, and the
text actually flows across the chain. Real text, real wrapping,
real headings + lists + code blocks — same layout engine the
reflow-entry path has always used.

Limitation captured for J4.b: every frame in a thread shares the
head's geometry. Variable-geometry threads (e.g. front-matter frame
narrower than body frames) need the engine to walk tokens per-frame
instead of all at once. Today the line breaks are computed once at
head geometry and re-used.

PDF export, Reader Mode, and the per-tile thumbnail painter still
walk book.pages reflow entries the old way — they don't see threaded
frames yet. That's the J4.c cleanup once the engine settles.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:28:35 -04:00
thePR0M3TH3ANandClaude Opus 4.7 83d451dfe4 feat(book): J5 — place chapter into a thread's head frame (placeholder body)
Wires a text-frame layer to a chapter source. UX:

- Each chapter row in the Chapters tab gets a '📥 Place in selected
  frame' button. Disabled when no text-frame is selected, when the
  selected frame is mid-thread (must place on the head), or when the
  selected frame already holds this chapter.
- On click: head.sourceChapter = entry.id, history-push, re-render.
- Threaded text frames render a small blue chip up top showing
  '📄 <chapter title> · frame N / M', plus an × button on the head
  to unplace. The chip is identical across every frame in the chain
  so the chapter assignment is legible everywhere.
- Inside the frame: italic placeholder line ('(text will flow here
  — J4 pours it)'). Real text layout into per-frame geometry lands
  in J4.

The thread-walk uses _bookCollectThreadChain, so a placed chapter
is visible across all linked frames immediately. Unplacing from the
head clears it everywhere in the chain.

Mid-thread frames don't get a clear button — clearing on a non-head
would be ambiguous. The Chapters tab button refuses to place on a
mid-thread frame for the same reason.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 20:01:14 -04:00
thePR0M3TH3ANandClaude Opus 4.7 a419160b3a feat(book): J3.c — show-thread overlay on port hover
Hovering any in / out port of a threaded frame highlights every
frame in the same chain. The head of the thread (first frame, no
incoming link) gets a blue outline; the rest get green. Hover off
clears the highlight.

_bookCollectThreadChain walks backwards along incoming nextFrame
refs to the head, then forward along outgoing refs to the tail.
Cycle-safe and depth-capped. Makes long threads (e.g., a chapter
flowing across many designed pages) immediately legible — useful
in J5+ when threads start spanning more than two frames.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 16:09:44 -04:00
thePR0M3TH3ANandClaude Opus 4.7 4afe726704 feat(book): J3.b — click-to-link UX for text-frame threading
Wires the in/out ports added in J3.a. Workflow:

- Click an empty out port → enters 'loading' state (cursor turns to
  copy, body gets .book-port-loading, source port pulses, every
  empty in port highlights as a drop target).
- Click another frame's in port → links them. sourceLayer.nextFrame =
  { target, frameId }. Toast confirms.
- Click an already-linked out port → breaks the thread at that point.
- Click the same source out port again, or press Esc → cancels.
- A cycle guard refuses links that would close a loop (A → B → C,
  then trying C → A).

Pure data updates so far — no rendering change to the chapter
content. The pagination engine still uses the master-frame-clone
model from C4. J4 swaps in a thread-walking pagination engine that
honours these nextFrame refs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 16:08:35 -04:00
thePR0M3TH3ANandClaude Opus 4.7 3cab9482e7 feat(book): J3.a — render in/out ports + frameId badge on text frames
First step of the threading UI. Every text-frame layer in book mode
now shows:

- An 'in' port (small square, top-left corner) — turns green when
  another frame's nextFrame ref points at this one.
- An 'out' port (small square, bottom-right corner) — turns green
  when this frame's nextFrame points somewhere.
- A tiny '⌗ <frameId>' badge in the bottom-left so the user can see
  the frame's stable id while authoring.

Reads thread-link state from layer.nextFrame on each frame (no
book.threads[] consumer yet — that lands in J4 with the pagination
refactor). Legacy text-frame layers (created pre-J2) get a frameId
backfilled the first time they render, so old books gain the new
ports automatically.

Click handling is not yet wired — J3.b adds the load-cursor + link
flow. The ports are visible affordances and tooltips today.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 16:01:07 -04:00
thePR0M3TH3ANandClaude Opus 4.7 2110e724b9 feat(book): J2 — first-class text-frame on designed pages + stable frameId
Generalises the text-frame layer from master-only (Phase C4) to any
book surface. Designed pages can now host text frames the same way
masters do, with the same '+ Text frame' button in the page-edit
bar.

What changed:

- addBookTextFrameToActiveMaster() → addBookTextFrame(targetOverride)
  that picks up book.editingMasterId OR book.editingEntryId depending
  on which surface is open. Legacy alias kept so old callers don't
  break.
- New layer carries a stable frameId (independent of layer.id) and
  a nextFrame field (null for now; J3 will use it for threading).
- bookMasterAddTextFrame button now visible in both master-edit
  AND page-edit modes. Title updated to read 'a text frame to this
  surface (master or designed page)'.
- Click handler now calls the generalized addBookTextFrame().

The frame still renders as the existing dashed-blue text-frame
shape with no content of its own — pagination still flows chapter
text through master frames as before. J3 wires the in/out ports
and the click-to-link UX; J4 makes the pagination engine walk
thread.frames[] instead of cloning masters.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:58:58 -04:00
thePR0M3TH3ANandClaude Opus 4.7 961b24d0d8 feat(book): J1.b — distinct Pages-overview empty state when only chapters exist
The starter-template panel fired on '!pages.length' which is now
ambiguous: a user can have chapters (counted in pages[]) but no
designed pages, and the Pages tab needs to say something. Splits
into three cases:

  (1) no designed pages AND no chapters → starter templates (as
      before, with the hint updated to point at the new Chapters tab
      for + Add chapter)
  (2) chapters but no designed pages → 'No designed pages yet' panel
      with + Add page / + Add 10 pages / Go to Chapters buttons
  (3) at least one designed page → render the grid normally

Phase J1 polish — pure UI; data model unchanged.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:57:23 -04:00
thePR0M3TH3ANandClaude Opus 4.7 1e6f2e9a57 feat(book): Phase J1.a — Chapters tab + Pages/Cover/Chapters split
First step on the phase-j-linked-content branch. Splits the book
view's pages-and-chapters mash-up into three tabs (Pages / Chapters
/ Cover) without yet touching the data model or the pagination
engine. Foundation for J2..J6.

What changed:

- New 'Chapters' tab between Pages and Cover. Lists every reflow
  entry in book.pages as a row with title, source (naddr or local
  draft), size, pin / live / private pills, and per-row Edit / Pin /
  Delete actions.
- '+ Add chapter' button moved off the Pages overview's toolbar and
  onto the new Chapters tab. Pages toolbar now reads cleanly:
  Add page / Add 10 pages / Import page / Read / Export PDF.
- Pages overview hides reflow-entry tiles via a CSS rule
  (display:none on .bookPageTile.reflowSegment). Data still lives
  in book.pages — drag-reorder indices unchanged, pagination engine
  unchanged, PDF export unchanged. J2+ migrates the data out.
- Count readout updated from '0 pages · 0 reflow' to
  'N pages · M chapters' (uses 'design' count + 'reflow' count).
- defaultBookState + ensureBookState now scaffold empty links[] and
  threads[] arrays so the rest of the codebase can assume they
  exist. No code reads them yet.
- setBookSubView extended to handle three views, sets active class
  + display + repaints the active list. renderBookChaptersList
  hooked into the main render() loop only when its tab is visible.

Everything that worked before still works — chapter editor, publish
flow, PDF export, Reader Mode, all untouched. The visible change is
the new tab + the cleaner Pages overview.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:46:46 -04:00
thePR0M3TH3ANandClaude Opus 4.7 79c89101c4 docs: Phase J spec — Linked Content + threaded text frames
Drafts the next architectural arc for the Book Designer around two
ideas:

- Events are linked files. Generalizes the pin-vs-live toggle
  shipped for chapters to every external reference. A new
  book.links[] collection becomes the project's 'Links panel'
  (chapters, masters, pages, illustration sets, future asset kinds).
- Threaded text frames (InDesign-style). First-class text-frame
  layers on designed pages, threaded port-to-port; a thread
  declares a content source (a linked chapter event) and the
  pagination engine pours text through the frame chain.

The current 'reflow entries in book.pages' model collapses into
links[] + threads[] + auto-generated designed pages — a one-time
migration on load. Pagination engine, PDF export, Reader Mode,
Linked Designs resolver, and NIP-23 chapter events all survive.

Phasing J1..J6 captured in the spec + TODO. No code yet — this is
just the design doc and arc placement.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:36:45 -04:00
thePR0M3TH3ANandClaude Opus 4.7 3f5540712b fix(book): stop double-offsetting cover layers in the preview composite
The earlier cover-preview commit assumed layers were stored in
panel-local coordinates (0..trimW relative to their panel's trim
corner). They're not. Cover layers are appended directly to
#layerOverlay (renderLayers, ~line 22344: 'el.style.left = inches(layer.x)'),
which lives inside #sheet, so layer.x is sheet-absolute: a back
layer's x already starts at >= bleed, a front layer's x already
starts at >= bleed + trimW + spineW (targetBounds() seeds them
there at creation time). Adding backX / spineX / frontX in the
preview shifted every layer twice — front cover content slid off
the right edge of the canvas, spine content drifted onto front,
back content drifted onto spine.

Fix: just remap target to 'canvas' and pass x / y through. The
panel-offset variables are kept (renamed in scope) only for the
overlay's fold-line and label positioning, which IS in absolute
spread coordinates.

The 'spec backfill' from the prior commit still stands — defensive
against undefined coverHasBack / coverHasSpine on legacy state —
but the visible misalignment in the preview vs. the editor was this
coordinate-system mismatch.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:23:46 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ef7e85a418 fix(book): backfill cover spec flags so older books don't drop back/spine layers
ensureBookState() now fills in any defaultBookSpec() fields missing
from state.book.spec. Older saved books that pre-date the
coverHasBack / coverHasSpine flags would otherwise restore with those
fields undefined, and the eleven '!!s.coverHasBack' / '!!s.coverHasSpine'
truthiness checks scattered across the cover-preview filter, sheet
sizing, renderDimensions, the cover edit slot layout, and the PDF
export pipeline would all read those as 'false' — silently filtering
back-cover and spine layers out of the spread.

User symptom: a cover with text + linked designs + a background shape
that spans the spread would render only the front panel's content,
because the back / spine layers were being dropped by the filter.
The spread width also collapsed to front + bleed, throwing off the
bleed visualization.

renderBookCoverPreview() now calls ensureBookState() before reading
the spec so the backfill runs even if no prior code path touched the
book this render cycle.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:10:19 -04:00
thePR0M3TH3ANandClaude Opus 4.7 842e672fc0 feat(book): load cover from Nostr or JSON (+ fix bookCoverPayload name collision)
Two new import paths for book covers:

- Load cover from Nostr: paste an naddr / nevent pointing at a
  casewrap-page cover-spread event. Pulls layers + spec hints (trim,
  bleed, hasBack, hasSpine) + the publish ref so the existing
  Re-publish cover flow keeps replacing in place.
- Load cover from JSON: file picker that accepts the format
  bookCoverFileExportPayload() emits. Applies layers + spec hints;
  clears book.cover.ref because the file isn't yet published.

Both ask before overwriting an existing cover and update the live
preview immediately.

The 'Replace cover from Nostr…' button was already in the HTML but
hard-disabled with a 'Phase D1 stub' note — now wired and re-labelled
'📥 Load cover from Nostr…'.

Also fixes a name collision from the prior JSON-export commit:
bookCoverPayload() was defined twice (Nostr publisher at line 11938,
file exporter that I added at line 26056). JS function hoisting let
the later one win, silently breaking publishBookCoverToNostr's
'page.layers' lookup. Renamed the file exporter to
bookCoverFileExportPayload() so both coexist.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:05:25 -04:00
thePR0M3TH3ANandClaude Opus 4.7 c66b1c03af fix(book): cover preview paints actual layers + book-aware project-title readouts
Two fixes wrapped together because they're both about the user
not seeing a meaningful preview in book mode.

1. renderBookCoverPreview() now paints the actual back / spine /
   front layers into a single composite canvas the size of the full
   wrap-around spread, using the same renderCustomArtPreviewDOM
   helper the Pages-overview tiles use. Each layer's target is
   remapped to 'canvas' and offset by its panel's position within the
   spread (back: x=bleed, spine: x=bleed+trimW, front: x=bleed+
   trimW+spineW). On top: a dashed-red trim guide, dashed fold-line
   dividers, subtle 'Back / Spine / Front' panel labels, and an
   empty-state hint when no cover artwork exists yet. The geometric
   panel-mock fallback is gone — the .bookCoverPanel CSS still ships
   but is now dead.

2. renderDimensions() no longer falls through to the DVD-cover
   else-branch in book mode. The 'Trim: 10.8 × 7.25 in / PDF page:
   8.50 × 11.00 in (portrait)' strings that showed for books were
   the DVD totalTrimW + state.trimH leaking through. A dedicated
   book branch now reads from state.book.spec and shows
   'Trim: 6 × 9 in / Spread: ... (with bleed)' when editing the
   cover, 'Page: ... (with bleed)' otherwise.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 15:00:26 -04:00
thePR0M3TH3ANandClaude Opus 4.7 faa4849523 fix(book): show page-edit bar in cover-edit mode + add Book/Meme/Other categories
- The bookPageEditBar CSS only matched .editing-book-page, so the bar
  (Back / Publish / Proof / Cover JSON) was completely hidden while
  editing the cover. Added .editing-book-cover to the selector so the
  bar shows in both modes.
- Back button label is now '✓ Done — back to Cover view' with a tooltip
  that says changes are autosaved. The old 'Back to Cover view' label
  hid the fact that work persists automatically.
- mediaCategories: added 'Book', 'Meme', 'Other'.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 14:54:59 -04:00
thePR0M3TH3ANandClaude Opus 4.7 6c33571329 feat(book): JSON export — whole book + cover-only
Two new payload builders:

- bookPayload() — captures spec, pages, masters, cover metadata,
  every layer that targets a book surface. Hooked into downloadProject
  so Save Project (JSON) in book mode now writes a real, round-
  trippable book file instead of falling through to coverTemplatePayload
  (which silently wrote a malformed DVD-cover JSON for books).

- bookCoverPayload() — cover-only payload with the three cover panels
  + the spec fields the cover needs to lay out correctly (trim, bleed,
  safe, spine width snapshotted at export so the file stays portable
  between books with different page counts). Surfaced via a new
  '💾 Cover JSON' button in the page-edit bar that only shows in
  cover-edit mode.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 14:50:29 -04:00
thePR0M3TH3ANandClaude Opus 4.7 9b5d6fa459 ui: disable trackpad two-finger swipe-to-navigate
Adds 'overscroll-behavior-x: none' on html / body so the browser
treats horizontal trackpad swipes as no-ops instead of back / forward
navigation. Vertical scroll is unaffected. Prevents the classic
'I lost my work because I scrolled the canvas' design-tool gotcha.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 14:43:02 -04:00
thePR0M3TH3ANandClaude Opus 4.7 3f5d244a8e fix(book): Edit cover now actually shows the cover scaffolding
Two bugs prevented the book cover editor from rendering anything
visible:

1. body.template-book had an unconditional 'display:none !important'
   on .coverOnly (and on .bleedFill, .trimArea, .foldLine, .spineText),
   so when editing-book-cover was set the slot boxes, fold lines, crop
   marks, and trim guides stayed hidden. The hide rule now uses
   :not(.editing-book-cover) for the cover scaffolding while still
   unconditionally hiding the disc/jewel scaffolding (which never
   belongs on a book cover).

2. The .slot positions are driven by --panel-w, --spine-w, --trim-h,
   --bleed, --safe CSS custom properties. renderDimensions() was
   writing DVD-cover state.* values into those for every render,
   including in book cover mode — so even if the slots were visible
   they would have been sized for the last DVD preset, not the book
   spec. renderDimensions now writes book-spec values into the CSS
   vars whenever state.book.editingCover is true, so the back / spine
   / front panels lay out at the book's trim with the spine derived
   from page count × paper thickness.

For the asymmetric cases (coverHasBack=false or coverHasSpine=false),
a new applyBookCoverSlotLayout() helper writes inline left / width
overrides for the slot, trim, fold line, and crop-mark elements so
they sit in the right places. clearBookCoverSlotLayout() drops those
overrides whenever we leave cover edit mode so the CSS defaults take
back over. New body classes no-cover-back / no-cover-spine hide the
slot box for the missing panel.

Slot placeholders ('Enter back image URL' etc.) are hidden in book
cover edit mode — those belong to the DVD URL flow, not the book
cover layer system.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 14:40:01 -04:00
thePR0M3TH3ANandClaude Opus 4.7 549d6a61d9 ui: 'Beta' badge on the Book layout tab + experimental banner in the Book sidebar
Surfaces that Book Designer is still under construction in two places:
- An amber 'Beta' pill on the Book layout-picker tab so users see it
  before they switch modes
- A full-width amber notice at the top of the Book sidebar fieldset
  that's always visible whenever the user is working in Book mode,
  with a short explanation of what works and what to expect

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 14:23:25 -04:00
thePR0M3TH3ANandClaude Opus 4.7 5706c4b21a docs: 'Copy as markdown' button in the docs modal header
Each docs page now has a header button that copies the raw markdown
source to the clipboard. Useful for pasting the docs into the Book
Designer chapter editor as test content.

- _docsCache now stores { html, md } so the raw source survives the
  marked.parse() pass without a re-fetch on copy
- _docsActiveMd tracks the currently displayed page's source
- Button shows a brief "✓ Copied" confirmation and routes through
  toastSuccess / toastError for status

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 14:14:08 -04:00
thePR0M3TH3AN 0f18580178 Merge book-designer: Book Designer feature + in-app docs + contextual help icons
67 commits delivering the Book Designer arc (phases A-I) plus the
in-app 'Read the docs' markdown viewer (30 pages across 5 groups)
and ~48 contextual ⓘ help icons knitted into tabs, layouts, panels,
tool sections, the pixel-art UI, welcome / community / tip modals.
2026-06-04 13:45:30 -04:00
thePR0M3TH3ANandClaude Opus 4.7 388ca5fce2 fix(docs-icons): use capture-phase delegation so clicking ⓘ inside a button doesn't fire the button's handler
Layout-tab buttons (mode-cover / mode-disc / etc) and app-mode tabs
(modeTabTemplate / modeTabDesigner) have direct click listeners that
fire during the bubble phase. The previous bubble-phase docs
delegation ran AFTER those handlers — so clicking the ⓘ inside a
layout tab would swap modes *and* open the docs.

Switching the docs handler to capture phase intercepts the click
before it reaches the wrapping button's bubble listener, and
stopPropagation prevents bubble delivery entirely. Now the ⓘ
opens docs without changing modes.

Verified with a slug-integrity sweep: every data-help attribute in
the UI resolves to a real _DOCS_TOPICS entry (no 404s).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 10:17:19 -04:00
thePR0M3TH3ANandClaude Opus 4.7 12b6beaffa docs: help icons in welcome / community / tip modals
Three more surfaces where docs help is high-value at the moment a
user is making a decision:

- Welcome modal h2 — opens the Overview docs page so first-run
  users can orient themselves before picking a starting layout.
- Browse Community modal h2 — opens the Publishing overview
  (public/private/premium comparison + tipping vs unlocking).
- Browse Community Premium tab — opens the dedicated
  Premium-publishing page so users browsing locked designs can
  read about how unlocking works before clicking ⚡.
- Tip modal h2 — opens the Zaps page; restructured the title
  area as a flex row so the icon survives the dynamic
  textContent updates that swap "Send a tip" vs other labels.

Coverage is now 48 ⓘ icons across the UI.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 10:13:18 -04:00
thePR0M3TH3ANandClaude Opus 4.7 4ff705709e docs: help icon in the pixel-art editor toolbar
Adds an ⓘ at the start of the pixel editor's tool bar (left of the
pencil/eraser/fill tool group) that opens the Pixel art docs page.
Pixel mode runs through its own bespoke toolbar (not the standard
left-sidebar fieldset flow), so the editor bar is the right home
for the icon.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 10:02:56 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ca2a722656 docs: help icons on layout-picker buttons + book sub-surfaces
Each individual layout button now carries its own ⓘ so authors get
straight-to-the-page help even before picking a mode. Same delegated
click handler from the previous slice — the layout-tab's mode-switch
click and the icon's docs-open click coexist because the docs handler
stopPropagation's the event before the tab handler sees it.

Layout-picker buttons (8):
- Template tab: Case cover, Disc labels, Slide deck, Book.
- Designer tab: Custom art, Slide, Pixel art, Disc design.

Book sub-surfaces (4):
- Pages / Cover toggle bar — opens the Book page.
- Page editor top bar (book-page + book-master editing) — opens the
  Book page.
- Chapter editor toolbar — opens the Book page.
- Reader Mode header — opens the Book page.

CSS:
- .layoutTab .docsHelpIcon — smaller (.76rem) + reduced opacity by
  default; active state inverts colour to white-on-accent so the
  icon stays readable on a selected tab.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 09:59:09 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ad39a72554 docs: contextual ⓘ help icons across the UI
Every major surface now carries a small ⓘ glyph that opens the in-
app docs modal directly to that surface's page. Single delegated
click handler on document.body (data-help attribute → openDocsModal
slug); zero per-icon wiring.

Placement (30+ icons):

- App-mode tabs — Template → template; Designer → designer.
- Sidebar legends (18) — Layout/Template/Canvas/Slides/Book/Deck
  theme/Artwork/Disc Layout/Jewel Inserts/Layers/Project metadata/
  Credits/Display options/Print & Save/Save & Export plus the
  Designer-tab equivalents — each linking to its matching page.
- Tool-options pane headings (6) — Pen tool, Direct Selection,
  Path actions, Pencil tool, Shape tool, Text tool — each opens
  its dedicated tool page.
- Modal titles (4) — Document settings, Export PDF, Master pages,
  Ready-to-publish — the publish-confirm h2 was restructured to a
  flex row so the icon doesn't get wiped by the JS that swaps the
  textContent.
- Settings → ⚡ Lightning wallet → opens the NWC setup page.

CSS:
- .docsHelpIcon — 16×16, muted color, inline-flex so it nests
  cleanly next to headings/labels. Hover brightens + scales 1.1.
- App-tab variant tones the colour down further (rgba on white +
  active states) so the icon doesn't compete with the tab label.

Behaviour:
- Cmd/Ctrl/Shift clicks pass through (let the browser handle if
  the icon is ever wrapped in a link).
- Each icon has role=button + aria-label + title for accessibility.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 09:54:53 -04:00
thePR0M3TH3ANandClaude Opus 4.7 7d63c353d5 TODO: surface industry-convention parity gaps in vector tools
The docs audit (commit ef03f73) caught several universal design-tool
conventions that aren't wired in the vector toolset — most are
single-branch additions to existing drag handlers. Capture them in
TODO.md under "Design-tool follow-ups" as a discrete cluster so we
remember they exist.

The 14 items:
- Select tool: Shift-constrain-axis on drag, Alt-drag duplicate,
  Shift-aspect-lock on corner scale, Shift-rotation 15° snap.
- Global: Cmd+A select-all, Spacebar temp-pan, Cmd+0 fit-zoom,
  Cmd+=/- zoom step.
- Shape tool: Shift-constrain to perfect primitive, Alt-from-center
  draw.
- Text tool: drag-to-size.
- Pencil tool: smoothing slider, Alt-drag append, auto-close near
  start.

Each entry notes rough scope so we can pick them off in any order.
None are blockers; the docs audit just reminded us they're missing.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 09:39:55 -04:00
thePR0M3TH3ANandClaude Opus 4.7 10a5022e9c docs: publishing tiers + zaps + NWC + JPEG/PDF fallback
Adds a "Publishing & payments" group covering the three tiers, the
Lightning plumbing, and how to wire a wallet up:

- publishing.md            — Overview of Public / Private / Premium
                             with a comparison table; how tipping vs
                             unlocking differs; replaceability +
                             republish-vs-fork.
- publishing-public.md     — Default tier. Event shape, tag layout,
                             discoverability, edit-vs-fork.
- publishing-private.md    — End-to-end encrypted to self via NIP-44
                             / NIP-04. AES-256-GCM pipeline, what stays
                             visible (pubkey, kind, d-tag), multi-
                             device decrypt via "Mine" tab, caveats
                             (no multi-recipient envelopes in v1).
- publishing-premium.md    — Zap-gated soft-gate publishing. Soft-gate
                             key derivation, watermarked preview,
                             zap-split tags (creator + platform),
                             buyer unlock flow, My Purchases vault,
                             honest framing about soft-gate limits.
- zaps.md                  — NIP-57 lightning payments. Tipping vs
                             unlocking. How to receive zaps (set
                             lud16 on profile). Fallback flow without
                             NWC (BOLT11 + QR + external wallet).
- nwc.md                   — Nostr Wallet Connect (NIP-47) setup.
                             CoinOS quickstart, supported wallets,
                             multi-device sync via NIP-44 encrypted
                             event, test-connection button, security
                             model (treat URI like a password + set a
                             budget).

Plus a "Why JPEG sometimes routes through PDF" section added to
panel-print-save.md, explaining the three fallback cases (CORS-
blocked images, tainted canvas, unsupported mode) and the auto-
switch to the print → PDF path that the browser's print engine
can handle.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 09:37:04 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ef03f731d1 docs: audit pass — fix wrong shortcut + behaviour claims
Swept the help pages against the actual code paths and removed /
corrected claims that didn't ship.

vector-tools.md
- Removed: spacebar temp-pan, Alt duplicate-as-you-drag, generic
  Shift-constrain.
- Added: verified shortcuts (Cmd+Z/Y/D/C/X/V/G, Cmd+]/[ with
  Shift modifier, Cmd+J / Cmd+Alt+J in Pen edit mode,
  Delete/Backspace for layers + anchors).

tool-select.md
- Removed Cmd+A (not wired), Alt-drag-duplicate (not wired),
  Shift-constrain-axis drag (not wired), Cmd-click stack-walk
  (not wired). Kept the verified marquee + multi-select.

tool-direct-select.md
- Re-wrote anchor / handle interactions to match the actual hit-
  test branches (Alt-click anchor toggles kind in one click; Alt-
  drag a handle breaks symmetry; Alt-click segment inserts an
  anchor; plain drag of a segment bows it). Removed the "click an
  endpoint to continue drawing" claim — that's a Pen-only flow.

tool-hand.md
- Removed every fictional zoom shortcut (Cmd+wheel, Cmd+0,
  Cmd+= / Cmd+-). Documented the real zoom controls (−/+/Fit
  buttons + dropdown in the canvas toolbar). Spacebar reposition
  scoped correctly to the Pen tool only.

tool-pen.md
- Clarified that the Pen options pane has its own Fill / Stroke
  inputs (separate from any "Stroke panel" that doesn't actually
  exist).

tool-pencil.md
- Removed every claim that wasn't true: smoothing slider, Alt-drag
  append, auto-close. Pencil writes a plain polyline (M…L L L…),
  one layer per stroke. Tool options pane has only colour + width.

tool-shape.md
- Filled in the missing primitives (rounded-rect / circle /
  triangle — total 8, not 5). Removed Shift / Alt drag modifiers
  that aren't checked in startShapeDrag / commitShapeFromDrag.
  Added the small-drag → default-size fallback that the code does
  do.

tool-text.md
- Replaced the "drag a rectangle to size" claim with the actual
  click-to-place behaviour (placeTextWithTool drops a fixed-size
  box at the cursor + auto-flips to Select with the box focused).
  Softened the Cmd+B/I/U claims to "browser native rich-text
  shortcuts" since they're not wired in the app code.

tool-eyedropper.md
- Replaced the fictional "inline ⊙ buttons next to colour fields"
  with the real OS-colour-picker eyedropper that Chrome's native
  <input type="color"> shows.

panel-layers.md
- Removed Cmd+A select-all (not wired). Added Shift modifier to
  Cmd+]/[ for bring-to-front / send-to-back. Clarified that
  position units are inches in print modes, pixels in Custom Art
  / Slide / Deck (matches the unit toggle behaviour).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 09:32:11 -04:00
thePR0M3TH3ANandClaude Opus 4.7 e9f3682bff docs: sidebar-panel pages — left fieldsets + right Tool Options pane
Adds a "Sidebar panels" group to the in-app docs:

- panels.md             — overview + a table of every sidebar panel
                          with where it lives + a one-liner
- panel-metadata.md     — Project Metadata fields (title, category,
                          IMDb/UPC/TVDB/MBID/custom-tag/language)
                          + how they feed publish + designer-mode
                          equivalent
- panel-layers.md       — Layers panel — per-mode surface scoping
                          (Cover/Disc/Jewel/Custom Art/Slide/Deck/
                          Pixel/Book), per-row controls, reorder +
                          group + multi-select, layer-options
                          field list
- panel-export.md       — Export options panel — show/print toggles
                          for guides/bleed/safe/crops/fold, mode-
                          specific hides
- panel-print-save.md   — Save / Open project JSON + Print/Save-as-
                          PDF print-dialog tips + Export JPEG/PNG +
                          mode-specific gotchas
- panel-credits.md      — Credits panel — Linked Designs contributor
                          surfacing, tip button, publish-time tag
                          emission, private-publish behaviour
- panel-tool-options.md — Right-side floating Tool Options pane —
                          how it switches between tool options and
                          layer options, cross-links to per-tool docs

Registered as a new "Sidebar panels" group ordered after Vector
tools in the docs sidebar.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 09:08:27 -04:00
thePR0M3TH3ANandClaude Opus 4.7 2d201ee522 docs: per-tool pages for the vector-canvas toolbar
Adds a new "Vector tools" group to the in-app docs sidebar with one
page per toolbar tool + one page per supporting panel:

Toolbar tools (8):
- tool-select.md           — Select (V): move/scale/rotate whole layers,
                             multi-select, marquee, dive-into-path
- tool-direct-select.md    — Direct Selection (A): per-anchor edits,
                             handle break, segment-direct-edit
- tool-hand.md             — Hand (H): pan + temp-pan via Spacebar,
                             plus zoom controls (which work from any
                             tool)
- tool-pen.md              — Pen (P): full Illustrator parity —
                             Bézier draw, mid-draw spacebar reposition,
                             Alt handle-break, auto-add/delete anchors,
                             Cmd+J join, Cmd+Alt+J average
- tool-pencil.md           — Pencil (B): freehand → smoothed Bézier
- tool-shape.md            — Shape (S): rect/ellipse/polygon/star/line
                             primitives + Shift/Alt modifiers
- tool-text.md             — Text (T): rich-text layer + Type panel
                             + token notes
- tool-eyedropper.md       — Eyedropper (I): window.EyeDropper sample +
                             inline ⊙ buttons + browser-support notes

Supporting panels (3):
- pathfinder.md            — Unite/Subtract/Intersect/Exclude via the
                             vendored polygon-clipping
- align-distribute.md      — six align ops + four distribute ops, with
                             behaviour around locked layers
- free-transform.md        — multi-layer scale + rotate handles on
                             the selection bbox

Plus an overview page (vector-tools.md) with a keyed table of every
shortcut, a description of how the toolbar interacts with the Layers
panel, and the canvas-level keyboard shortcuts (Shift/Alt/arrow
nudges/Cmd+D/etc).

All linked into _DOCS_TOPICS as a new "Vector tools" group, ordered
after the existing Template-mode layouts section.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 08:59:47 -04:00
thePR0M3TH3ANandClaude Opus 4.7 23a16c8e89 docs: in-app "Read the docs" modal + per-mode help pages
Adds a 📖 Docs link to the sidebar footer (next to GitHub + artstr.org)
that opens a Read-the-Docs-style two-pane modal: topic sidebar on the
left, rendered markdown on the right.

Content (src/help/*.md, 11 files):
- index.md            — overview + nav
- template.md         — Template tab explainer
- designer.md         — Designer tab explainer
- cover.md            — Case cover wrap
- disc.md             — Disc-label sheet
- jewel.md            — Jewel-case insert
- customart.md        — Custom art
- slide.md            — Slide
- deck.md             — Slide deck
- pixelart.md         — Pixel art
- book.md             — Book Designer (links out to the deeper
                        BOOK_DESIGNER_TUTORIAL.md + spec on GitHub)

Implementation:
- _DOCS_TOPICS registry maps slug → { title, group, file }. Sidebar
  groups headings under "Start here", "App tabs", "Template-mode
  layouts".
- loadDocsTopic(slug) fetches `help/<slug>.md` (force-cache), renders
  via the already-vendored marked, caches the rendered HTML for
  session-instant re-visits, and updates the URL hash via
  history.replaceState so deep links work.
- #/help/<slug> hash route auto-opens the modal at that topic on
  page load + on hashchange.
- Esc closes; backdrop click closes; internal `#/help/foo` links in
  page content load via the dispatcher (no page bounce); external
  http(s) links get target="_blank" + noopener.

Styling:
- Inherits the rest of the modal aesthetic (var(--line),
  var(--accent), system font for chrome, Georgia serif for body
  text). Dark-mode-aware backdrops on code / blockquote / table
  blocks.
- Two-pane layout collapses to a narrower sidebar on <720px viewports.

Files live in src/help/ (not docs/) because Vercel's outputDirectory
is "src" — the production site only serves files under src/. The
canonical deeper docs (BOOK_DESIGNER_TUTORIAL, FEATURE specs) stay
in docs/ and are linked-out from the in-app pages.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 08:52:34 -04:00
thePR0M3TH3ANandClaude Opus 4.7 f50d92043c docs: add BOOK_DESIGNER_TUTORIAL.md
Hands-on end-to-end walkthrough for the Book Designer feature —
setup, starting a book (templates / deck-import / scratch), Document
settings, masters + text-frame, Pages overview, designed-page editor,
chapter editor (full feature exercise: tables, task lists, footnotes,
xrefs, {toc}, {index}, ^[term]), cover view, visibility chip,
publishing order, resolver behaviour, Reader Mode, embed integration,
PDF export modal, tokens reference, edge cases to probe, and a
codebase map.

Companion to docs/BOOK_DESIGNER_FEATURE.md (the spec).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-04 08:41:25 -04:00
thePR0M3TH3ANandClaude Opus 4.7 0651a3e4fc book(I4): footnote refs + chapter-end definitions (v1)
Inline \`[^N]\` markers render as Unicode-superscript numerals
(⁰¹²³…) and \`[^N]: definition\` lines collect into a "Footnotes"
section appended to the chapter (after the body, separated by a
horizontal rule).

How it works:

- _processBookFootnotes(md):
  1. Sweeps definitions via /^[ \t]*\[\^id\]:[ \t]+(.+)$/gm,
     stores them in a Map keyed by raw id, strips the line from
     the body.
  2. Renumbers: each defined id gets a 1..N number based on first
     encounter of its \`[^id]\` ref in the body. Refs without a
     matching def pass through unchanged.
  3. Replaces every resolved ref with _bookSuperscript(num) so
     ¹² renders as actual superscript glyphs.
  4. Appends a "### Footnotes" section with one bullet per
     definition in canonical (first-ref) order.

Substitution sites:
- paginateChapter: runs after the {index} expansion + marker
  stripping, before xref resolution. Only fires when \`[\^\` is
  present in the source so most chapters pay zero cost.
- markdownToSafeHtml: same flow for the live preview pane.

Known v1 limitation (deferred to I4.2):
- Definitions render as a single end-of-chapter section rather than
  per-page in a footnote-frame layer on the master. Per-page
  footnote placement requires:
    * A new footnote-frame layer kind on masters (parallel to
      text-frame).
    * Page-aware definition collection in the pagination engine.
    * Page-break logic that keeps a ref + its def on the same page.
  Out of scope for this slice; the chapter-end section is the
  pragmatic v1.

Phase I scope: I1 ✅ I2.1 ✅ I2.2 ✅ I3 ✅ I4 ✅ I5 ✅ I6 ✅.
All spec'd Phase I features ship in v1 form.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:46:45 -04:00
thePR0M3TH3ANandClaude Opus 4.7 5e3e7d1d7b book(I5): \{index}\ token + \^[term]\ inline markers
Authors mark indexable terms with \`^[term]\` inline anywhere in
chapter markdown. A standalone \`{index}\` line expands at render
time into a sorted alphabetical index with the page numbers the
term appears on.

How it works:

- _computeBookIndexEntries(book) walks every reflow chapter and
  scans its markdown for the \`^[term]\` pattern. Each unique term
  collects the page numbers (chapter-start granularity in v1) of
  the chapters it appears in. Results sort alphabetically by
  term.localeCompare. Chapter physical page counts are
  re-derived via paginateChapter({ _skipToc:true, _skipXref:true })
  so the index numbering tracks the same physical-page sequence
  enumerateBookPhysicalPages produces.
- _formatBookIndexMarkdown(entries) emits a "## Index" heading
  + one bullet per term: "- term — Page A, Page B".
- _stripBookIndexMarkers(md) replaces every \`^[term]\` with just
  the term text so the marker stays invisible in the rendered
  body. Done before xref substitution so a marker inside a link
  text doesn't confuse the matcher.

Substitution sites:
- paginateChapter: when opts._skipIndex is unset, expands
  \`{index}\` lines + strips markers. When _skipIndex is true (the
  inner pass triggered by the index builder), strips both the
  \`{index}\` placeholder line AND the markers.
- markdownToSafeHtml: same expansion for the chapter editor
  preview pane, so authors see the index as they type around it.

Phase I scope now: I1 ✅ I2.1 ✅ I2.2 ✅ I3 ✅ I5 ✅ I6 ✅. Only
I4 (footnotes with per-page footnote-frame layer on masters)
remains — it's the deepest of the bunch, requires a new layer kind
+ page-aware definition collection, and is the natural last slice
before the branch lands.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:45:33 -04:00
thePR0M3TH3ANandClaude Opus 4.7 f3d8135a9a book(I6): cross-references — [text](#chapter-N) → page numbers
Markdown links pointing at in-book anchors get their link text
augmented with the destination's page number at pagination time.

Slug matching:
- _bookSlugify(s) = lowercase + non-alphanumeric → hyphen, trim
  edge dashes (matches GitHub-style heading-anchor convention).
- _computeBookSlugToPageMap(book) walks every reflow chapter with
  _skipXref:true to avoid recursion, building a slug → page-number
  map that registers:
    * Each chapter's slugified chapterTitle.
    * "chapter-N" aliases for entries with chapterNumber.
    * Each H1-H6 heading's slugified text (first occurrence wins).

Substitution sites:
- paginateChapter: when the chapter markdown contains `](#anchor)`
  and !opts._skipXref, rewrites every matching link to include
  " (p. N)" in its visible text. Renders through DOM tile thumbs,
  Reader Mode, and PDF real-text emission the same way.
- markdownToSafeHtml: live preview pane gets the same rewrite so
  the author sees page numbers as they type.
- Unknown slugs pass through unchanged so a typo'd anchor stays
  visible as a regular markdown link instead of silently breaking.

Phase I now has every spec'd feature except I4 (footnotes) and I5
(auto-index from inline ^[term] markers) shipped end-to-end.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:43:48 -04:00
thePR0M3TH3ANandClaude Opus 4.7 4b2f124fde book(I2.2): full table layout in pagination + DOM + canvas + PDF
GFM tables are now first-class content blocks across every reflow
rendering surface: tile thumbnails, Reader Mode, PDF export with
real text emission. Replaces the I2.1 "[Table — N×M]" placeholder.

Pagination engine:

- For \`token.type === 'table'\`, computes equal-width columns
  (availW / colCount), wraps each cell's text into lines at the
  column's content width, and tracks row heights = max line count
  per row × line height + cell padding.
- Returns the block with \`tokenType: 'table'\` and a \`tableLayout\`
  payload carrying { colCount, colWidthIn, cellPadIn, align,
  headerCellLines, rows, header/row line-heights, totalHeightIn }.
- blockH baked from the layout so the page-break logic treats
  tables identically to other blocks.

DOM (paintReflowPageOverlay):

- Table blocks render as a real <table> with table-layout:fixed
  and per-column text-align, header in bold with a solid bottom
  border, body rows separated by hairline borders. white-space:
  pre-wrap preserves the engine's wrap output.

Canvas (renderBookReflowPhysicalPageToCanvas):

- Each cell draws via fillText at the column's offset; alignment
  honours the cell's column align directive. Hairline strokes
  separate the header row + each body row so the table reads as
  a grid even at lowish DPIs.

PDF real-text emission:

- When the block's font resolves to a StandardFonts key, each
  cell's lines emit as textOps with leftIn / widthIn / align
  scoped to the column's content rectangle. Header cells force
  the bold variant so the printer sees real bold glyphs.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:41:49 -04:00
thePR0M3TH3ANandClaude Opus 4.7 d16c475dca book(I3): \{toc}\ token — auto-generated table of contents
A standalone \`{toc}\` line in any chapter's markdown expands at
pagination time into a list of every reflow chapter's H1 / H2 / H3
headings paired with their physical page number.

Two-pass internally:

- _computeBookTocEntries(book) walks the manifest and paginates
  each reflow chapter with { _skipToc: true } so the inner pass
  treats {toc} as an empty placeholder, then collects every
  heading block plus the page number it lands on. Driven off the
  same numbering rules enumerateBookPhysicalPages uses
  (startAt / firstNumberedPage / skipNumber / skipNumberOnFirstPage).
- paginateChapter, when called without _skipToc and the markdown
  contains a standalone \`{toc}\` line, replaces that line with the
  generated TOC markdown before lexing. The TOC chapter itself
  paginates normally with the expanded content.
- markdownToSafeHtml does the same substitution so the chapter
  editor preview pane shows the rendered TOC as the user types
  around it.

Known v1 limitation:
- TOC page numbers come from the pre-expansion enumeration; if
  the TOC itself takes N pages, downstream chapter starts shift
  by ~N from what the TOC reports. For typical books this is a
  1–2 page offset. A full converging iteration is a follow-up
  (acceptable v1 trade-off so we don't spin paginating the same
  book repeatedly on every render).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:36:49 -04:00
thePR0M3TH3ANandClaude Opus 4.7 e5721b67a7 book(fix): tile action buttons + page-number chip always on top
The X / duplicate / proof / master-picker chrome on Pages overview
tiles was rendering behind the composited master+page thumbnail
because text layers carry their own zIndex inline (layer.z) and
the actions container had no stacking context.

- .bookPageTileActions gains z-index: 20 and the per-button
  children + master <select> get z-index: 21 with position:
  relative so they create their own stacking contexts (necessary
  for the select to dropdown above neighbouring tiles too).
- .bookPageTileNum gains z-index: 10 + a translucent white
  background so the page-number chip stays legible over dark
  text layers.

Reported: "the X button on the pages overview slide is behind
the master content. The pages buttons like the X should always
be rendered on top so the user can see them."

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:35:42 -04:00
thePR0M3TH3ANandClaude Opus 4.7 5caf1d48cd book(I2.1): GFM task lists + nested lists in pagination
marked switches to gfm:true everywhere (lexer + parser), unlocking:

- Task lists — `- [ ] todo` / `- [x] done` parse as list items with
  task:true + checked:bool. The pagination engine emits ☐ / ☑ as
  the marker prefix (replacing the bullet) so paginated and preview
  output both render the checkbox state.
- Nested lists — list items whose tokens contain an inner list
  recurse with a 3-space-per-level indent. Capped at depth 6 so
  pathological input can't blow the stack.
- Autolinks + strikethrough — parsed by marked into the HTML
  preview pane (the pagination engine flattens to plain text so
  strike doesn't visually render in paginated tiles, but the
  inline preview shows it).

Tables get a placeholder row in v1 — "[Table — N cols × M rows: …]"
with a warning surfaced through pag.warnings. Full column layout
ships in I2.2 once the renderer side (DOM + canvas + PDF emission)
gains a per-cell branch.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:32:58 -04:00
thePR0M3TH3ANandClaude Opus 4.7 a46d13f189 book(I1): CodeMirror markdown editor in chapter pane
Replaces the plain textarea with a CodeMirror 5 instance configured
for markdown — syntax highlighting, line wrapping, smart Enter for
list continuation.

Library:
- Vendored CodeMirror 5.65.16 as three files in src/vendor (core,
  markdown mode, CSS). ~188 KB total. Lazy-loaded through
  loadCodeMirrorOnce() so the cost is only paid when a chapter
  opens.

Wiring:
- openBookChapter kicks off _upgradeChapterEditorToCodeMirror after
  the existing sync runs. The upgrade swaps the textarea for a
  CodeMirror instance bound to its DOM node and stores the editor
  handle on ta._cmEditor.
- syncBookChapterEditor pushes value changes through the CM editor
  when present (only if value differs AND the editor doesn't have
  focus — preserves the user's caret + IME composition).
- Editor change → updateBookChapterMarkdown, which already debounces
  history + repaints the markdown preview + page-count readout.
- Enter on a list line auto-continues the bullet (- / * / +) or
  numbered marker (1. → 2.); pressing Enter on an empty list item
  breaks out of the list.
- Falls back gracefully to the plain textarea if the CodeMirror
  download fails (offline / blocked CDN re-host).

CSS:
- Forces .bookChapterEditorBody .CodeMirror to fill its grid cell
  (CodeMirror's default is 300 px); matches the surrounding
  monospace font + line-height so the pre/post-upgrade UX is
  visually consistent.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:08:42 -04:00
thePR0M3TH3ANandClaude Opus 4.7 a0e84d50bc book(H1): per-page paywall toggle (gating intent)
Per-page editor gains a ⚡ Free / ⚡ N sats button that records
the user's paywall intent on the manifest entry. Pages overview
tiles surface a matching amber chip at the bottom-left so authors
can scan paywall coverage at a glance.

- openBookPageGatingDialog(entryId) prompts for a price in sats
  (empty / "0" clears the gating). Records as
  entry.gating = { mode: 'premium', priceSats, previewWatermark }.
- syncBookPageEditBar swaps the button's label, colour, and title
  based on entry.gating; visible only when editing a page.
- renderBookPagesGrid paints a .bookPageTileGateChip on tiles with
  premium gating.

Limitation (deferred): publishBookPageToNostr does not yet route
premium pages through _publishPremiumDesign — for v1 we persist the
intent on the manifest, and the page event still publishes via the
free path. Wiring the encrypted-publish + Reader-Mode unlock CTA
lands in a follow-up (H1.2 / H3).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:06:43 -04:00
thePR0M3TH3ANandClaude Opus 4.7 2f15bdca17 book(G2): embed \?book=<naddr>\ flip-book mode
The chromeless embed viewer now handles book manifests. The route
parser doesn't need a code change — any naddr that decodes to a
casewrap-book event falls into _paintEmbedBook automatically.

How it works:

- _paintEmbed dispatches mode === 'book' to a new _paintEmbedBook.
- The painter seeds state.book / state.layers / state.meta from
  the parsed manifest, then awaits resolveBookSidecars() to pull
  every referenced page / master / cover / chapter event from
  relays. The disk cache from D1.6 makes warm embeds instant.
- After resolution, walks enumerateBookPhysicalPages and renders
  the current page through the same canvas helpers Reader Mode
  uses (renderBookDesignedPageToCanvas /
  renderBookReflowPhysicalPageToCanvas) at ~144 DPI.
- One-page-at-a-time stage with click-to-flip (left half back,
  right half forward), keyboard nav (← / → / Space / Home / End /
  f for fullscreen), and prefetch of the next page.
- Footer chips honour the existing embed params:
    ?controls=0 hides prev/next/fullscreen
    ?attr=0 hides the author chip
    ?open=0 hides the "Open in Artstr ↗" link
    ?page=N (1-based) deep-links to a starting page
- Encrypted-private book sidecars resolve via the existing
  _decryptBookSidecarEvent path, so the same key-wrap-to-self
  rules apply (the embed can show private books for the signed-in
  author across devices; foreign-author private events render
  blank text as expected).

Phase G complete: Reader Mode in the editor + cut-down flip-book
in the embed iframe.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:04:37 -04:00
thePR0M3TH3ANandClaude Opus 4.7 0d0c89da6a book(G1): Reader Mode — full-screen page-flip viewer
Full-screen reader launched from the Pages overview. Walks
enumerateBookPhysicalPages and renders each via the existing
export-canvas helpers (the same path the PDF pipeline uses) at
~144 DPI; pages cache in a session Map for instant revisits.

Affordances:
- Header: ☰ TOC toggle, book title, ✕ Close.
- TOC sidebar: chapter headings + designed-page labels with
  current-page highlight; click jumps. Collapsible (closed by
  default; auto-closes on mobile-width jumps).
- Stage: current page centered in the dark viewport. Click the
  left half to go back, right half to advance. Hover-revealed
  arrows on each side as a backup affordance.
- Footer: "N / total" counter, progress bar, keyboard-hint line.

Keyboard nav: → / Space / PageDown advance; ← / PageUp back;
Home / End jump to first / last; Esc exits. Handler is registered
on open and removed on close so the editor's shortcuts stay live
behind the modal.

Prefetch: after a page renders, the next two pages render
in the background (best-effort, errors silenced) so forward
flips feel instant once the user gets going.

Premium / encrypted handling: the underlying renderers already
decrypt via _decryptBookSidecarEvent and substitute tokens via
bookTokenContext, so encrypted-private books and chapter-token
masters Just Work in Reader Mode too.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:02:48 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ea3fa6f060 book(F3): import a single page from another book
New "+ Import page" button in the Pages overview toolbar takes a
naddr / nevent / note / hex pointing at a casewrap-page event and
adds it to the manifest as a design entry referencing that event.

- Resolves through the shared _resolveEmbedEvent helper (works for
  both authors' own and third-party events; honours encrypted
  envelopes via _decryptBookSidecarEvent for sidecars private path).
- Validates kind 30078 + warns when role isn't "interior" before
  adding.
- De-duplicates: refuses to add a page whose (pubkey, dTag) is
  already in the manifest.
- Seeds the disk cache with the resolved event and applies the
  page's layers immediately so the new tile paints without a second
  relay round-trip.
- Carries the event's `title` tag into entry.label as a sensible
  default sorter label.

Phase F is feature-complete per the spec: starter templates,
deck → book conversion, single-page import.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 18:00:34 -04:00
thePR0M3TH3ANandClaude Opus 4.7 461ab85728 book(F2): deck → book conversion
A new "→ Convert to book" action lives in two places:

- Deck-sorter toolbar (next to "+ Add slide") — for users already
  in deck mode who want to flip their existing slides into a book.
- Book starter panel's "Or import from a deck" block — surfaces
  automatically when the user enters book mode with no pages and a
  non-empty deck.

How the conversion works:

- convertDeckToBook({ presetKey }) resets the book to a starter
  spec (US Trade 6×9 by default; can pass any BOOK_SIZE_PRESETS key)
  with a default master.
- Each slide becomes one designed-page entry. Slide layers
  letterbox-fit into the trim:
    scale = min(trimW / slideWIn, trimH / slideHIn)
    layers reposition to offset + x*scale, offset + y*scale
    layers' w/h scale linearly; fontSize and stroke.width scale too
- Slide background (when non-default) carries to entry.background.
- Slide.name carries to the entry's label.
- Confirms before clobbering an existing book.
- Switches templateMode to 'book' on success + toasts a
  "Imported N slides as designed pages." message.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 17:59:36 -04:00
thePR0M3TH3ANandClaude Opus 4.7 0567133e06 book(F1): starter book templates on empty Pages overview
When a book has no pages yet, the Pages overview now shows a
four-card starter gallery (US Trade 6×9, A5, A4, Square 8×8) instead
of the bare "No pages yet" placeholder. Click a card → fresh book
seeded with:

- The preset spec (trim + bookSize label).
- A default master named "Body pages" with a text-frame layer at a
  0.75 in margin type area — so reflow chapters reflow correctly
  out of the box.
- A starter chapter with friendly placeholder markdown that
  exercises headings / paragraphs / lists / blockquotes so authors
  see the default Georgia / Helvetica stylesheet at work.
- A blank "Title page" designed entry (skipNumber:true) so the
  designed-page editor isn't a dead-end either.

Implementation:

- applyBookStarterTemplate(presetKey) resets the book state
  (preserving state.meta + community), seeds the master + chapter +
  title page, drops any leftover book-* layers from prior sessions,
  and clears lastPublishedManifestSerial so the next publish mints a
  fresh casewrap-book event.
- renderBookPagesGrid's empty branch paints a four-card grid; each
  card is a button with preset metadata + a one-liner use case.
  Click runs applyBookStarterTemplate.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 17:57:04 -04:00
thePR0M3TH3ANandClaude Opus 4.7 55e60150f0 book(E4): "Proof one page" quick export
One-click PDF proof of a single page or single chapter — useful for
sending to a printer to test colour / paper / paper-weight before
committing to a full book run.

- proofBookEntryPdf(entryId, opts) finds the entry's range in the
  physical-page sequence (one slot for designed pages, N slots for
  reflow segments) and calls exportBookToPdf with includeCover:false
  scoped to that range.
- Filename = <book-slug>-proof-<entry-suffix>.pdf where the suffix
  is the chapter title (reflow) or the page label / "page-N"
  (designed) slugified.
- Onboard surfaces:
    * Each Pages-overview tile gets a 📄 action between Duplicate
      and Delete; click runs the proof for that entry.
    * The per-page edit bar gains a "📄 Proof PDF" button next to
      Publish — proofs the currently-open page.
    * The chapter editor gains the same button — proofs all
      paginated pages of the open chapter.
- Status flows back through the same hint slot each surface
  already uses for Publish status, including warning surfacing
  (failed images, fallback fonts).

Phase E now feature-complete per the spec: vendored pdf-lib +
trim/bleed/crop-marks/range/split modal + real PDF text for
reflowed prose + proof-one-page.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 17:54:04 -04:00
thePR0M3TH3ANandClaude Opus 4.7 5ed606e3d0 book(E3): real PDF text for reflowed prose
Reflowed chapter prose now emits as real PDF text — selectable,
searchable, vector — when the block's font maps to one of the 14
built-in PDF standard fonts (Times Roman, Helvetica, Courier
families × four styles each). A 200-page novel that exported as
hundreds of MB of PNG pages in E1 now exports as a few MB with
copy-paste-able text and full font fidelity.

How it works:

- _resolveStandardFontKey(family, bold, italic) maps a CSS family
  name onto a pdf-lib StandardFonts key. Serif families (Georgia /
  Times / etc) → TimesRoman; sans-serif (Helvetica / Arial / etc)
  → Helvetica; monospace → Courier. Returns null for off-list
  fonts so the caller knows to fall back.
- renderBookReflowPhysicalPageToCanvas grew two optional outputs:
  textOps (array — collected positioned text ops) and
  fontWarnings (Set — families that fell back to raster).
- Per block: if the resolved fontKey is non-null and we're in
  PDF-export collect mode, push one op per line into textOps and
  SKIP the canvas draw for that block. Off-list blocks still
  rasterise as before, but their family is added to fontWarnings.

PDF emission:

- exportBookToPdf maintains a per-doc font cache so each
  StandardFonts variant is embedded once across the whole book.
- After each reflow page is stamped, the textOps are emitted via
  pdfPage.drawText with width-of-text alignment maths
  (font.widthOfTextAtSize) for centre/right alignment and a
  baseline = pageHpt − topPt − size×0.8 conversion from inches-
  from-trim-top to pdf-lib's bottom-up grid.
- _pdfRgbFromColor parses #hex / rgb() into pdf-lib's rgb() so
  textStyles colours carry through.

UX:

- The per-export warning summary now includes
  "N font families are not on the embeddable allowlist… those
  blocks fell back to vector raster: <list>" so authors know which
  fonts to swap if they want fully-real-text output.

Known limits (deferred):
- Designed-page text layers still rasterise — they have richer
  styling (inline marks, rotation) that doesn't map cleanly to
  pdf-lib text in one slice. Coming in a follow-up.
- Bold/italic resolution is based on fontWeight ≥ 600 / fontStyle
  === 'italic'; partial weights round to 400/700.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 17:20:32 -04:00
thePR0M3TH3ANandClaude Opus 4.7 ef73d73152 book(E2): PDF export modal with bleed / crop marks / range / split
Replaces the one-click "Export PDF…" with a dedicated modal that
exposes the options the pipeline now supports.

Options:
- Page range — All / 1-based from–to. Editing either input flips the
  radio so the user doesn't have to click it first.
- Include cover spread (default = on when the book has a cover).
- Include bleed margin — pages export at trim + 2×bleed, with the
  trim canvas centered inside; the surrounding strip is the page bg.
- Crop marks — _drawCropMarks emits L-shaped marks outside each
  trim corner via pdf-lib's drawLine (printer guidance for cutting).
- Output: single PDF (interior + cover) or split (interior + cover
  as two files).
- Filename pattern: <name>.pdf, or <name>-interior.pdf +
  <name>-cover.pdf for split mode. Default = title-slug.

Pipeline:
- exportBookToPdf now accepts {dpi, includeCover, includeBleed,
  cropMarks, range:{from,to}, split}. Range filters
  enumerateBookPhysicalPages. Bleed-inclusive pages are sized
  trimW+2×bleed and place the trim canvas at the bleed offset, so
  artwork extends past the trim edge only when bleed-aware layers
  on the page actually do — for v1 the strip stays the page bg.
- Cover spread honours includeBleed too: when off, the bleed-
  inclusive canvas draws at a negative offset so only the trim
  area lands on the (smaller) page. Cover crop marks position at
  the spread's trim corners.
- Split output returns { split: true, interior, cover, warnings };
  single output keeps the existing { blob, warnings } shape.

Modal lifecycle:
- openBookExportModal seeds totals + sensible defaults.
- runBookExportFromModal reads inputs, calls exportBookToPdf, and
  triggers the download(s). Auto-closes on success after 800 ms;
  surfaces warnings inline.
- Click-outside + ESC close behave like other modals.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 17:16:56 -04:00
thePR0M3TH3ANandClaude Opus 4.7 f4243887cc book(E1): vendor pdf-lib + book PDF export skeleton
First slice of Phase E. The Pages overview now has an Export PDF…
button that walks the physical-page sequence, renders each page at
print DPI, and stamps them into a single PDF via pdf-lib.

Library:
- Vendored [email protected].1 as src/vendor/pdf-lib.min.js (~513 KB,
  MIT). Lazy-loaded through loadPdfLibOnce() so the cost is only
  paid when an author actually exports.

Pipeline:
- exportBookToPdf({ dpi, includeCover }) walks
  enumerateBookPhysicalPages(book), rendering each slot at the
  resolved DPI (default 200) onto a trim-sized canvas:
    * Designed pages → master underlay + page layers via
      drawLayerToCanvas, with token substitution applied to master
      text layers (book.spec.textStyles tokens resolve per page).
    * Reflow physical pages → master underlay (with text-frame
      outline stripped) + the pagination engine's block output drawn
      via fillText at the frame's coordinates.
    * Cover → wide spread canvas, all book-cover-* / book-spine
      layers drawn in place.
- Each canvas converts to PNG via canvas.toBlob → Uint8Array, then
  pdf-lib's embedPng + addPage at trimW×trimH points (cover spread
  is its own landscape page at the end).

UI:
- Export PDF… button in the Pages overview toolbar with a status
  line that surfaces progress + warnings (failed image embeds,
  per-page render errors).
- Filename = `<title-slug>.pdf`.

Known v1 limitations (handled in later E phases):
- Raster-only: every page is a PNG inside the PDF. Real PDF text
  for embeddable-allowlist fonts comes in E3.
- No bleed-inclusive output / crop marks / page-range / two-file
  modes yet (E2).
- Linked-design layers + premium-gated content not exercised.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 13:32:20 -04:00
thePR0M3TH3ANandClaude Opus 4.7 55f53aeb49 book(D2 polish): manifest dirty tracking + feed-card preview
Two pieces that close out Phase D2:

Dirty tracking
- isBookManifestDirty() compares the current bookManifestPayload
  serial to state.book.lastPublishedManifestSerial; a missing
  snapshot but any existing ref counts as dirty so the sidebar
  prompts the first publish.
- markBookManifestClean() snapshots the serial on success; called
  from both the public and private manifest publish paths in
  publishCurrentTemplateToNostr.
- syncBookSidebarSummary renders a one-line hint —
  "⚠ Manifest has unsaved changes" or "✓ Manifest is in sync" —
  so authors see when sidecar publishes have outpaced the manifest
  publish.

Feed-card preview
- buildFeedCard now has a `book` branch: a chapbook-shaped card
  (cream-to-amber gradient, Georgia serif title, page + chapter
  counts) so book manifests don't fall through to a blank "Preview
  unavailable" tile in the community browser.
- MODE_LABELS gets 'book': 'Book' so the type chip + fallback label
  read correctly.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 13:27:52 -04:00
thePR0M3TH3ANandClaude Opus 4.7 5b19c25e2b book(D1.7): upstream-update chips on tiles + cover
After the resolver paints from the warm cache, a background probe
queries relays for the latest event matching each naddr ref and
compares against the cached created_at. Refs with a newer upstream
version stage in _bookUpdates; tiles render an "↑ Update" chip,
and the cover-view hint surfaces a matching "Apply update" button.
Click applies the event (decrypting envelopes when private), writes
through to the disk cache, and clears the flag.

Implementation:

- checkBookSidecarUpdates(book) batches every live naddr ref
  (cover / page / master / chapter; pinned eventId refs skipped,
  pinned chapter refs also skipped) by kind:pubkey, runs one
  queryRelays filter per group, and stages newer events in a
  session-only Map.
- applyBookUpdate(ref) reuses the resolver's apply helpers +
  envelope decryption so the application path is identical to a
  fresh fetch.
- Probe fires from resolveBookSidecars(non-force) on a 600 ms
  delay so the warm cache paints first; force-refresh from the
  sidebar skips it (the relays were already hit).
- Tile chip styling lives next to .bookPageTileNum; cover hint
  injects an inline button when hasBookUpdate(book.cover.ref).
- Every successful Publish (page / master / cover / chapter) calls
  clearBookUpdate(ref) so a re-publish doesn't leave a stale
  chip pointing at the version the user just superseded.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 13:17:06 -04:00
thePR0M3TH3ANandClaude Opus 4.7 77514cf408 book(D1.6): localStorage disk cache for book sidecars
A re-open of a published book now paints instantly: the resolver
checks localStorage before relays, and every successful network fetch
+ every just-published event is written back to the cache.

Cache shape:

- Single localStorage key casewrap:bookSidecar:v1 with
  { version: 1, entries: { <refKey>: { ev, fetchedAt } } }.
- refKey is the addressable coord (`<kind>:<pubkey>:<dTag>`) or
  `id:<eventId>` for pinned imports.
- 2 MB total content-size cap; LRU eviction by fetchedAt ascending.
- Read bumps fetchedAt so hot entries stay resident.
- Quota errors clear the cache so a follow-up write can succeed.

Wiring:

- resolveBookSidecars: warm path checks _bookCacheRead first; only
  hits relays on a miss. summary now returns
  { resolved, failed, cached } so the refresh button can surface
  cache hits ("Resolved 12 (10 cached) · 0 failed").
- Force-refresh (the sidebar's ↻ Refresh button) skips the cache so
  the user gets fresh upstream state, then writes the result back.
- Cache writes also fire when each Publish handler completes (page /
  master / cover / chapter) and on chapter import / refresh — so a
  freshly published or imported event is already hot for the next
  reopen.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 12:41:46 -04:00
thePR0M3TH3ANandClaude Opus 4.7 4cabc7a938 book(D1.3): editable cover view + publish
Cover view is no longer a static summary. Click "Edit cover" → enters
cover-edit mode with the canvas widened to the full wrap-around spread
(back + spine + front + bleed); layers land under book-cover-front by
default; the layer-target dropdown lists front / spine / back as
available panels (filtered by coverHasSpine / coverHasBack so a
front-only chapbook just shows one panel).

State + body-class:

- state.book.editingCover flag; body class editing-book-cover.
- CSS gate now reveals sheet/layers/tools whenever editing-book-cover
  OR editing-book-page is set; #bookView hides while editing.
- openBookCover / closeBookCover lifecycle helpers; the shared
  bookPageEditBack button dispatches to closeBookCover when in
  cover-edit mode.

Canvas wiring:

- sheetW returns spread width when editingCover, honouring
  coverHasBack / coverHasSpine.
- targetBounds for book-cover-back / book-spine / book-cover-front
  computes x offsets from the same flags so the front panel starts
  at the bleed edge when there's no back / no spine.
- isLayerForCurrentMode and currentDrawTarget pick up the cover
  surface; templateLayerTargetsForMode lists the three panels for
  the sidebar layer-target select.
- syncBookPageEditBar handles the cover surface: relabels Back /
  Publish, hides the prev/next arrows + text-frame button.

Publish:

- bookCoverPayload assembles a role:'cover-spread' payload —
  cover layers retain their book-cover-front/back/spine targets, the
  coverSpread block snapshots spine width + has-back/has-spine so the
  event renders standalone.
- publishBookCoverToNostr mints kind-30078 with d-tag
  book-cover:<title-slug>, reuses the existing ref's d-tag when
  re-publishing own cover (NIP-33 replace). Honours
  state.visibility for private encrypted publish.
- publishBookSurface dispatches to the cover helper when
  editingCover is set, so the same Publish button serves all three
  surfaces.

UI:

- Cover view gains an Edit cover button (primary).
- Ref hint line reports published / unpublished / "no artwork yet"
  state with the d-tag and 🔒 indicator on encrypted publishes.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 11:55:03 -04:00
thePR0M3TH3ANandClaude Opus 4.7 dc0a5ad20e book(D1.5): Linked Designs resolver for book sidecars
When a casewrap-book manifest loads, the resolver progressively
fetches every referenced page / master / cover / chapter event and
grafts its content into state so a fresh client can reconstruct the
book from refs alone.

- _collectBookSidecarJobs(book, { force }) walks the manifest and
  returns one job per ref whose layers / markdown aren't already in
  state. Idempotent — autosave restore with cached layers triggers
  nothing.
- _refToDecoded turns {kind, pubkey, dTag} or {eventId} into the
  shape _resolveEmbedEvent uses (already proven on the embed route).
- resolveBookSidecars(book, opts) fetches every job in parallel,
  decrypts envelopes via _decryptBookSidecarEvent (works for private
  publishes from D3), and dispatches to per-kind apply helpers:
    _applyResolvedBookPage   — rewrites target to book-page:<id>
    _applyResolvedBookMaster — rewrites to book-master:<id>
    _applyResolvedBookCover  — keeps book-cover-front/back/spine
    _applyResolvedBookChapter — drops markdown into entry.chapterMarkdown
  Concurrent calls coalesce on a single in-flight promise so spamming
  "Refresh" doesn't fan out.
- Public NIP-23 chapter events (kind-30023) fall through to the raw
  ev.content markdown path; encrypted chapters route through the
  decrypt helper.

Wiring:

- loadProjectFromText: new explicit `book` branch sets state.book,
  preserves any existing book-* layers, drops non-book layers, then
  kicks off the resolver async. Default textStyles + spec are merged
  under the loaded ones so older manifests with missing keys still
  render correctly.
- restoreAutosave: when the restored project is templateMode='book',
  fires the resolver to backfill any sidecars whose layers aren't in
  the cached state.
- New ↻ Refresh from Nostr button + status line in the book sidebar
  invokes resolveBookSidecars(state.book, { force: true }) so the
  user can manually pull fresh upstream changes.

This closes the round-trip: publish a manifest + sidecars → open
the manifest on another device → resolver reconstructs the book.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 11:08:40 -04:00
thePR0M3TH3ANandClaude Opus 4.7 988f25c754 book(D3): private publishing for sidecars
Wires chapter / page / master publish to honor state.visibility ===
'private' by routing through the existing PRIVATE_PUBLISHING flow,
plus a visibility chip in the book sidebar so authors see and can
flip the current mode without opening the publish modal.

What changed:

- _publishEncryptedBookSidecar(payload, dTag, extraTags) — wraps
  encryptProjectEnvelope + publishCommunityEvent with an explicit
  stable d-tag, so re-publishes replace via NIP-33 (the existing
  publishEncryptedDesign uses state.privateDTag, which is wrong for
  per-entry sidecars).
- _decryptBookSidecarEvent(ev) — symmetric helper; returns null for
  non-envelope content so the public NIP-23 import path still works.

Per-helper changes:

- publishBookPageToNostr / publishBookMasterToNostr: branch on
  state.visibility; encrypted path uses the same book-page:<id> /
  book-master:<id> d-tag and flags entry.ref.encrypted = true.
- publishBookChapterToNostr: public path stays kind-30023 with
  title-slug d-tag; private path switches to kind-30078 with an
  encrypted envelope under book-chapter:<entry-id> (the slug would
  leak title even though content is encrypted).
- importBookChapterFromNostr / refreshBookChapterFromNostr:
  detect encrypted envelopes and decrypt before storing into
  chapterMarkdown; surface a clear error when the user can't decrypt
  (foreign author's private event).

UI:

- New chip in the book sidebar — "Public" / "🔒 Private" — clickable
  toggle. Disabled when the extension lacks NIP-44/NIP-04. Note line
  explains exactly what each mode does.
- Per-page / per-master / per-chapter Publish buttons gain a 🔒
  badge + tooltip when in private mode, so authors see what's about
  to happen without leaving the editor.
- Sidebar chip + Publish-button labels stay in sync via the existing
  render() pass (syncBookSidebarSummary → syncBookVisibilityChip),
  the publish-modal radio handlers, and a manual sync after the chip
  toggle so the change is immediate.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 11:00:12 -04:00
thePR0M3TH3ANandClaude Opus 4.7 b60acec93b book(D2): publish casewrap-book manifest
Wires the existing top-bar Publish flow so a book in templateMode='book'
emits a casewrap-book manifest event (kind-30078) that references the
sidecar page / master / cover / chapter events instead of inlining
their layers.

- bookManifestPayload() returns a lean manifest — just the spec, the
  cover/page/master refs, the per-entry typography overrides, and
  chapter metadata. Layers stay on their per-surface events.
- _buildBookAttributionTags walks every referenced ref and emits
  matching `p` (role: 'book-contributor') + `link` tags so external
  clients can resolve the sidecars and credit the right authors.
- publishCurrentTemplateToNostr + the communityPublishBtn pre-flight
  both gain a `book` branch that:
    * refuses to publish empty books,
    * refuses to publish when any designed page lacks a ref (would
      point at nothing), telling the author which pages to publish
      first.
- Publish confirm modal renders a lightweight book card (title +
  trim size + entry counts) until cover-view ships a real composited
  preview.
- MODE_LABELS_PRETTY gets a 'book' label so the modal type chip
  reads "Book manifest".

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 08:49:27 -04:00
thePR0M3TH3ANandClaude Opus 4.7 c329eb4839 book(D1.2): publish page + master as casewrap-page events
Adds a Publish button to the per-page / per-master editor bar that
mints a kind-30078 casewrap-page event for that single surface,
signs through window.nostr, publishes to user relays, and stores
the resulting naddr coord on the manifest entry / master.

- bookPagePayload(entry, role) builds the standalone payload —
  layers filtered to just this entry, target prefix dropped so the
  event renders cleanly through Linked Designs / embed routes.
- D-tag: `book-page:<entry-id>` or `book-master:<master-id>`, stable
  across renames so re-publishes replace in place via NIP-33.
- publishBookSurface dispatches to page vs master publish based on
  which mode is active.
- Bar relabels the button "Publish page" / "Re-publish page" /
  "Publish master" / "Re-publish master" with the matching title
  tooltip so authors see the d-tag they're about to overwrite.
- Status hint inline next to the button surfaces signing / publish
  outcome.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 08:45:45 -04:00
thePR0M3TH3ANandClaude Opus 4.7 be5fe7bf18 book(D1.1): publish chapter as NIP-23 article
First chapter of Phase D — the chapter editor now has a Publish
button that mints a kind-30023 article from chapterTitle +
chapterMarkdown, signs through window.nostr, publishes to the user's
relays, and updates entry.textRef so subsequent reads come from
their own event.

- d-tag: reuses entry.textRef.dTag when the user is re-publishing
  their own existing article (NIP-33 replaceability); otherwise mints
  `chapter:<title-slug>` falling back to `chapter:<entry-id>`.
- Tags: d / title / published_at / t=book-chapter.
- Confirms before clobbering a foreign-author textRef with the
  user's own publish.
- Own publishes default to live (textPinnedEventId = null) so future
  edits to the same d-tag flow into the book automatically.
- Sourcebar status flips to "Live · d:…" with the user's own ref;
  Refresh / Pin / Unlink continue to work against the new ref.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 08:43:21 -04:00
thePR0M3TH3ANandClaude Opus 4.7 af3cdf7af0 book(C.5.7): NIP-23 chapter import + pin/live toggle
Adds a source bar to the chapter editor so authors can drop in a
naddr/nevent/note/hex id, pull the markdown via the shared relay
resolver, and choose whether the chapter follows future edits.

- Import button decodes the id with decodeNostrId, resolves the event
  through _resolveEmbedEvent (same logic the embed route uses), copies
  .content into chapterMarkdown, and records textRef.
- nevent imports pin to the resolved event id; naddr imports default
  to live (follow d-tag).
- Pin/live toggle: pinning a live chapter resolves the current event
  id and freezes it; flipping to live just clears textPinnedEventId.
- Refresh re-resolves the linked source — picks up new versions on
  live links, just re-fetches the same id on pinned links.
- Unlink confirms then drops textRef / textPinnedEventId. The local
  markdown stays put.
- Source-bar status chip: "Local only" / "Live · d:…" / "Pinned · …",
  with short id + author preview. Disables the import input while
  linked so the path is unambiguous.
- Picks up the article's NIP-23 title tag when the chapter is unnamed.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 08:38:00 -04:00
thePR0M3TH3ANandClaude Opus 4.7 3a97f54ea0 book(C.5.6): per-tile master picker on Pages overview
Each tile in the Pages overview now has a hover-revealed master picker
that overrides effectiveMasterIdForPage for that single entry.

- Empty selection ("Default (…)") falls through to spec.defaultMasterId.
- "No master" explicitly opts out via masterId === null.
- Otherwise persists the chosen master id on the manifest entry.
- Unified the reflow tile + pagination engine + physical-page enumerator
  to call effectiveMasterIdForPage instead of the local
  `p.masterId || defaultMasterId` short-circuit so the explicit-null
  semantics work everywhere.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 08:34:44 -04:00
thePR0M3TH3ANandClaude Opus 4.7 d24c55ded7 book(C.5.5): textStyles editor in Document settings
Surface book.spec.textStyles as an editable Typography section inside
the Document settings modal so authors can override the v1 markdown
stylesheet without dropping into JSON.

- Per-group schema lists the fields to surface (font/size/weight/color/
  alignment/margins/etc). Adding a row in BOOK_TEXT_STYLE_FIELDS makes
  the field render + persist automatically.
- renderBookTypographyEditor merges defaults under the live spec when
  populating, so selects show the effective value rather than the empty
  default — e.g. a default fontWeight of 700 doesn't render as 400 just
  because the user hasn't customized it yet.
- Apply merges editor output over existing spec + defaults so partial
  customizations don't wipe untouched fields.
- Reset button restores defaults in the editor without applying.
- After Apply, render() repaints reflow tiles and any open chapter
  editor's readout refreshes — typography changes can move page breaks.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-03 08:33:10 -04:00
thePR0M3TH3ANandClaude Opus 4.7 f2252230fa book(C.5.4): substitute {page-number}/{chapter-title}/etc tokens in master text layers
When a master text layer renders on top of a specific page — in tile
thumbnails or the canvas underlay during book-page edit — `{page-number}`,
`{page-count}`, `{physical-page-count}`, `{book-title}`, `{book-author}`,
`{chapter-title}` and `{chapter-number}` resolve against that page's place
in the manifest.

- `enumerateBookPhysicalPages` walks the manifest into a flat physical-page
  sequence, paginating reflow segments and threading chapter context.
- `bookTokenContext` returns the context for a given physical page within
  a manifest entry (designed pages use indexInEntry=0).
- `substituteBookTokens` does HTML-safe string replacement; values are
  escaped before insertion so a chapter title with `<` or `&` can't break
  the layer markup.
- Tile thumbnails for both designed pages and reflow segments now run
  master layers through `applyBookTokensToLayers` before composing.
- The canvas editor substitutes tokens on master text layers when they
  appear as the page-edit underlay (and disables contenteditable so the
  substituted text can't accidentally overwrite the master's source).
  Master-edit mode leaves tokens literal.
- `bookPageCount` (spine-width input) now counts physical pages.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
2026-06-02 21:34:42 -04:00