diff --git a/docs/api-reference/decorations.md b/docs/api-reference/decorations.md index 3b00f16ee..ca7e83a6a 100644 --- a/docs/api-reference/decorations.md +++ b/docs/api-reference/decorations.md @@ -25,8 +25,9 @@ ReaderDecoration( | Field | Type | Description | |-------|------|-------------| -| `style` | `DecorationStyle` | `highlight` or `underline` | +| `style` | `DecorationStyle` | `highlight`, `underline` or `marginMarker` | | `tint` | `Color` | Colour of the decoration | +| `marker` | `MarginMarker?` | Label or icon to show. Required for `marginMarker` | ## DecorationStyle @@ -34,6 +35,18 @@ ReaderDecoration( |-------|-----------| | `DecorationStyle.highlight` | Background colour fill over the text range | | `DecorationStyle.underline` | Underline beneath the text range | +| `DecorationStyle.marginMarker` | Label or icon in the page margin, level with the first line of the range. See [Margin Markers](../guides/margin-markers.md) | + +## MarginMarker + +| Constructor | Description | +|-------------|-------------| +| `MarginMarker.label(String, {side, anchor})` | Text label, such as a page number | +| `MarginMarker.icon(MarginMarkerIcon, {side, anchor})` | Built-in icon: `MarginMarkerIcon.bookmark`, `.note` or `.star` | + +`side` is `MarginSide.start` (default) or `MarginSide.end`, and flips in right-to-left text. Labels are HTML-escaped. Icons are a closed set: the plugin never renders app-supplied markup. + +`anchor` is `MarginAnchor.text` (default), which keeps the marker a small gap from the text column however wide the margin is, or `MarginAnchor.page`, which puts it near the page or column edge. See [Margin Markers](../guides/margin-markers.md#anchoring). ## Applying decorations diff --git a/docs/api-reference/preferences.md b/docs/api-reference/preferences.md index cd115d9af..6c81003eb 100644 --- a/docs/api-reference/preferences.md +++ b/docs/api-reference/preferences.md @@ -33,6 +33,7 @@ Controls the visual appearance of the EPUB reader. All fields are optional unles | `verticalText` | `bool?` | Lay out text vertically (CJK). Auto-derived from `language` if not set. | | `readingProgression` | `EpubReadingProgression?` | `ltr` or `rtl`. | | `firstElementTopMargin` | `int?` | Top margin applied to the first element, in pixels — useful to clear a toolbar. Custom plugin setting | +| `makeSpaceForMarginDecoration` | `bool` | Widen the side page margins with the font size so [margin markers](../guides/margin-markers.md#margin-width) never overlap the text. Never narrower than `pageMargins`. Reflowable EPUB only. Defaults to `false`. Custom plugin setting | ### Theme & color diff --git a/docs/guides/highlights-annotations.md b/docs/guides/highlights-annotations.md index 037201e45..644e98e92 100644 --- a/docs/guides/highlights-annotations.md +++ b/docs/guides/highlights-annotations.md @@ -42,6 +42,10 @@ await reader.applyDecorations('highlights', []); Colours use Flutter `Color` values. The JSON representation uses `rgba(r, g, b, a)` notation. +## Margin markers + +To flag a highlight with an icon in the page margin, or to show page numbers, use the `marginMarker` style. See [Margin Markers](margin-markers.md). + ## Typical group layout ```dart diff --git a/docs/guides/margin-markers.md b/docs/guides/margin-markers.md new file mode 100644 index 000000000..d8131ca77 --- /dev/null +++ b/docs/guides/margin-markers.md @@ -0,0 +1,125 @@ +# Margin Markers + +A margin marker is a small label or icon in the page margin, level with the first line of a text location. Use it for printed page numbers, bookmarks, or any note-style flag that should not cover the text. + +Markers are decorations with the `DecorationStyle.marginMarker` style, so they follow the same group rules as [highlights](highlights-annotations.md): re-applying a group replaces it, and an empty list clears it. They are supported for EPUB on iOS, Android and web. PDF navigators do not support decorations. + +## The marker + +`ReaderDecorationStyle.marker` is required for `marginMarker` and ignored for other styles. A marker is either a text label or a built-in icon: + +```dart +const MarginMarker.label('12', side: MarginSide.end, anchor: MarginAnchor.page) +const MarginMarker.icon(MarginMarkerIcon.bookmark) // side defaults to MarginSide.start, anchor to MarginAnchor.text +``` + +The fields are described in the [API reference](../api-reference/decorations.md#marginmarker). + +`tint` colours the marker's label or icon. Without a tint the marker uses the publication's text colour, so it follows the reader theme. Labels are drawn slightly muted. `isActive` is ignored. + +## Anchoring + +`anchor` decides where the marker sits inside the margin: + +- `MarginAnchor.page` puts the marker near the page edge, or the column edge in two-column layouts. On a wide screen this can be far from the text, which suits printed page numbers. +- `MarginAnchor.text` (default) keeps the marker a small gap (half the body font size) from the text column, however wide the margin is. Use it for markers that belong to a passage, such as bookmarks. + +A text-anchored marker follows font size, page margins, scroll mode and publisher CSS. When the margin is narrower than the marker, it overflows toward the text rather than off the page; [`makeSpaceForMarginDecoration`](#margin-width) prevents that. It lines up with the body's text column, so paragraphs that the publisher indents further keep their extra indent. + +A `marginMarker` decoration without a label or icon is skipped and logged. In debug builds, `applyDecorations` asserts that the marker is present. + +## Recipe: page numbers + +Print-equivalent EPUBs carry a `pageList` navigation document. Map each entry to a locator and apply one marker per entry: + +```dart +Future showPageNumbers(Publication publication) { + final decorations = []; + for (final (index, link) in publication.pageList.indexed) { + final title = link.title; + final locator = publication.locatorFromLink(link); + if (title == null || locator == null) continue; + decorations.add( + ReaderDecoration( + id: 'page_$index', + locator: locator, + style: ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.label(title, side: MarginSide.end, anchor: MarginAnchor.page), + ), + ), + ); + } + return FlutterReadium().applyDecorations('page-list', decorations); +} + +Future hidePageNumbers() => FlutterReadium().applyDecorations('page-list', []); +``` + +Use `pageList`, not `pageListOrGenerated`: generated entries are PDF links. The example app has this behind a toggle in the player app bar. + +## Recipe: bookmarked highlights + +Apply a second group with one icon marker per highlight, on the same locator as the highlight: + +```dart +await reader.applyDecorations('highlights', [ + for (final h in highlights) + ReaderDecoration( + id: h.id, + locator: h.locator, + style: ReaderDecorationStyle(style: DecorationStyle.highlight, tint: h.color), + ), +]); + +await reader.applyDecorations('highlight-markers', [ + for (final h in highlights) + ReaderDecoration( + id: '${h.id}_marker', + locator: h.locator, + style: const ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + tint: Color(0xFF2E7D32), + marker: MarginMarker.icon(MarginMarkerIcon.bookmark), + ), + ), +]); +``` + +Re-apply both groups together whenever the highlights change, so markers never outlive their highlight. + +## Taps + +A marker only reacts to taps on the marker itself, not on the row of text beside it, so taps on the highlighted text still reach the highlight. A tap on the marker reports a normal `onDecorationInteraction` event with the marker's group. Ignore groups you do not handle: + +```dart +onDecorationInteraction: (event) { + if (event.group != 'highlights') return; + // open the highlight sheet +}, +``` + +Pair a marker with a text decoration if tapping the location should do something. Markers are additive; the plugin has no option to suppress marker taps. + +## Margin width + +Markers are sized with the font, but Readium's page margin is a fixed number of pixels (scaled by `pageMargins`). At large font sizes, or with small `pageMargins`, a marker can therefore overlap the text. You cannot fix this with `pageMargins` alone, because the publication's base font size is not exposed. + +Set `makeSpaceForMarginDecoration` to let the plugin size the margin instead: + +```dart +await reader.setEPUBPreferences(prefs.copyWith(makeSpaceForMarginDecoration: true)); +``` + +The side margins then grow with the font size, enough for an icon or a page number of up to three digits with either [anchor](#anchoring). Longer labels can still reach the text. They are never narrower than `pageMargins` would make them. Turning it on shortens the lines, so the text re-paginates like any other layout change. It also applies in scroll mode, and it is ignored for fixed-layout publications. + +The margin is reserved on both sides, whether or not any marker is showing. Leave it off if you do not show margin markers. + +## Layout notes + +- **Two columns.** The `end` margin of the left column and the `start` margin of the right column are the same gap, so markers on both sides can overlap there. +- **Vertical writing modes** are not supported. +- **Fixed layout on iOS.** Decorations are duplicated on both pages of a two-page spread until swift-toolkit 4.0. +- **Volume.** A long book can have hundreds of page-list entries. Apply them in one `applyDecorations` call rather than one call per entry. + +See also the [decorations API reference](../api-reference/decorations.md). diff --git a/docs/plans/README.md b/docs/plans/README.md index 173c2310f..4f1124f53 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -28,6 +28,7 @@ This directory holds implementation plans, parity audits, and retained reference - **[todo/web-ts-refactor.md](todo/web-ts-refactor.md)** — structural refactor of the web TypeScript. The `web/src/` rename landed; collapsing `ReadiumReader.ts` into a thin facade has not. *(Maintainability / L)* +- **[todo/margin-marker-custom-icons.md](todo/margin-marker-custom-icons.md)** — let apps pass their own single-path SVG icon to `marginMarker`; parked until a client asks. *(Feature / S)* - **[todo/highlight-modes.md](todo/highlight-modes.md)** — `highlight`, `underline` and `spotlight` decoration styles exist; the `ruler` style does not. *(Feature / M)* @@ -47,6 +48,7 @@ This directory holds implementation plans, parity audits, and retained reference - **[native-media-overlay-toc-context.md](native-media-overlay-toc-context.md)** — native ToC ownership, resource boundaries and anchored seeking, following [ADR 0001](../adr/0001-media-overlay-toc-ownership.md). - **[web-decorations.md](web-decorations.md)** — web decoration rendering and interaction. +- **[margin-marker-decorations.md](margin-marker-decorations.md)** — built-in `marginMarker` decoration style (label or icon in the page margin). - **[web-goto-locator-precision.md](web-goto-locator-precision.md)** — full-locator web navigation. - **[web-error-event.md](web-error-event.md)** — web error event stream. - **[web-comic-support-plan.md](web-comic-support-plan.md)** — comic helper injection and web panel sync. diff --git a/docs/plans/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md new file mode 100644 index 000000000..f021ac2f1 --- /dev/null +++ b/docs/plans/margin-marker-decorations.md @@ -0,0 +1,156 @@ +# Margin Marker Decorations + +> **✅ Implemented.** The `marginMarker` style landed on iOS, Android and web, with both recipes in the example app. Usage: [guides/margin-markers.md](../guides/margin-markers.md). + +**Type:** Feature +**Platforms affected:** iOS, Android, Web +**Estimated effort:** M + +## Context + +Two client needs come down to the same thing, a small marker in the page margin, lined up with a text location: + +- **Page numbers.** Print-equivalent EPUBs carry a `pageList` nav (see the [DAISY KB page on page lists](http://kb.daisy.org/publishing/docs/navigation/pagelist.html)). Readers want the printed page numbers shown in the margin so they can cite or follow along with a paper copy. +- **Bookmarked highlights.** A client mock-up shows a highlighted passage with a bookmark icon in the margin next to its first line. + +Both upstream toolkits do page numbers in their test apps with a custom decoration style backed by an `HTMLDecorationTemplate` (`layout: bounds`, `width: page`, and a small element floated into the page margin): + +- swift-toolkit: `TestApp/Sources/Reader/Common/VisualReaderViewController.swift`, section "Page list decorations". +- kotlin-toolkit: `test-app/src/main/java/org/readium/r2/testapp/reader/EpubReaderFragment.kt` (`DecorationStylePageNumber`, `pageNumberTemplate()`). +- kotlin-toolkit `demos/navigator/.../decorations/CustomDecorationStyles.kt` shows `data-activable="1"`, which limits a template's tap area to the marked child element. + +As of swift-toolkit 3.11.1 / 4.0.0-alpha.3 and kotlin-toolkit 3.4.0 this is still the recommended approach; neither toolkit has a first-class margin-marker feature. ts-toolkit's Decorator also accepts `HTMLDecorationTemplate` styles (`type: "template"`). Its sanitiser allows SVG "for icon-style decorations (e.g. sidemarks)". The versions already pinned in `flutter_readium/package.json` (`@readium/navigator` 2.15.0, injectables 2.10.1) include all of this. + +## Why a built-in style, not docs-only recipes + +Client apps cannot add decoration templates themselves. Templates are registered in native code when the navigator is created, and the Dart API has no hook for them and no way to run JavaScript in the webview. A recipe would have to tell clients to patch the plugin's Swift, Kotlin and TypeScript. + +The plugin therefore ships **one generic margin-marker style** that shows either a text label or a built-in icon. The docs then give **recipes** that use it: page numbers and bookmarked highlights. If clients later need markers this style can't express, a Dart-side template API can be added on top of the same native code. + +## Current state + +- **Dart** (`flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart`): `DecorationStyle` is `highlight | underline | spotlight`, and the hand-written `DecorationStyle.fromString` falls back to `highlight` for unknown values. `ReaderDecorationStyle` has `style`, optional `tint` and `isActive`. On the wire, `style` is sent as `style.name`. +- **iOS**: the template map is built in `reader/EPUBReaderView.swift` (around line 171, `decorationTemplates[Decoration.Style.Id("spotlight")] = …`). `spotlightDecorationTemplate()` and `escapeHtmlAttr` are in `reader/EPUBReaderView+Decorations.swift`; the spotlight template force-casts its config (`as!`). In `utils/ReadiumExtensions.swift`, `Decoration.Style.init(withStyle:tintColor:isActive:)` turns any style string into a `Style.Id`, but always with a `HighlightConfig`, which has nowhere to put marker data. +- **Android**: `decorationTemplates` is set in `fragments/EpubReaderFragment.kt` (around line 832, `templates[SpotlightStyle::class] = …`). `SpotlightStyle.kt` is the model for a custom `@Parcelize` style. `decorationStyleFromMap` in `ReadiumExtensions.kt` takes a `Map` and is shared by two paths: `applyDecorations` (`ReadiumReaderWidget.kt:535`) goes through `decorationFromJson`, which holds an `org.json.JSONObject` and copies only `style`/`tint`/`isActive` into a new map; the TTS `setDecorationStyle` path passes method-channel Maps directly. `decorationFromJson` also calls `styleJson.getString("tint")`, which **throws when `tint` is absent**, even though `tint` has been optional in the Dart model since the spotlight change. +- **Web** (`web/src/decorations/DecorationController.ts`): `applyDecorations` maps each raw style to a built-in `Highlight`/`Underline` style, and routes spotlight into a subgroup. +- **Example app**: `pageList.page.dart` lists `pageListOrGenerated` for navigation. User highlights are created through the `highlight` selection action and rendered as a decoration group. The `example.*` debug extensions (`docs/agent-testing.md`) can create and inspect them. + +## API + +```dart +enum DecorationStyle { highlight, underline, spotlight, marginMarker; … } + +enum MarginMarkerIcon { bookmark } +enum MarginSide { start, end } + +class MarginMarker implements JSONable { + const MarginMarker.label(String this.label, {this.side = MarginSide.start}) : icon = null; + const MarginMarker.icon(MarginMarkerIcon this.icon, {this.side = MarginSide.start}) : label = null; + final String? label; + final MarginMarkerIcon? icon; + final MarginSide side; + // toJson: {'label'?: …, 'icon'?: icon.name, 'side': side.name} +} + +class ReaderDecorationStyle { + const ReaderDecorationStyle({required this.style, this.tint, this.isActive = false, this.marker}); + /// Required when [style] is [DecorationStyle.marginMarker]; ignored otherwise. + final MarginMarker? marker; + // toJson adds: if (marker != null) 'marker': marker!.toJson() +} +``` + +Design decisions: + +1. **Wire value `"marginMarker"`.** Dart sends `style.name`, so every platform matches on `"marginMarker"`. +2. **Marker data is one nested `marker` object**, not separate `label`/`icon`/`side` fields on `ReaderDecorationStyle`. The other styles keep a clean shape, and the two named constructors make "label xor icon" impossible to get wrong. This is non-breaking: the field is optional, like `tint` and `isActive`. As a plugin-owned flat structure it travels as a map, per `docs/architecture.md#bridge-serialization`. +3. **Icons are a closed enum** rendered as built-in inline SVG (`fill="currentColor"`). Dart never supplies markup. Web sanitises template HTML, but native doesn't, so accepting app markup would open an injection path. Add icons to the enum when a client needs one. +4. **`tint` colours the marker** (label text and icon fill through `color`). Without a tint, `color` is omitted and the marker uses the text colour. `isActive` is ignored. +5. **`side` is logical.** `start` is the left margin in LTR and the right margin in RTL; `end` is the opposite. Declare `float: left|right` first and `float: inline-start|inline-end` second, so webviews without logical float values keep the physical one. The recipes put page numbers at `end` and bookmarks at `start`, as in the mock-up, so both fit on one line in single-column layouts. In two-column layouts the `end` margin of the left page and the `start` margin of the right page are the same gap, so markers there can overlap; document this rather than compensating for it. +6. **No special tap handling.** The marker span carries `data-activable="1"`, which limits the template's tap area to the span in the margin on all three platforms (swift and kotlin `decorator.js`, and ts-toolkit's `Decorator.handleActivation`). Without it the tap area would be the page-width row over the line's text, and kotlin-toolkit hit-tests every group and takes the first match, so the marker could steal taps meant for the highlight. With it, text taps reach the highlight. A tap on the marker itself reports a normal `onDecorationInteraction` for the marker's group; apps ignore groups they don't handle. Markers live in the app's own groups (`page-list`, `highlight-markers`), never in a plugin subgroup. +7. **Styles are inline in the template element**, not in `FlutterReadiumTools.scss`. ts-toolkit renders decorations inside a shadow root, where document stylesheets don't apply, and on native, Readium CSS theme rules (`:root[style*="--USER__backgroundColor"] *` with `background-color: transparent !important`, and `color: inherit !important` under a text colour) beat any class rule. Inline `!important` declarations win on all three platforms (see `docs/troubleshooting.md#decorations-render-invisibly-fills-must-be-important`). +8. **Template element** (identical markup on all platforms): + ```html +
{escaped label | built-in SVG}
+ ``` + Inline styles on the span, each with `!important`: the two `float` declarations from decision 5, `margin: 0 max(4px, 1.5%)` (1.5% of the page width keeps markers off the screen edge on tablets without pushing them into the text on narrow phone margins), `font-size: 0.75em`, `line-height: 1.4`, `opacity: 0.8` for labels only, and `color: {tint}` when a tint is set. There is no border or background: a box made icons look like checkboxes, and its padding pushed markers into the text on narrow phone margins. Labels are muted like printed margin page numbers; icons keep the full colour. The SVG carries `width="1.3em" height="1.3em"`, so it is about one body em. Use `layout: bounds` and `width: page`, so the row's top lines up with the first line of the range and spans the page, and the span floats into the margin. +9. **A `marginMarker` without a `marker` is skipped and logged on every platform**, never rendered empty and never a crash. Dart also asserts in debug in `applyDecorations`, but release builds and `setDecorationStyle` (TTS) reach native unchecked. +10. **The page-number mapping lives in the example app only**, as in the upstream test apps (`pageList` → `locatorFromLink` → `ReaderDecoration`). Use `pageList`, not `pageListOrGenerated`: the generated entries are PDF links, and PDF navigators don't support decorations. If it proves useful for a client, promote it to a `Publication` extension later. +11. **`anchor` chooses between the page edge and the text column, per marker.** `MarginAnchor.page` is the float template above. `MarginAnchor.text` (default) makes the span a child of a flex cell as wide as the margin, with the span pushed against the cell's text side: + ```html +
…
+ ``` + - **Cell:** `display: flex`, `flex-direction: row` (`row-reverse` on the `end` side), `box-sizing: border-box`, `width: var(--flutter-readium-text-inset-start|end, 0px)`, and `padding-inline: 4px 0.5em` (`0.5em 4px` on the `end` side). The `end` cell also gets `margin-inline-start: auto`. + - **Span:** `margin-inline-start|end: auto` and `flex: none`, plus decision 8's styles without the float and margin. + - **Overflow:** when the margin is too narrow, the auto margin collapses and the span overflows toward the text, never off the page. + - **Inset variables:** `flutterReadiumTools.js` sets them on the body. It measures the body's used inline margin, border and padding, and swaps start and end in RTL. It re-measures on body resize, on changes to `` (where Readium writes user settings) and on window resize. + - **Why measure:** a single measurement follows Readium CSS on native and web, publisher CSS, and any injected body padding. A `calc()` copy of Readium's body rules fails on web in scroll mode, where Readium CSS 2 drops the page gutter. No toolkit offers a text-column decoration width. + - **Per marker, not a preference:** apps can then keep page numbers at the edge and bookmarks by the text. + - **Text is the default:** on wide screens a page-anchored marker drifts far from its passage, while on narrow margins the two anchors look the same. Page numbers opt into `page`. + +## Implementation steps + +### 1. Dart + +`reader_decoration.dart`: add `marginMarker` (including a case in `DecorationStyle.fromString`, which otherwise maps it back to `highlight`), `MarginMarker`, `MarginMarkerIcon` and `MarginSide`, and add `marker` to `ReaderDecorationStyle` (constructor, `toJson`, `fromJson`, `copyWith` with the shared `unset` sentinel). In `applyDecorations`, assert in debug that `marginMarker` decorations have a `marker`. Export the new types. Add a `toJson`/`fromJson` round-trip test for a marker decoration. + +### 2. iOS + +- `EPUBReaderView+Decorations.swift`: + - Add `Decoration.Style.Id.marginMarker = "marginMarker"`. + - Add `struct MarginMarkerConfig: Hashable, Sendable { label: String?; icon: String?; side: String; tint: UIColor? }`. + - Add `static func marginMarkerDecorationTemplate()`, which builds the element from the config, escapes the label with `escapeHtmlAttr`, and maps the icon name to the built-in SVG. Read the config with `as?` and return an empty element on a mismatch; never copy the spotlight template's `as!`. +- `ReadiumExtensions.swift`: in `Decoration.Style.init(fromMap:)`, when `styleStr == "marginMarker"`, read `map["marker"]` and build `Decoration.Style(id: .marginMarker, config: MarginMarkerConfig(…))`. If `marker` is missing or has neither label nor icon, log and return `nil` so the decoration is skipped. +- `EPUBReaderView.swift`: register the template next to spotlight. + +### 3. Android + +- New `MarginMarkerStyle.kt`, modelled on `SpotlightStyle.kt`: `@Parcelize data class MarginMarkerStyle(val label: String?, val icon: String?, val side: String, @ColorInt override val tint: Int) : Decoration.Style, Decoration.Style.Tinted`. `@Parcelize` is required because `Decoration.Style` is `Parcelable`. +- `ReadiumExtensions.kt`: + - `decorationFromJson`: read `tint` with `optString`/`isNull` (this fixes the existing crash), and add `"marker"` to the map it builds, converted from `JSONObject` to `Map` (`m.keys().asSequence().associateWith { m.get(it) }`; Android's org.json has no `toMap()`). `decorationStyleFromMap` then sees the same Map shape on both the `applyDecorations` and the TTS path. + - `decorationStyleFromMap`: add a `"marginMarker"` branch. If `marker` is missing or has neither label nor icon, log and return `null` so the decoration is skipped. +- `EpubReaderFragment.kt`: add `marginMarkerDecorationTemplate()` and register it with `templates[MarginMarkerStyle::class] = …`. Move `escAttr()` out of the spotlight template so both templates can use it. +- Run the Android gates in `flutter_readium/android/AGENTS.md`. + +### 4. Web + +- `DecorationController.ts`: type the raw style with optional `tint` and `marker`. For `marginMarker` decorations, push `{ type: DecorationStyleType.Template, layout: DecorationLayout.Bounds, width: DecorationWidth.Page, element: () => html }` in the decoration's own group, using the same markup and SVG as native. Skip and log a `marginMarker` without a `marker`. +- Put the marker payload and tint in the decoration's `extras`. ts-toolkit's `stylesEqual` ignores a Template's `element`, so without this a changed label, icon, side or tint under the same decoration id is never re-rendered; `decorationsEqual` does compare `extras`. +- Check against the pinned `@readium/navigator` 2.15.0 typings that `element` is a function at the navigator level (it is a string in injectables) and that `extras` is available. +- Add cases to `web/src/__tests__/DecorationController.test.ts`, including a re-apply with a changed tint. Run the web gates in `flutter_readium/web/AGENTS.md`, including `bin/update_web_example`. + +### 5. Example app (the two recipes) + +- **Page numbers:** in the reader page, add a "Page numbers in margin" toggle with `ValueKey('page_numbers_toggle')`, shown only when `pub.pageList.isNotEmpty`. When on, apply group `page-list` with `MarginMarker.label(link.title!, side: MarginSide.end)` per entry, skipping entries with a null title or locator. When off, apply an empty list. +- **Bookmarked highlights:** wherever the example applies its highlights group, also apply a `highlight-markers` group with one `MarginMarker.icon(MarginMarkerIcon.bookmark)` per highlight, on the same locator, tinted the highlight's colour (or a fixed green, as in the mock-up). Taps on the text keep going to the highlight decoration itself. + +### 6. Docs and changelog + +- New guide `docs/guides/margin-markers.md`, with both recipes as copy-paste snippets and notes on `side`, `tint`, margin width, two-column overlap, and the fact that markers are meant to be paired with a text decoration for taps. Link it from `docs/api-reference/decorations.md` and `docs/guides/highlights-annotations.md`. +- `docs/api-reference/decorations.md`: add `marginMarker` and `MarginMarker`. The tables there are otherwise stale (`spotlight`, `isActive` and optional `tint` are missing); that is a separate docs fix, not part of this change. +- Changelog fragments per `CONTRIBUTING.md#changelog`: `+margin-marker-decorations.added.md`, and `+android-decoration-without-tint.fixed.md` for the crash. Validate with `bin/changelog check`. The example-app changes get no fragment. +- When done, move this plan to `docs/plans/` with an `> **✅ Implemented**` note and update `docs/plans/README.md`. + +### 7. Validation + +- `bin/format` and `bin/analyze`, plus the iOS, Android and web gates from their `AGENTS.md` files. `bin/check_channel_parity` should be unaffected, because no channel method is added. +- Smoke test on the iOS simulator, an Android device and web (`docs/agent-testing.md`): + - Turn on page numbers and take screenshots in paginated and scroll mode, with a dark custom theme (marker background and tint must survive it), and in an RTL publication if one is available. + - Create a highlight with `example.selectionAction` and confirm the bookmark icon appears next to its first line. Tap the highlighted text on the simulator or device and confirm `onDecorationInteraction` reports the highlight, not the marker. +- Fixtures come from `bin/fetch_test_resources`. Check whether a fixture EPUB has a `pageList`. If none does, add one to `Notalib/readium-test-resources` and to the `trim` list in `bin/build_test_fixtures`. + +## Risks / open questions + +- **Empty page-break anchors.** Page-list targets are often empty elements (``). The upstream test apps use the same anchors, but check that the marker's vertical position matches on all three platforms. +- **Unescaped page-break selectors.** `locatorFromLink` (`publication.dart`) builds `cssSelector: '#'` without CSS escaping. An id that starts with a digit (`12`) makes `querySelector` throw before the fragment fallback runs, and that page number silently disappears. Fix `locatorFromLink` in its own PR if a real publication hits this. +- **Margin width.** Markers sit in the page margin. Icons need a little more room than page numbers, and with small `pageMargins` they may overlap the text. Document this rather than compensating for it. +- **Fixed-layout two-page spreads (iOS).** Decorations are duplicated on both pages until swift-toolkit 4.0 (readium/swift-toolkit#632). This is cosmetic, and margin markers are rare in fixed layout. +- **Volume.** A long book has hundreds of page-list entries in one `applyDecorations` call. The natives render only loaded resources, but check that opening a chapter doesn't get noticeably slower. +- **Overlap with [highlight-modes.md](highlight-modes.md).** Its open `ruler` style also adds a `DecorationStyle` value and a native template next to spotlight. Whichever lands second rebases onto the other; the two don't conflict in design. + +## Out of scope + +- App-supplied icons, CSS or templates. See [todo/margin-marker-custom-icons.md](todo/margin-marker-custom-icons.md). +- Suppressing marker taps. Markers are additive; an app that doesn't want marker events ignores their group. +- Vertical writing modes. +- PDF (PDF navigators don't support decorations, and PDFs show their own page numbers). diff --git a/docs/plans/todo/margin-marker-custom-icons.md b/docs/plans/todo/margin-marker-custom-icons.md new file mode 100644 index 000000000..76e348b93 --- /dev/null +++ b/docs/plans/todo/margin-marker-custom-icons.md @@ -0,0 +1,48 @@ +# Custom Margin Marker Icons + +**Type:** Feature +**Platforms affected:** iOS, Android, Web +**Estimated effort:** S +**Status:** Parked until a client asks for an icon the built-in set doesn't cover. + +## Context + +`DecorationStyle.marginMarker` ([margin-marker-decorations.md](../margin-marker-decorations.md), guide: [margin-markers.md](../../guides/margin-markers.md)) shows a text label or a built-in icon in the page margin. The icons are a closed enum, `MarginMarkerIcon { bookmark, note, star }`. Dart sends the icon's name, and each platform looks it up in its own name → SVG path map: + +- iOS: `MarginMarkerConfig.iconPaths` in `reader/EPUBReaderView+Decorations.swift`. +- Android: `MarginMarkerStyle.ICON_PATHS` in `MarginMarkerStyle.kt`. +- Web: `MARGIN_MARKER_ICON_PATHS` in `web/src/decorations/DecorationController.ts`. + +Each template wraps the path in the same element: ``. Today a new icon needs a plugin release. + +## Proposal: app-supplied SVG path + +Let apps pass their own single-path icon as SVG path data, not as markup: + +```dart +const MarginMarker.svgPath('M12 2l2.9 6.9 …z', side: MarginSide.start) +``` + +- **Wire format:** `marker: { "svgPath": "", "side": … }`, next to `label` and `icon`. Exactly one of the three is set; the named constructors make that impossible to get wrong in Dart. +- **Rendering:** the existing icon branch of each template, with the app's path in place of the built-in one. The icon therefore follows `tint` and dark themes, and taps, diffing (`extras` on web) and layout behave exactly like the built-in icons. +- **Validation, on every platform at parse time:** accept only SVG path syntax, that is `^[MmLlHhVvCcSsQqTtAaZz0-9eE.,+\-\s]+$`, with a length cap (say 4 KB). Reject anything else like a marker with no content: skip the decoration and log. Escape the value into the attribute anyway. +- **Constraints to document:** a 24×24 viewBox, a single colour (`currentColor`), and `fill-rule="evenodd"` for holes. Multi-colour icons are out of scope; see option C below. +- **Tests:** Dart round-trip; on each platform, a valid path renders and an invalid one (for example containing `"` or `<`) is skipped. + +The regex is what makes this safe. Path data can't contain markup, so the app can't inject elements or scripts into the publication webview, even when the path comes from server data. + +## Alternatives considered + +| Option | Why not (yet) | +|---|---| +| **C. Image bytes**
(data URI in ``) | Can't be tinted, so it clashes with dark themes.
The base64 is repeated in every marker's HTML.
Unverified whether ts-toolkit's sanitiser keeps `data:` image sources. | +| **D. App CSS**
(style string or map) | Readium CSS theme rules beat normal declarations, so apps would need `!important` everywhere.
Web renders in a shadow root.
If needed, prefer an allowlisted property map over a raw string. | +| **E. Dart-side template API**
(raw HTML) | Readium inserts template HTML as markup, so an attribute like `onerror` runs script in the publication webview, which has native bridges on Android.
Native renders the HTML as-is but web sanitises it, so results differ per platform.
It is the most flexible option and the biggest API to keep stable; revisit only for a need B can't meet. | + +`B` (this proposal) covers "our own icon" without those costs. + +## Done when + +- `MarginMarker.svgPath` exists in Dart, with docs in `docs/api-reference/decorations.md` and a short section in the guide. +- iOS, Android and web validate, render and test it as above. +- A changelog fragment (`.added`) in both packages. diff --git a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/FlutterEpubPreferences.kt b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/FlutterEpubPreferences.kt index f4ce1a1af..414da9b8b 100644 --- a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/FlutterEpubPreferences.kt +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/FlutterEpubPreferences.kt @@ -18,6 +18,9 @@ private const val TAG = "FlutterEpubPreferences" private const val TOP_MARGIN_CSS_VARIABLE = "--FLUTTER_READIUM-first-element-top-margin" private const val BLACK_AND_WHITE_COMIC_MODE_CSS_VARIABLE = "--FLUTTER_READIUM-black-white-comic-mode" +// The flag only switches on the padding rule in FlutterReadiumTools.scss. +private const val MARGIN_DECORATION_SPACE_CSS_VARIABLE = "--FLUTTER_READIUM-margin-decoration-space" + @OptIn(ExperimentalReadiumApi::class) @Serializable data class FlutterEpubPreferences( @@ -50,6 +53,7 @@ data class FlutterEpubPreferences( val syncPolicy: String? = null, val firstElementTopMargin: Int? = null, val preventMOColumnBreaks: Boolean? = true, + val makeSpaceForMarginDecoration: Boolean? = false, ) : Configurable.Preferences { override fun plus(other: FlutterEpubPreferences): FlutterEpubPreferences = FlutterEpubPreferences( @@ -82,6 +86,7 @@ data class FlutterEpubPreferences( syncPolicy = other.syncPolicy ?: syncPolicy, firstElementTopMargin = other.firstElementTopMargin ?: firstElementTopMargin, preventMOColumnBreaks = other.preventMOColumnBreaks ?: preventMOColumnBreaks, + makeSpaceForMarginDecoration = other.makeSpaceForMarginDecoration ?: makeSpaceForMarginDecoration, ) fun toEpubPreferences(): EpubPreferences = @@ -117,6 +122,7 @@ data class FlutterEpubPreferences( val map = mutableMapOf() map[TOP_MARGIN_CSS_VARIABLE] = firstElementTopMargin?.let { "${it}px" } map[BLACK_AND_WHITE_COMIC_MODE_CSS_VARIABLE] = if (blackAndWhiteComicMode == true) "1" else null + map[MARGIN_DECORATION_SPACE_CSS_VARIABLE] = if (makeSpaceForMarginDecoration == true) "1" else null return map } diff --git a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt new file mode 100644 index 000000000..53734ab1f --- /dev/null +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt @@ -0,0 +1,31 @@ +package dk.nota.flutterreadium + +import androidx.annotation.ColorInt +import kotlinx.parcelize.Parcelize +import org.readium.r2.navigator.Decoration + +/** + * Margin marker: a text [label] or built-in [icon] floated into the page margin, level with the + * first line of the range. [side] is "start" or "end" (logical, so it flips in RTL). + * [anchor] is "page" (near the page edge) or "text" (a small gap from the text column). + * A transparent [tint] means no tint was set. + */ +@Parcelize +data class MarginMarkerStyle( + val label: String?, + val icon: String?, + val side: String, + val anchor: String, + @ColorInt override val tint: Int, +) : Decoration.Style, + Decoration.Style.Tinted { + companion object { + /** SVG path data (24x24 viewBox) by `MarginMarkerIcon` name. Keep in sync with Dart, iOS and web. */ + val ICON_PATHS = + mapOf( + "bookmark" to "M6 2h12a1 1 0 0 1 1 1v19l-7-4-7 4V3a1 1 0 0 1 1-1z", + "note" to "M4 3h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H9l-5 4v-4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM7 7v2h10V7zm0 4v2h7v-2z", + "star" to "M12 2l2.9 6.9 7.1.6-5.4 4.7 1.6 7-6.2-3.8-6.2 3.8 1.6-7L2 9.5l7.1-.6z", + ) + } +} diff --git a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/ReadiumExtensions.kt b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/ReadiumExtensions.kt index 2dabfe617..eb35a735e 100644 --- a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/ReadiumExtensions.kt +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/ReadiumExtensions.kt @@ -106,6 +106,11 @@ fun decorationFromJson(jsonString: String): Decoration? = // `tint` is optional; getString would throw when it is absent. "tint" to if (styleJson.isNull("tint")) null else styleJson.getString("tint"), "isActive" to styleJson.optBoolean("isActive", false), + // decorationStyleFromMap expects a Map, as on the TTS path. + "marker" to + styleJson.optJSONObject("marker")?.let { m -> + m.keys().asSequence().associateWith { m.get(it) } + }, ), ) ?: throw Exception("Failed to deserialize decoration style") Decoration(id, locator, style) @@ -147,9 +152,34 @@ fun decorationStyleFromMap(decoMap: Map<*, *>?): Decoration.Style? { val tint = tintColorStr?.let { readiumColorFromCSS(it).int } ?: Color.TRANSPARENT val style = when (styleStr) { - "underline" -> Decoration.Style.Underline(tint, isActive) - "spotlight" -> SpotlightStyle(tint) - else -> Decoration.Style.Highlight(tint, isActive) // "highlight" + unknown + "underline" -> { + Decoration.Style.Underline(tint, isActive) + } + + "spotlight" -> { + SpotlightStyle(tint) + } + + "marginMarker" -> { + val marker = decoMap["marker"] as? Map<*, *> + val label = (marker?.get("label") as? String)?.takeIf { it.isNotEmpty() } + val icon = (marker?.get("icon") as? String)?.takeIf { it in MarginMarkerStyle.ICON_PATHS } + if (label == null && icon == null) { + // Without content the marker would render empty, so skip the decoration. + PluginLog.e( + "ReadiumExtensions", + "::decorationStyleFromMap. marginMarker needs a marker with a label or a known icon", + ) + return null + } + val side = if (marker?.get("side") == "end") "end" else "start" + val anchor = if (marker?.get("anchor") == "page") "page" else "text" + MarginMarkerStyle(label, icon, side, anchor, tint) + } + + else -> { + Decoration.Style.Highlight(tint, isActive) + } // "highlight" + unknown } return style } catch (ex: Exception) { @@ -847,12 +877,12 @@ fun Locator.addPageNumber( ), ) -// Resolves preferences against the publication's layout. The first-element top margin -// is a reflowable-text affordance, so it's dropped for every non-reflowable publication -// (fixed/scrolled layouts and image publications, which report no layout) where it would -// otherwise shift the full-page content down. +// Resolves preferences against the publication's layout. The first-element top margin and +// the margin-decoration space are reflowable-text affordances, so they're dropped for every +// non-reflowable publication (fixed/scrolled layouts and image publications, which report no +// layout) where they would otherwise shift the full-page content. fun FlutterEpubPreferences.effectiveForLayout(layout: Layout?): FlutterEpubPreferences = - if (layout?.isReflowable == true) this else copy(firstElementTopMargin = null) + if (layout?.isReflowable == true) this else copy(firstElementTopMargin = null, makeSpaceForMarginDecoration = null) val Layout.isFixed: Boolean get() = this == Layout.FIXED diff --git a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/fragments/EpubReaderFragment.kt b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/fragments/EpubReaderFragment.kt index dafe96717..b22dd3d7a 100644 --- a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/fragments/EpubReaderFragment.kt +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/fragments/EpubReaderFragment.kt @@ -10,6 +10,7 @@ import androidx.lifecycle.lifecycleScope import dk.nota.flutterreadium.EpubImageTapBridge import dk.nota.flutterreadium.EpubSameDocumentLinkBridge import dk.nota.flutterreadium.FlutterEpubPreferences +import dk.nota.flutterreadium.MarginMarkerStyle import dk.nota.flutterreadium.NarrationSyncInterface import dk.nota.flutterreadium.PluginLog import dk.nota.flutterreadium.R @@ -81,7 +82,7 @@ class EpubReaderFragment : * Called when an external link is activated. */ fun onExternalLinkActivated(url: AbsoluteUrl) - + /** * Called when an internal link is about to be followed. `from` is the position before the jump. */ @@ -830,6 +831,7 @@ class EpubReaderFragment : experimentalPositioning = true, ).also { templates -> templates[SpotlightStyle::class] = spotlightDecorationTemplate() + templates[MarginMarkerStyle::class] = marginMarkerDecorationTemplate() }, // Only register the callback if custom selectionActions are added. selectionActionModeCallback = @@ -996,6 +998,12 @@ class EpubReaderFragment : companion object { private const val NAVIGATOR_FRAGMENT_TAG = "READIUM_EPUB_READER_FRAGMENT" + private fun String.escAttr() = + replace("&", "&") + .replace("\"", """) + .replace("<", "<") + .replace(">", ">") + /** * Spotlight: semi-transparent tinted box over the active range, one per text line. * @@ -1037,17 +1045,79 @@ class EpubReaderFragment : "rgba($r,$g,$b,0.5)" } - fun String.escAttr() = - replace("&", "&") - .replace("\"", """) - .replace("<", "<") - .replace(">", ">") val sel = (decoration.locator.locations.cssSelector ?: "").escAttr() val hl = (decoration.locator.text.highlight ?: "").escAttr() val bef = (decoration.locator.text.before ?: "").escAttr() """
""" }, ) + + /** + * Margin marker floated into the page margin, or placed next to the text for the "text" anchor. + * Keep the markup identical to the iOS and web templates; the design is in + * docs/plans/margin-marker-decorations.md. + */ + private fun marginMarkerDecorationTemplate(): HtmlDecorationTemplate = + HtmlDecorationTemplate( + layout = HtmlDecorationTemplate.Layout.BOUNDS, + width = HtmlDecorationTemplate.Width.PAGE, + element = { decoration -> + val style = decoration.style as? MarginMarkerStyle + val content = + when { + style == null -> { + null + } + + style.label != null -> { + style.label.escAttr() + } + + style.icon in MarginMarkerStyle.ICON_PATHS -> { + """""" + } + + else -> { + null + } + } + if (style == null || content == null) { + "
" + } else { + val end = style.side == "end" + val color = + if (android.graphics.Color.alpha(style.tint) == 0) { + "" + } else { + val r = android.graphics.Color.red(style.tint) + val g = android.graphics.Color.green(style.tint) + val b = android.graphics.Color.blue(style.tint) + " color: rgba($r, $g, $b, ${android.graphics.Color.alpha(style.tint) / 255.0}) !important;" + } + // Labels are muted like printed margin page numbers; icons keep the full colour. + val opacity = if (style.label != null) " opacity: 0.8 !important;" else "" + val css = " font-size: 0.75em !important; line-height: 1.4 !important;$opacity$color" + if (style.anchor == "text") { + // The cell is as wide as the margin, which flutterReadiumTools.js measures. The marker is pushed + // against the cell's text side; in a too-narrow margin it overflows toward the text, never off the page. + val cell = + "display: flex !important; flex-direction: ${if (end) "row-reverse" else "row"} !important;" + + " box-sizing: border-box !important;" + + " width: var(--flutter-readium-text-inset-${if (end) "end" else "start"}, 0px) !important;" + + " padding-inline: ${if (end) "0.5em 4px" else "4px 0.5em"} !important;" + + if (end) " margin-inline-start: auto !important;" else "" + val push = "margin-${if (end) "inline-end" else "inline-start"}: auto !important; flex: none !important;" + """
$content
""" + } else { + val float = + "float: ${if (end) "right" else "left"} !important;" + + " float: ${if (end) "inline-end" else "inline-start"} !important;" + + " margin: 0 max(4px, 1.5%) !important;" + """
$content
""" + } + } + }, + ) } } diff --git a/flutter_readium/android/src/test/kotlin/dk/nota/flutterreadium/FlutterEpubPreferencesTest.kt b/flutter_readium/android/src/test/kotlin/dk/nota/flutterreadium/FlutterEpubPreferencesTest.kt index 884ec9100..107b511b7 100644 --- a/flutter_readium/android/src/test/kotlin/dk/nota/flutterreadium/FlutterEpubPreferencesTest.kt +++ b/flutter_readium/android/src/test/kotlin/dk/nota/flutterreadium/FlutterEpubPreferencesTest.kt @@ -3,6 +3,7 @@ package dk.nota.flutterreadium import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test +import org.readium.r2.shared.publication.Layout @OptIn(org.readium.r2.shared.ExperimentalReadiumApi::class) internal class FlutterEpubPreferencesTest { @@ -26,4 +27,13 @@ internal class FlutterEpubPreferencesTest { val epub = prefs.toEpubPreferences() assertNull(epub.fontSize) } + + @Test + fun `makeSpaceForMarginDecoration sets its CSS flag only for reflowable layouts`() { + val key = "--FLUTTER_READIUM-margin-decoration-space" + val prefs = FlutterEpubPreferences.fromJson("""{"makeSpaceForMarginDecoration":true}""") + assertEquals("1", prefs.effectiveForLayout(Layout.REFLOWABLE).toCustomCssVariables()[key]) + assertNull(prefs.effectiveForLayout(Layout.FIXED).toCustomCssVariables()[key]) + assertNull(FlutterEpubPreferences().toCustomCssVariables()[key]) + } } diff --git a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.scss b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.scss index 90fbfd7b1..1dde649c0 100644 --- a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.scss +++ b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.scss @@ -18,6 +18,25 @@ body > *:first-child { margin-top: var(--FLUTTER_READIUM-first-element-top-margin) !important; } +// EPUBPreferences.makeSpaceForMarginDecoration: side padding wide enough for a margin marker. +// The marker content is at most 1.3em: a 1.3em icon in the 0.75em span (0.975em), or a three-digit +// page label. A page-anchored marker adds a max(4px, 1.5%) margin on each side (1.5vw is at least 1.5% +// of a page); a text-anchored one sits in a cell with 4px padding at the page edge and 0.5em at the +// text. Both cells inherit the body font size, so these em match the body's. Never narrower than +// Readium's own padding. `html:root` gives (0,2,2), which beats Readium CSS's (0,2,1) page-margin +// rule whatever the stylesheet order. Native sets the flag as a root CSS variable; web uses a data +// attribute, because ts-toolkit removes root style properties it did not set. +$margin-decoration-space: max( + calc(var(--RS__pageGutter) * var(--USER__pageMargins, 1)), + calc(2 * max(4px, 1.5vw) + 1.3em), + calc(4px + 0.5em + 1.3em) +); +html:root[style*='--FLUTTER_READIUM-margin-decoration-space'] body, +html:root[data-flutter-readium-margin-decoration-space] body { + padding-left: $margin-decoration-space !important; + padding-right: $margin-decoration-space !important; +} + //TODO: Temporary fix for https://github.com/readium/readium-css/issues/129#issue-1856586505 //remove when resolved * { diff --git a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts index b8f7bf1fa..5faa93bfc 100644 --- a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts +++ b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts @@ -421,6 +421,48 @@ function Setup() { initResponsiveTables(); startSpotlightObserver(document); + startTextInsetObserver(document); + relayoutDecorationsOnResize(); + }); +} + +/** + * Publishes the distance from each page edge to the text column as `--flutter-readium-text-inset-start` + * and `--flutter-readium-text-inset-end` on the body, so text-anchored margin markers can sit next to the + * text. Measuring the used box follows Readium CSS, publisher CSS and injected padding alike. + */ +function startTextInsetObserver(doc: Document): void { + const update = () => { + const body = doc.body; + if (!body) return; + const cs = getComputedStyle(body); + const px = (v: string) => parseFloat(v) || 0; + const left = px(cs.marginLeft) + px(cs.borderLeftWidth) + px(cs.paddingLeft); + const right = px(cs.marginRight) + px(cs.borderRightWidth) + px(cs.paddingRight); + const rtl = cs.direction === 'rtl'; + body.style.setProperty('--flutter-readium-text-inset-start', `${rtl ? right : left}px`); + body.style.setProperty('--flutter-readium-text-inset-end', `${rtl ? left : right}px`); + }; + update(); + // Readium writes user settings to . The variables go on the body, so writing them does + // not retrigger this observer. A wider viewport can move auto margins without resizing the body. + new ResizeObserver(update).observe(doc.body); + new MutationObserver(update).observe(doc.documentElement, { attributes: true, attributeFilter: ['style'] }); + window.addEventListener('resize', update); +} + +/** + * Lays out every decoration group again once the viewport has resized. The toolkit decorator only relays out + * on a body ResizeObserver, which WebKit can fire during rotation while `window.innerWidth` still reports the + * old viewport, so `width: page` decorations keep the old page width. `resize` fires with the new size. + */ +function relayoutDecorationsOnResize(): void { + window.addEventListener('resize', () => { + const readium = window.readium; + if (typeof readium?.getDecorations !== 'function') return; + document.querySelectorAll('body > [id^="r2-decoration-"][data-group]').forEach((container) => { + readium.getDecorations(container.dataset.group!).requestLayout?.(); + }); }); } diff --git a/flutter_readium/changelog.d/+android-decoration-without-tint.fixed.md b/flutter_readium/changelog.d/+android-decoration-without-tint.fixed.md new file mode 100644 index 000000000..bf27509a8 --- /dev/null +++ b/flutter_readium/changelog.d/+android-decoration-without-tint.fixed.md @@ -0,0 +1,3 @@ +**Android: decorations without a `tint` were dropped.** +`applyDecorations` threw while parsing a decoration style with no `tint`, so the decoration never rendered, although `tint` is optional in the Dart model. +The tint is now read as optional. diff --git a/flutter_readium/changelog.d/+ios-apply-decorations-skip-invalid.fixed.md b/flutter_readium/changelog.d/+ios-apply-decorations-skip-invalid.fixed.md new file mode 100644 index 000000000..275e06f54 --- /dev/null +++ b/flutter_readium/changelog.d/+ios-apply-decorations-skip-invalid.fixed.md @@ -0,0 +1,2 @@ +**iOS: one invalid decoration dropped its whole group.** +A decoration that failed to parse made the call fail with a `JSON mapping error`, so none of the group was shown. iOS now skips and logs that decoration and applies the rest, matching Android and web. diff --git a/flutter_readium/changelog.d/+margin-decoration-space.added.md b/flutter_readium/changelog.d/+margin-decoration-space.added.md new file mode 100644 index 000000000..e9ac3f5bc --- /dev/null +++ b/flutter_readium/changelog.d/+margin-decoration-space.added.md @@ -0,0 +1,3 @@ +**Room for margin markers at any font size.** +At large font sizes a margin marker could overlap the text, because the page margin does not grow with the font. +The opt-in `EPUBPreferences.makeSpaceForMarginDecoration` widens the side margins with the font size so markers fit, on iOS, Android and web. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#margin-width). diff --git a/flutter_readium/changelog.d/+margin-marker-decorations.added.md b/flutter_readium/changelog.d/+margin-marker-decorations.added.md new file mode 100644 index 000000000..911313c45 --- /dev/null +++ b/flutter_readium/changelog.d/+margin-marker-decorations.added.md @@ -0,0 +1,3 @@ +**Margin marker decorations.** +`DecorationStyle.marginMarker` shows a text label or a built-in icon (bookmark, note or star) in the margin, level with the first line of a locator, on iOS, Android and web. +By default a marker sits a small gap from the text column; `anchor: MarginAnchor.page` puts it at the page edge instead. Use it for printed page numbers or bookmarked highlights. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md). diff --git a/flutter_readium/example/lib/pages/player.page.dart b/flutter_readium/example/lib/pages/player.page.dart index 93ff5a9e2..6e67490f2 100644 --- a/flutter_readium/example/lib/pages/player.page.dart +++ b/flutter_readium/example/lib/pages/player.page.dart @@ -14,6 +14,9 @@ import '../widgets/index.dart'; const Color _appBarColor = Colors.amber; const Color _playerControlsColor = Color.fromARGB(255, 240, 240, 240); +/// Decoration group with one printed page number in the margin per page-list entry. +const _pageListGroup = 'page-list'; + class PlayerPage extends StatefulWidget { const PlayerPage({super.key}); @@ -25,6 +28,7 @@ class _PlayerPageState extends State with RestorationMixin { final _slideDuration = const Duration(milliseconds: 350); final _shouldShowControls = ValueNotifier(true); StreamSubscription? _errorSub; + bool _showPageNumbers = false; @override void initState() { @@ -103,6 +107,30 @@ class _PlayerPageState extends State with RestorationMixin { ); } + /// Shows the printed page numbers from the page list in the end margin, or clears them. + void _togglePageNumbers(final Publication publication) { + setState(() => _showPageNumbers = !_showPageNumbers); + final decorations = []; + if (_showPageNumbers) { + for (final (index, link) in publication.pageList.indexed) { + final title = link.title; + final locator = publication.locatorFromLink(link); + if (title == null || locator == null) continue; + decorations.add( + ReaderDecoration( + id: 'page_$index', + locator: locator, + style: ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.label(title, side: MarginSide.end, anchor: MarginAnchor.page), + ), + ), + ); + } + } + FlutterReadium().applyDecorations(_pageListGroup, decorations); + } + Future _deferWebGoToAfterRoutePop() async { if (!kIsWeb) { return; @@ -156,7 +184,7 @@ class _PlayerPageState extends State with RestorationMixin { pubState.error != null ? 'Error' : pubState.publication?.metadata.title ?? 'Unknown', ), ), - actions: _buildActionButtons(isAudioBook, isDivina, isPdf), + actions: _buildActionButtons(isAudioBook, isDivina, isPdf, pubState.publication), ), body: Stack( children: [ @@ -216,7 +244,21 @@ class _PlayerPageState extends State with RestorationMixin { }, ); - List _buildActionButtons(final bool isAudioBook, final bool isDivina, final bool isPdf) => [ + List _buildActionButtons( + final bool isAudioBook, + final bool isDivina, + final bool isPdf, + final Publication? publication, + ) => [ + // Margin markers are decorations on text content, so PDF and DiViNa are out; no page list, no toggle. + if (!isAudioBook && !isDivina && !isPdf && publication != null && publication.pageList.isNotEmpty) + IconButton( + key: const ValueKey('page_numbers_toggle'), + icon: const Icon(Icons.format_list_numbered), + isSelected: _showPageNumbers, + onPressed: () => _togglePageNumbers(publication), + tooltip: 'Page numbers in margin', + ), if (!isAudioBook && !isDivina) IconButton( key: const ValueKey('visual_settings_button'), diff --git a/flutter_readium/example/lib/state/highlight.dart b/flutter_readium/example/lib/state/highlight.dart index a2e051858..cbc5878e0 100644 --- a/flutter_readium/example/lib/state/highlight.dart +++ b/flutter_readium/example/lib/state/highlight.dart @@ -5,6 +5,9 @@ import 'package:flutter_readium/flutter_readium.dart'; /// Decoration group that holds all user highlights in the reader. const highlightsGroup = 'user_highlights'; +/// Decoration group with one bookmark marker in the margin next to each highlight. +const highlightMarkersGroup = 'highlight-markers'; + /// A user highlight: the decoration sent to the reader plus the selected text. /// /// The text is kept here because the selection locator's `text.highlight` @@ -20,6 +23,18 @@ class Highlight { Color? get tint => decoration.style.tint; + /// A bookmark icon in the margin, level with the first line of the highlight and next to the text. + /// + /// Untinted, so it takes the text colour and follows the reader theme. + ReaderDecoration get marker => ReaderDecoration( + id: '${id}_marker', + locator: decoration.locator, + style: const ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.icon(MarginMarkerIcon.bookmark), + ), + ); + Highlight withTint(Color tint) => Highlight( decoration: decoration.copyWith(style: decoration.style.copyWith(tint: tint)), text: text, diff --git a/flutter_readium/example/lib/state/publication_bloc.dart b/flutter_readium/example/lib/state/publication_bloc.dart index 88672025e..6456801ec 100644 --- a/flutter_readium/example/lib/state/publication_bloc.dart +++ b/flutter_readium/example/lib/state/publication_bloc.dart @@ -275,6 +275,7 @@ class PublicationBloc extends HydratedBloc { void _emitHighlights(final Emitter emit, final Map highlights) { emit(state.copyWith(highlights: highlights)); instance.applyDecorations(highlightsGroup, [for (final highlight in highlights.values) highlight.decoration]); + instance.applyDecorations(highlightMarkersGroup, [for (final highlight in highlights.values) highlight.marker]); } void _cancelSubscriptions() { diff --git a/flutter_readium/example/lib/state/text_settings_bloc.dart b/flutter_readium/example/lib/state/text_settings_bloc.dart index a839b35b1..259c3e355 100644 --- a/flutter_readium/example/lib/state/text_settings_bloc.dart +++ b/flutter_readium/example/lib/state/text_settings_bloc.dart @@ -52,6 +52,8 @@ class OpenPubSuccess extends TextSettingsEvent {} @immutable class ToggleBlackAndWhiteComicMode extends TextSettingsEvent {} +class ToggleMarginDecorationSpace extends TextSettingsEvent {} + @immutable class ToggleDisableSynchronization extends TextSettingsEvent {} @@ -140,6 +142,7 @@ class TextSettingsState { this.pageMargins, this.paragraphSpacing = 1.0, this.blackAndWhiteComicMode = false, + this.makeSpaceForMarginDecoration = false, this.disableSynchronization = false, this.reduceCrowding = false, this.firstElementTopMargin = 40, @@ -168,6 +171,7 @@ class TextSettingsState { final double? pageMargins; final double? paragraphSpacing; final bool blackAndWhiteComicMode; + final bool makeSpaceForMarginDecoration; final bool disableSynchronization; /// Dyslexia crowding-reduction preset: increases letter/word/line spacing. @@ -201,6 +205,7 @@ class TextSettingsState { final double? pageMargins, final double? paragraphSpacing, final bool? blackAndWhiteComicMode, + final bool? makeSpaceForMarginDecoration, final bool? disableSynchronization, final bool? reduceCrowding, final int? firstElementTopMargin, @@ -229,6 +234,7 @@ class TextSettingsState { pageMargins: pageMargins ?? this.pageMargins, paragraphSpacing: paragraphSpacing ?? this.paragraphSpacing, blackAndWhiteComicMode: blackAndWhiteComicMode ?? this.blackAndWhiteComicMode, + makeSpaceForMarginDecoration: makeSpaceForMarginDecoration ?? this.makeSpaceForMarginDecoration, disableSynchronization: disableSynchronization ?? this.disableSynchronization, reduceCrowding: reduceCrowding ?? this.reduceCrowding, firstElementTopMargin: firstElementTopMargin ?? this.firstElementTopMargin, @@ -267,6 +273,7 @@ class TextSettingsBloc extends Bloc { paragraphSpacing: state.paragraphSpacing, publisherStyles: state.publisherStyles, blackAndWhiteComicMode: state.blackAndWhiteComicMode, + makeSpaceForMarginDecoration: state.makeSpaceForMarginDecoration, disableSynchronization: state.disableSynchronization, firstElementTopMargin: state.firstElementTopMargin, letterSpacing: state.letterSpacing, @@ -296,6 +303,7 @@ class TextSettingsBloc extends Bloc { paragraphSpacing: state.paragraphSpacing, publisherStyles: state.publisherStyles, blackAndWhiteComicMode: state.blackAndWhiteComicMode, + makeSpaceForMarginDecoration: state.makeSpaceForMarginDecoration, disableSynchronization: state.disableSynchronization, firstElementTopMargin: state.firstElementTopMargin, letterSpacing: state.letterSpacing, @@ -362,6 +370,13 @@ class TextSettingsBloc extends Bloc { submitPreferenceUpdate(); }); + on((final event, final emit) { + emit( + state.copyWith(makeSpaceForMarginDecoration: !state.makeSpaceForMarginDecoration), + ); + submitPreferenceUpdate(); + }); + on((final event, final emit) { emit( state.copyWith(disableSynchronization: !state.disableSynchronization), diff --git a/flutter_readium/example/lib/widgets/text_settings.widget.dart b/flutter_readium/example/lib/widgets/text_settings.widget.dart index c2b9217b6..06f1f54e3 100644 --- a/flutter_readium/example/lib/widgets/text_settings.widget.dart +++ b/flutter_readium/example/lib/widgets/text_settings.widget.dart @@ -399,6 +399,17 @@ class _LayoutSection extends StatelessWidget { }, ), ), + ListItemWidget( + label: 'Room for margin markers', + isVerticalAlignment: true, + child: Switch( + key: const ValueKey('margin_decoration_space_switch'), + value: state.makeSpaceForMarginDecoration, + onChanged: (value) { + textSettingsBloc.add(ToggleMarginDecorationSpace()); + }, + ), + ), ListItemWidget( label: 'Disable Synchronization', isVerticalAlignment: true, diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/FlutterReadiumPlugin.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/FlutterReadiumPlugin.swift index dbc60495a..4e2836beb 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/FlutterReadiumPlugin.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/FlutterReadiumPlugin.swift @@ -332,8 +332,8 @@ public class FlutterReadiumPlugin: NSObject, FlutterPlugin, ReadiumShared.Warnin // Explicitly set to nil when the arg is null — do NOT skip the assignment. // An `if let` guard would leave the previous style in place when null is // passed, which prevents the caller from clearing an active decoration. - ttsUtteranceDecorationStyle = (args[0] as? [String: Any]).map { try! Decoration.Style(fromMap: $0) } - ttsRangeDecorationStyle = (args[1] as? [String: Any]).map { try! Decoration.Style(fromMap: $0) } + ttsUtteranceDecorationStyle = (args[0] as? [String: Any]).flatMap(ttsDecorationStyle) + ttsRangeDecorationStyle = (args[1] as? [String: Any]).flatMap(ttsDecorationStyle) Task { @MainActor in self.timebasedNavigator?.decorationsUpdated() } @@ -811,6 +811,16 @@ extension FlutterReadiumPlugin { NowPlayingInfo.shared.clear() } + /// Parses a TTS decoration style; an invalid one is logged and clears the decoration. + func ttsDecorationStyle(_ map: [String: Any]) -> Decoration.Style? { + do { + return try Decoration.Style(fromMap: map) + } catch { + Log.reader.error("setDecorationStyle: ignoring unparsable style: \(error)") + return nil + } + } + @MainActor func emitExternalPlaybackCommand(_ command: ReadiumExternalPlaybackCommand) { externalPlaybackCommandStreamHandler?.sendEvent(command.toMap()) diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/model/preferences/FlutterEPUBPreferences.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/model/preferences/FlutterEPUBPreferences.swift index 6403c94f7..b8b9b6718 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/model/preferences/FlutterEPUBPreferences.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/model/preferences/FlutterEPUBPreferences.swift @@ -4,9 +4,11 @@ let blackAndWhiteComicModeKey: String = "blackAndWhiteComicMode"; let disableSynchronizationKey: String = "disableSynchronization"; let firstElementTopMarginKey: String = "firstElementTopMargin"; let preventMOColumnBreaksKey: String = "preventMOColumnBreaks"; +let makeSpaceForMarginDecorationKey: String = "makeSpaceForMarginDecoration"; let topMarginCssVariable = "--FLUTTER_READIUM-first-element-top-margin" let blackAndWhiteComicModeCssVariable = "--FLUTTER_READIUM-black-white-comic-mode"; +let marginDecorationSpaceCssVariable = "--FLUTTER_READIUM-margin-decoration-space" public struct FlutterEPUBPreferences { @@ -22,6 +24,8 @@ public struct FlutterEPUBPreferences { /// When true (default), prevents paragraph elements from splitting across CSS columns during /// media-overlay playback. Nil means the Dart-side default (true) applies. public var preventMOColumnBreaks: Bool? + /// Widens the side page margins to fit a margin marker decoration (rule in FlutterReadiumTools.scss). + public var makeSpaceForMarginDecoration: Bool? init() { readium = EPUBPreferences.init(); @@ -46,6 +50,10 @@ public struct FlutterEPUBPreferences { self.preventMOColumnBreaks = preventMOColumnBreaks mutableMap.removeValue(forKey: preventMOColumnBreaksKey); } + if let makeSpace = jsonMap[makeSpaceForMarginDecorationKey] as? Bool { + self.makeSpaceForMarginDecoration = makeSpace + mutableMap.removeValue(forKey: makeSpaceForMarginDecorationKey); + } readium = EPUBPreferences.init(fromMap: mutableMap) } @@ -55,6 +63,7 @@ public struct FlutterEPUBPreferences { map[topMarginCssVariable] = firstElementTopMargin.map { "\($0)px" } map[blackAndWhiteComicModeCssVariable] = (blackAndWhiteComicMode == true) ? "1" : nil + map[marginDecorationSpaceCssVariable] = (makeSpaceForMarginDecoration == true) ? "1" : nil return map } diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift index 8548cfbbe..c6851ac6b 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift @@ -1,10 +1,31 @@ import Foundation import ReadiumNavigator import ReadiumShared +import UIKit + +extension Decoration.Style.Id { + static let marginMarker: Decoration.Style.Id = "marginMarker" +} + +/// Payload of a `marginMarker` decoration style. `side` is "start" or "end"; `anchor` is "page" or "text". +struct MarginMarkerConfig: Hashable { + var label: String? + var icon: String? + var side: String + var anchor: String + var tint: UIColor? + + /// SVG path data (24x24 viewBox) by `MarginMarkerIcon` name. Keep in sync with Dart, Android and web. + static let iconPaths: [String: String] = [ + "bookmark": "M6 2h12a1 1 0 0 1 1 1v19l-7-4-7 4V3a1 1 0 0 1 1-1z", + "note": "M4 3h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H9l-5 4v-4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM7 7v2h10V7zm0 4v2h7v-2z", + "star": "M12 2l2.9 6.9 7.1.6-5.4 4.7 1.6 7-6.2-3.8-6.2 3.8 1.6-7L2 9.5l7.1-.6z", + ] +} /// Decoration application, decoration-interaction observation, the custom -/// "highlight current selection" editing action, and the spotlight decoration -/// template used for TTS utterance highlighting. +/// "highlight current selection" editing action, and the spotlight and margin +/// marker decoration templates. extension EPUBReaderView { public func applyDecorations(_ decorations: [Decoration], forGroup groupIdentifier: String) { @@ -95,4 +116,47 @@ extension EPUBReaderView { } ) } + + /// Margin marker floated into the page margin, or placed next to the text for the "text" anchor. Keep + /// the markup identical to the Android and web templates; the design is in docs/plans/margin-marker-decorations.md. + static func marginMarkerDecorationTemplate() -> HTMLDecorationTemplate { + HTMLDecorationTemplate( + layout: .bounds, + width: .page, + element: { decoration in + guard let config = decoration.style.config as? MarginMarkerConfig else { + Log.reader.error("marginMarkerDecorationTemplate: unexpected style config") + return "
" + } + let content: String + // Labels are muted like printed margin page numbers; icons keep the full colour. + var opacity = "" + if let label = config.label { + content = Self.escapeHtmlAttr(label) + opacity = " opacity: 0.8 !important;" + } else if let path = config.icon.flatMap({ MarginMarkerConfig.iconPaths[$0] }) { + content = "" + } else { + return "
" + } + let end = config.side == "end" + var css = " font-size: 0.75em !important; line-height: 1.4 !important;" + opacity + if let tint = config.tint { + css += " color: \(tint.cssValue()) !important;" + } + if config.anchor == "text" { + // The cell is as wide as the margin, which flutterReadiumTools.js measures. The marker is pushed + // against the cell's text side; in a too-narrow margin it overflows toward the text, never off the page. + let cell = "display: flex !important; flex-direction: \(end ? "row-reverse" : "row") !important;" + + " box-sizing: border-box !important; width: var(--flutter-readium-text-inset-\(end ? "end" : "start"), 0px) !important;" + + " padding-inline: \(end ? "0.5em 4px" : "4px 0.5em") !important;\(end ? " margin-inline-start: auto !important;" : "")" + let push = "margin-\(end ? "inline-end" : "inline-start"): auto !important; flex: none !important;" + return "
\(content)
" + } + let float = "float: \(end ? "right" : "left") !important; float: \(end ? "inline-end" : "inline-start") !important;" + + " margin: 0 max(4px, 1.5%) !important;" + return "
\(content)
" + } + ) + } } diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+MethodChannel.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+MethodChannel.swift index 0bb96ed5e..ff13b973f 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+MethodChannel.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+MethodChannel.swift @@ -99,11 +99,14 @@ extension EPUBReaderView { let identifier = args[0] as! String let decorationsStr = args[1] as! [String] - guard let decorations = try? decorationsStr.map({ try Decoration(fromJson: $0) }) else { - return result(FlutterError.init( - code: "JSON mapping error", - message: "Could not map decorations from JSON: \(decorationsStr)", - details: nil)) + // Skip decorations that fail to parse (e.g. a marginMarker without a marker) instead of dropping the whole group. + let decorations = decorationsStr.compactMap { str -> Decoration? in + do { + return try Decoration(fromJson: str) + } catch { + Log.reader.error("applyDecorations: skipping unparsable decoration: \(error)") + return nil + } } applyDecorations(decorations, forGroup: identifier) diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Preferences.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Preferences.swift index c1d8f07f0..83584752f 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Preferences.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Preferences.swift @@ -16,14 +16,16 @@ extension EPUBReaderView { } /// Resolves preferences against the publication's layout. The first-element top - /// margin is a reflowable-text affordance, so it's dropped for every non-reflowable - /// publication — FXL EPUBs and paginated DiViNa report `.fixed`, scrolled DiViNa - /// reports `.scrolled`, and image publications (CBZ via ImageParser) report no - /// layout at all — where it would otherwise shift the full-page content down. + /// margin and the margin-decoration space are reflowable-text affordances, so they're + /// dropped for every non-reflowable publication — FXL EPUBs and paginated DiViNa report + /// `.fixed`, scrolled DiViNa reports `.scrolled`, and image publications (CBZ via + /// ImageParser) report no layout at all — where they would otherwise shift the + /// full-page content. func effectivePreferences(_ preferences: FlutterEPUBPreferences) -> FlutterEPUBPreferences { guard publication.metadata.layout != .reflowable else { return preferences } var resolved = preferences resolved.firstElementTopMargin = nil + resolved.makeSpaceForMarginDecoration = nil return resolved } diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView.swift index 3bd4d8d4f..cd54019a0 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView.swift @@ -169,6 +169,7 @@ public class EPUBReaderView: NSObject, FlutterPlatformView, ReadiumReaderView, E // NOTE: Use experimentalPositioning. It places highlights on z-index -1 behind text, instead of on top. var decorationTemplates = HTMLDecorationTemplate.defaultTemplates(alpha: 1.0, experimentalPositioning: true) decorationTemplates[Decoration.Style.Id("spotlight")] = EPUBReaderView.spotlightDecorationTemplate() + decorationTemplates[.marginMarker] = EPUBReaderView.marginMarkerDecorationTemplate() config.decorationTemplates = decorationTemplates // TODO: This is a PoC for adding custom editing actions, like user highlights. It should be configurable from Flutter. diff --git a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/utils/ReadiumExtensions.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/utils/ReadiumExtensions.swift index f1297ef13..414e1e3c3 100644 --- a/flutter_readium/ios/flutter_readium/Sources/flutter_readium/utils/ReadiumExtensions.swift +++ b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/utils/ReadiumExtensions.swift @@ -492,7 +492,8 @@ extension Decoration.Style { } // Accepts the flat style map produced by ReaderDecorationStyle.toJson() on the Dart side: - // { "style": "highlight", "tint": "#RRGGBB" (optional), "isActive": true/false } + // { "style": "highlight", "tint": "#RRGGBB" (optional), "isActive": true/false, + // "marker": { "label"|"icon", "side", "anchor" } (only for "marginMarker") } // `tint` is optional — when absent the decoration has no background colour. init(fromMap jsonMap: [String: Any]?) throws { guard let map = jsonMap, @@ -503,6 +504,25 @@ extension Decoration.Style { } let isActive = map["isActive"] as? Bool ?? false let tintColor: Color? = (map["tint"] as? String).flatMap { Color(hex: $0) } + + if styleStr == Decoration.Style.Id.marginMarker.rawValue { + // A marker with neither a label nor a known icon would render nothing, so reject it. + let marker = map["marker"] as? [String: Any] + let label = (marker?["label"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let icon = (marker?["icon"] as? String).flatMap { MarginMarkerConfig.iconPaths[$0] != nil ? $0 : nil } + guard label != nil || icon != nil else { + Log.readium.error("Decoration parse error: `marginMarker` needs a `marker` with a label or a known icon") + throw JSONError.parsing(Self.self) + } + let side = marker?["side"] as? String == "end" ? "end" : "start" + let anchor = marker?["anchor"] as? String == "page" ? "page" : "text" + self.init( + id: .marginMarker, + config: MarginMarkerConfig(label: label, icon: icon, side: side, anchor: anchor, tint: tintColor?.uiColor) + ) + return + } + try self.init(withStyle: styleStr, tintColor: tintColor, isActive: isActive) } } diff --git a/flutter_readium/lib/flutter_readium.dart b/flutter_readium/lib/flutter_readium.dart index 588177f0f..f6a1a1302 100644 --- a/flutter_readium/lib/flutter_readium.dart +++ b/flutter_readium/lib/flutter_readium.dart @@ -165,10 +165,18 @@ class FlutterReadium { /// Applies a list of decorations to the visual reader. /// /// The decorations will be identified by the given [id], which can be used to update or remove them later by calling this method again with the same [id]. + /// + /// A [DecorationStyle.marginMarker] decoration needs a [ReaderDecorationStyle.marker]; all platforms skip one without. Future applyDecorations( String id, List decorations, - ) => _readiumCall(() => _platform.applyDecorations(id, decorations)); + ) { + assert( + decorations.every((d) => d.style.style != DecorationStyle.marginMarker || d.style.marker != null), + 'A marginMarker decoration requires a marker.', + ); + return _readiumCall(() => _platform.applyDecorations(id, decorations)); + } /// Enables TTS (text-to-speech) for the currently opened publication, optionally applying the given [preferences]. Future ttsEnable(TTSPreferences? preferences) => _readiumCall(() => _platform.ttsEnable(preferences)); diff --git a/flutter_readium/web/src/ReadiumReader.ts b/flutter_readium/web/src/ReadiumReader.ts index c6a7fcc0b..07e2da590 100644 --- a/flutter_readium/web/src/ReadiumReader.ts +++ b/flutter_readium/web/src/ReadiumReader.ts @@ -1,7 +1,7 @@ import "./style.css"; import { AudioNavigator, EpubNavigator, WebPubNavigator } from "@readium/navigator"; -import { getTime, Link, Locator, Publication } from "@readium/shared"; +import { getTime, Layout, Link, Locator, Publication } from "@readium/shared"; // Bridge import { ReadiumBridge } from "./bridge/ReadiumBridge"; @@ -52,7 +52,7 @@ import { UncuedTocTargets } from "./mediaoverlay/uncuedTocTargets"; // Decoration overrides (for comic/visual sync) import { navIframeWindows } from "./decorations/decorationFrameUtils"; // Iframe injection utilities -import { injectMOBreakCSSIntoWindow, setHelperAssetUrls } from "./utils/iframeInjection"; +import { injectMOBreakCSSIntoWindow, setHelperAssetUrls, setMarginDecorationSpaceInWindow } from "./utils/iframeInjection"; import { FontFamilyDeclaration, injectFontFacesIntoWindow, parseFontFamilyDeclarations } from "./fonts/FontFamilyDeclarations"; // Errors import { ReadiumWebError, ReadiumWebErrorCode, ResourceReadErrorReason } from "./errors/ReadiumWebError"; @@ -208,6 +208,8 @@ class _ReadiumReader { private _narrationSyncEnabled = true; /** Mirrors `EPUBPreferences.preventMOColumnBreaks`. Defaults to `true`. */ private _preventMOColumnBreaks = true; + /** Mirrors `EPUBPreferences.makeSpaceForMarginDecoration`; always off for fixed layout. */ + private _makeSpaceForMarginDecoration = false; /** Last visual sync locator deferred while synchronization was disabled. */ private _lastDeferredSyncLocator: Locator | null = null; /** Segment duration paired with `_lastDeferredSyncLocator` when available. */ @@ -576,6 +578,7 @@ class _ReadiumReader { this._selectionToolbar.attach(container); if (publication.conformsToEpub) { log.info("Publication conforms to EPUB profile"); + this._makeSpaceForMarginDecoration = this._wantsMarginDecorationSpace(preferencesJsonString); await FlutterEpubNavigator.create( container, publication, @@ -586,6 +589,7 @@ class _ReadiumReader { (json) => { this._bridge.emitImageTapped(json); }, (wnd) => { injectFontFacesIntoWindow(wnd, fontFamilyDeclarations); + setMarginDecorationSpaceInWindow(wnd, this._makeSpaceForMarginDecoration); // Re-inject MO column-break CSS into freshly-loaded frames when MO is active. // Use direct DOM manipulation — window.flutterReadium is deferred by rAF // inside the helper script and may not exist yet at frameLoaded time. @@ -698,6 +702,11 @@ class _ReadiumReader { } } this._preventMOColumnBreaks = preventMOColumnBreaks; + const makeSpace = this._wantsMarginDecorationSpace(newPreferencesString); + if (makeSpace !== this._makeSpaceForMarginDecoration) { + this._makeSpaceForMarginDecoration = makeSpace; + for (const wnd of navIframeWindows(this._nav)) setMarginDecorationSpaceInWindow(wnd, makeSpace); + } } catch (_) { // Ignore parse errors — setEpubPreferencesFromString will surface them. } @@ -1159,6 +1168,17 @@ class _ReadiumReader { } } + /** Body padding on a fixed-layout page would shift it, so the preference only applies to reflowable EPUBs. */ + private _wantsMarginDecorationSpace(preferencesJson: string): boolean { + const publication = this._publication; + if (!publication || EpubNavigator.determineLayout(publication) === Layout.fixed) return false; + try { + return pluginPrefsFromJson(JSON.parse(preferencesJson)).makeSpaceForMarginDecoration; + } catch (_) { + return false; + } + } + /** Inject MO column-break CSS into all loaded EPUB iframes directly via the DOM. */ private _injectMOBreakCSSOnIframes(): void { if (!this._nav) return; diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index 0ae7a3d56..7015d10b8 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -129,6 +129,147 @@ describe("DecorationController", () => { }); }); + describe("margin markers", () => { + function marker(id: string, style: object) { + return { id, locator: locator.serialize(), style: { style: "marginMarker", ...style } }; + } + const label = (text: string, side = "start") => ({ marker: { label: text, side, anchor: "page" } }); + + it("renders a label as a bounds/page template in the decoration's own group", () => { + const { controller, nav } = setup(); + + controller.applyDecorations(nav as any, "page-list", JSON.stringify([marker("p12", label("12", "end"))])); + + const [deco] = appliedTo(nav, "page-list"); + expect(deco.style).toEqual(expect.objectContaining({ type: "template", layout: "bounds", width: "page" })); + const html: string = deco.style.element(deco); + expect(html).toContain('data-activable="1"'); + expect(html).toContain(">12"); + expect(html).toContain("float: right !important; float: inline-end !important;"); + expect(html).toContain("opacity: 0.8 !important;"); + expect(html).not.toContain(" color:"); + expect(appliedTo(nav, "page-list__spotlight")).toEqual([]); + }); + + it("escapes the label", () => { + const { controller, nav } = setup(); + + controller.applyDecorations(nav as any, "page-list", JSON.stringify([marker("x", label('"&'))])); + + const [deco] = appliedTo(nav, "page-list"); + expect(deco.style.element(deco)).toContain("<b>"&"); + }); + + it("renders the bookmark icon on the start side and applies the tint", () => { + const { controller, nav } = setup(); + + controller.applyDecorations( + nav as any, + "highlight-markers", + JSON.stringify([marker("b", { tint: "#ff2e7d32", marker: { icon: "bookmark", side: "start", anchor: "page" } })]) + ); + + const [deco] = appliedTo(nav, "highlight-markers"); + const html: string = deco.style.element(deco); + expect(html).toContain(" { + const { controller, nav } = setup(); + + controller.applyDecorations( + nav as any, + "highlight-markers", + JSON.stringify([marker("t", { marker: { icon: "bookmark", side } })]) + ); + + const [deco] = appliedTo(nav, "highlight-markers"); + const html: string = deco.style.element(deco); + expect(html).toContain(`flex-direction: ${direction} !important;`); + expect(html).toContain(`width: var(${inset}, 0px) !important;`); + expect(html).toContain(` { + const { controller, nav } = setup(); + + controller.applyDecorations(nav as any, "highlight-markers", JSON.stringify([marker(icon, { marker: { icon } })])); + + const [deco] = appliedTo(nav, "highlight-markers"); + expect(deco.style.element(deco)).toMatch(/<\/svg><\/span>/); + }); + + it("puts the marker payload and tint in extras so a changed tint re-renders", () => { + const { controller, nav } = setup(); + + controller.applyDecorations( + nav as any, + "page-list", + JSON.stringify([marker("p1", { tint: "#ffff0000", ...label("1") })]) + ); + controller.applyDecorations( + nav as any, + "page-list", + JSON.stringify([marker("p1", { tint: "#ff00ff00", ...label("1") })]) + ); + + const [first, second] = nav.applyDecorations.mock.calls + .filter(([, g]) => g === "page-list") + .map(([list]) => list[0]); + expect(first.extras).toEqual({ marker: { label: "1", side: "start", anchor: "page" }, tint: "#ff0000ff" }); + expect(second.extras).toEqual({ marker: { label: "1", side: "start", anchor: "page" }, tint: "#00ff00ff" }); + expect(JSON.stringify(first.extras)).not.toEqual(JSON.stringify(second.extras)); + }); + + it("skips a marker without a label or known icon and keeps the rest", () => { + const warn = jest.spyOn(console, "warn").mockImplementation(() => {}); + const { controller, nav } = setup(); + + controller.applyDecorations( + nav as any, + "page-list", + JSON.stringify([ + marker("none", {}), + marker("empty", { marker: { side: "end" } }), + marker("unknown-icon", { marker: { icon: "rocket" } }), + marker("prototype-key", { marker: { icon: "constructor" } }), + marker("ok", label("7")), + ]) + ); + + expect(appliedTo(nav, "page-list").map((d) => d.id)).toEqual(["ok"]); + expect(warn).toHaveBeenCalledTimes(4); + warn.mockRestore(); + }); + + it("reports a tap on a marker with the app's group name", () => { + const { bridge, controller, nav } = setup(); + controller.applyDecorations(nav as any, "page-list", JSON.stringify([marker("p3", label("3"))]), { + tappable: true, + }); + const observer = nav.registerDecorationObserver.mock.calls.find(([g]) => g === "page-list")![1]; + + observer.onDecorationActivated({ + decoration: appliedTo(nav, "page-list")[0], + group: "page-list", + rect: { top: 0, left: 0, width: 1, height: 1 }, + point: { x: 0, y: 0 }, + }); + + expect(bridge.emitDecorationInteraction).toHaveBeenCalledWith( + expect.objectContaining({ decorationId: "p3", group: "page-list", type: "tap" }) + ); + }); + }); + describe("decoration taps", () => { it("registers observers for the group and its subgroups only when tappable", () => { const { controller, nav } = setup(); diff --git a/flutter_readium/web/src/__tests__/iframeInjection.test.ts b/flutter_readium/web/src/__tests__/iframeInjection.test.ts index 052c73fd2..86f63550c 100644 --- a/flutter_readium/web/src/__tests__/iframeInjection.test.ts +++ b/flutter_readium/web/src/__tests__/iframeInjection.test.ts @@ -3,6 +3,7 @@ import { injectFlutterReadiumHelperScripts, scrollingElementGuardRule, setHelperAssetUrls, + setMarginDecorationSpaceInWindow, } from "../utils/iframeInjection"; describe("injectFlutterReadiumHelperScripts", () => { @@ -20,6 +21,21 @@ describe("injectFlutterReadiumHelperScripts", () => { }); }); +describe("setMarginDecorationSpaceInWindow", () => { + // The helper CSS rule matches this attribute; a root style property would be stripped by ts-toolkit. + it("toggles the data attribute the helper CSS matches", () => { + const frameDocument = document.implementation.createHTMLDocument(); + const wnd = { document: frameDocument } as unknown as Window; + const attr = "data-flutter-readium-margin-decoration-space"; + + setMarginDecorationSpaceInWindow(wnd, true); + expect(frameDocument.documentElement.hasAttribute(attr)).toBe(true); + + setMarginDecorationSpaceInWindow(wnd, false); + expect(frameDocument.documentElement.hasAttribute(attr)).toBe(false); + }); +}); + describe("scrollingElementGuardRule", () => { // jsdom has no scrollingElement, so each test supplies the "native" getter. const nativeDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, "scrollingElement"); diff --git a/flutter_readium/web/src/__tests__/preferences.test.ts b/flutter_readium/web/src/__tests__/preferences.test.ts index f53211e55..b8ddab2ad 100644 --- a/flutter_readium/web/src/__tests__/preferences.test.ts +++ b/flutter_readium/web/src/__tests__/preferences.test.ts @@ -7,7 +7,7 @@ * value through without any /100 conversion. */ -import { epubPreferencesFromJson } from "../preferences/FlutterEpubPreferences"; +import { epubPreferencesFromJson, pluginPrefsFromJson } from "../preferences/FlutterEpubPreferences"; import { initializeWebPubPreferencesFromString } from "../preferences/FlutterWebPubPreferences"; describe("EPUBPreferences fontSize — forwarded as ratio, not converted", () => { @@ -47,3 +47,14 @@ describe("WebPubPreferences fontSize → zoom — forwarded as ratio", () => { expect(out.zoom ?? null).toBeNull(); }); }); + +describe("EPUBPreferences makeSpaceForMarginDecoration — plugin-owned", () => { + it("is read by pluginPrefsFromJson and defaults to false", () => { + expect(pluginPrefsFromJson({ makeSpaceForMarginDecoration: true }).makeSpaceForMarginDecoration).toBe(true); + expect(pluginPrefsFromJson({}).makeSpaceForMarginDecoration).toBe(false); + }); + + it("is not forwarded to the navigator", () => { + expect(epubPreferencesFromJson({ makeSpaceForMarginDecoration: true })).not.toHaveProperty("makeSpaceForMarginDecoration"); + }); +}); diff --git a/flutter_readium/web/src/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index 9d8742319..2c3df900c 100644 --- a/flutter_readium/web/src/decorations/DecorationController.ts +++ b/flutter_readium/web/src/decorations/DecorationController.ts @@ -7,6 +7,7 @@ import { Decoration, + DecorationLayout, DecorationStyleType, DecorationWidth, EpubNavigator, @@ -21,6 +22,73 @@ import { } from "./decorationFrameUtils"; import { dartColorToCss } from "../utils/colors"; import { ReadiumBridge } from "../bridge/ReadiumBridge"; +import { createLogger } from "../utils/ReadiumPluginLogger"; + +const log = createLogger("DecorationController"); + +/** Wire shape of `MarginMarker.toJson()` on the Dart side. */ +interface MarginMarker { + label?: string; + icon?: string; + side?: string; + anchor?: string; +} + +/** SVG path data (24x24 viewBox) by `MarginMarkerIcon` name. Keep in sync with Dart, iOS and Android. */ +const MARGIN_MARKER_ICON_PATHS = new Map([ + ["bookmark", "M6 2h12a1 1 0 0 1 1 1v19l-7-4-7 4V3a1 1 0 0 1 1-1z"], + ["note", "M4 3h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H9l-5 4v-4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM7 7v2h10V7zm0 4v2h7v-2z"], + ["star", "M12 2l2.9 6.9 7.1.6-5.4 4.7 1.6 7-6.2-3.8-6.2 3.8 1.6-7L2 9.5l7.1-.6z"], +]); + +function marginMarkerIconSvg(icon: string): string | undefined { + const path = MARGIN_MARKER_ICON_PATHS.get(icon); + return path === undefined + ? undefined + : ``; +} + +function escapeHtml(s: string): string { + return s + .replace(/&/g, "&") + .replace(/"/g, """) + .replace(//g, ">"); +} + +/** + * Builds the margin marker element, or `null` when there is nothing to show. It floats into the page + * margin, or sits next to the text for the "text" anchor. Keep the markup identical to the iOS and + * Android templates; the design is in docs/plans/margin-marker-decorations.md. + */ +function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undefined): string | null { + const content = marker?.label + ? escapeHtml(marker.label) + : marker?.icon !== undefined + ? marginMarkerIconSvg(marker.icon) + : undefined; + if (!content) return null; + + const end = marker?.side === "end"; + let css = " font-size: 0.75em !important; line-height: 1.4 !important;"; + // Labels are muted like printed margin page numbers; icons keep the full colour. + if (marker?.label) css += " opacity: 0.8 !important;"; + if (tint) css += ` color: ${escapeHtml(tint)} !important;`; + if (marker?.anchor !== "page") { + // The cell is as wide as the margin, which flutterReadiumTools.js measures. The marker is pushed + // against the cell's text side; in a too-narrow margin it overflows toward the text, never off the page. + const cell = + `display: flex !important; flex-direction: ${end ? "row-reverse" : "row"} !important;` + + ` box-sizing: border-box !important; width: var(--flutter-readium-text-inset-${end ? "end" : "start"}, 0px) !important;` + + ` padding-inline: ${end ? "0.5em 4px" : "4px 0.5em"} !important;${end ? " margin-inline-start: auto !important;" : ""}`; + const push = `margin-${end ? "inline-end" : "inline-start"}: auto !important; flex: none !important;`; + return `
${content}
`; + } + const float = + `float: ${end ? "right" : "left"} !important; float: ${end ? "inline-end" : "inline-start"} !important;` + + " margin: 0 max(4px, 1.5%) !important;"; + return `
${content}
`; +} export interface ApplyDecorationsOptions { /** @@ -68,7 +136,7 @@ export class DecorationController { const decorationsRaw: Array<{ id: string; locator: object; - style: { style: string; tint: string }; + style: { style: string; tint?: string; marker?: MarginMarker }; }> = JSON.parse(decorationsJson); // Every subgroup gets a list, even an empty one, so that a subgroup the new @@ -79,10 +147,33 @@ export class DecorationController { ]); for (const raw of decorationsRaw) { + if (raw.style.style === "marginMarker") { + const tint = raw.style.tint ? dartColorToCss(raw.style.tint) : undefined; + const html = marginMarkerHtml(raw.style.marker, tint); + if (html === null) { + log.warn(`applyDecorations: skipping marginMarker ${raw.id} without a label or known icon`); + continue; + } + bySubgroup.get(group)!.push({ + id: raw.id, + locator: Locator.deserialize(raw.locator)!, + style: { + type: DecorationStyleType.Template, + layout: DecorationLayout.Bounds, + width: DecorationWidth.Page, + element: () => html, + }, + // Upstream ignores a Template's element when diffing, so the payload goes into extras + // to make a changed label, icon, side or tint re-render under the same id. + extras: { marker: raw.style.marker, tint }, + }); + continue; + } + const isSpotlight = raw.style.style === "spotlight"; // Convert tints from Dart's AARRGGBB to CSS RRGGBBAA at the entry point so // upstream's Decorator and the spotlight CSS see CSS colors. - const tint = dartColorToCss(raw.style.tint); + const tint = raw.style.tint ? dartColorToCss(raw.style.tint) : undefined; bySubgroup.get(isSpotlight ? spotlightGroup : group)!.push({ id: raw.id, diff --git a/flutter_readium/web/src/preferences/FlutterEpubPreferences.ts b/flutter_readium/web/src/preferences/FlutterEpubPreferences.ts index f1df8312b..dc3086c19 100644 --- a/flutter_readium/web/src/preferences/FlutterEpubPreferences.ts +++ b/flutter_readium/web/src/preferences/FlutterEpubPreferences.ts @@ -179,6 +179,8 @@ export function epubPreferencesFromJson( // custom CSS injection into the EPUB iframe. // - disableSynchronization: handled by ReadiumReader (plugin state), not navigator prefs. // - preventMOColumnBreaks: handled by ReadiumReader (plugin state), not navigator prefs. + // - makeSpaceForMarginDecoration: handled by ReadiumReader, which flags each EPUB iframe + // for the padding rule in the helper CSS. // --------------------------------------------------------------------------- return normalizeTypes(out); @@ -190,9 +192,11 @@ export function epubPreferencesFromJson( */ export function pluginPrefsFromJson(prefs: Record): { preventMOColumnBreaks: boolean; + makeSpaceForMarginDecoration: boolean; } { return { preventMOColumnBreaks: prefs.preventMOColumnBreaks !== false, + makeSpaceForMarginDecoration: prefs.makeSpaceForMarginDecoration === true, }; } diff --git a/flutter_readium/web/src/utils/iframeInjection.ts b/flutter_readium/web/src/utils/iframeInjection.ts index 750c21373..8d343f2d6 100644 --- a/flutter_readium/web/src/utils/iframeInjection.ts +++ b/flutter_readium/web/src/utils/iframeInjection.ts @@ -58,6 +58,20 @@ export function injectMOBreakCSSIntoWindow(wnd: Window): void { doc.head.appendChild(style); } +/** + * Switches the helper CSS rule that widens the side page margins for margin markers + * (`EPUBPreferences.makeSpaceForMarginDecoration`). A data attribute rather than a root CSS + * variable, because ts-toolkit removes root style properties it did not set on every CSS update. + */ +export function setMarginDecorationSpaceInWindow(wnd: Window, enabled: boolean): void { + const root = wnd.document.documentElement; + if (enabled) { + root.dataset.flutterReadiumMarginDecorationSpace = ""; + } else { + delete root.dataset.flutterReadiumMarginDecorationSpace; + } +} + /** * Readium reads `document.scrollingElement` without a null check, and Safari returns null in a * quirks-mode frame. Prepended so it runs in every frame before Readium's modules attach. diff --git a/flutter_readium_platform_interface/changelog.d/+decoration-style-fromjson-tint.fixed.md b/flutter_readium_platform_interface/changelog.d/+decoration-style-fromjson-tint.fixed.md new file mode 100644 index 000000000..18199863e --- /dev/null +++ b/flutter_readium_platform_interface/changelog.d/+decoration-style-fromjson-tint.fixed.md @@ -0,0 +1,2 @@ +**`ReaderDecorationStyle.fromJson` no longer throws for a tinted style.** +It read `tint` as an integer, but `toJson` sends a CSS colour string, so round-tripping any tinted style failed. It now parses the CSS string. diff --git a/flutter_readium_platform_interface/changelog.d/+margin-decoration-space.added.md b/flutter_readium_platform_interface/changelog.d/+margin-decoration-space.added.md new file mode 100644 index 000000000..e9ac3f5bc --- /dev/null +++ b/flutter_readium_platform_interface/changelog.d/+margin-decoration-space.added.md @@ -0,0 +1,3 @@ +**Room for margin markers at any font size.** +At large font sizes a margin marker could overlap the text, because the page margin does not grow with the font. +The opt-in `EPUBPreferences.makeSpaceForMarginDecoration` widens the side margins with the font size so markers fit, on iOS, Android and web. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#margin-width). diff --git a/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md b/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md new file mode 100644 index 000000000..911313c45 --- /dev/null +++ b/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md @@ -0,0 +1,3 @@ +**Margin marker decorations.** +`DecorationStyle.marginMarker` shows a text label or a built-in icon (bookmark, note or star) in the margin, level with the first line of a locator, on iOS, Android and web. +By default a marker sits a small gap from the text column; `anchor: MarginAnchor.page` puts it at the page edge instead. Use it for printed page numbers or bookmarked highlights. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md). diff --git a/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart index 1f7c00f86..f79f818dd 100644 --- a/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart +++ b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart @@ -10,8 +10,13 @@ enum DecorationStyle { /// Colored border-bottom under the active text line. underline, - /// Tinted box behind text **and** all surrounding body text is dimmed, drawing the eye to the active range. | - spotlight; + /// Tinted box behind text **and** all surrounding body text is dimmed, drawing the eye to the active range. + spotlight, + + /// Small label or icon floated into the page margin, level with the first line of the range. + /// + /// Requires [ReaderDecorationStyle.marker]; a decoration without one is skipped. Supported on iOS, Android and web. + marginMarker; static DecorationStyle fromString(String? styleStr) { switch (styleStr) { @@ -19,6 +24,8 @@ enum DecorationStyle { return DecorationStyle.underline; case 'spotlight': return DecorationStyle.spotlight; + case 'marginMarker': + return DecorationStyle.marginMarker; case 'highlight': default: return DecorationStyle.highlight; @@ -57,8 +64,63 @@ class ReaderDecoration implements JSONable { ); } +/// Built-in icons for [MarginMarker.icon]. Icons are a closed set so that Dart never supplies markup. +enum MarginMarkerIcon { + /// A bookmark ribbon. + bookmark, + + /// A speech bubble with text lines, for a highlight that carries a note. + note, + + /// A star, for favourite or important passages. + star, +} + +/// Which page margin a [MarginMarker] sits in. Logical: [start] is the left margin in LTR and the right margin in RTL. +enum MarginSide { start, end } + +/// What a [MarginMarker] lines up with horizontally. +enum MarginAnchor { + /// Near the edge of the page (or of the column, in two-column layouts). Suits printed page numbers. + page, + + /// A small gap from the text column, however wide the margin is. The default. + text, +} + +/// The content of a [DecorationStyle.marginMarker] decoration: a text label or a built-in icon. +class MarginMarker implements JSONable { + const MarginMarker.label(String this.label, {this.side = MarginSide.start, this.anchor = MarginAnchor.text}) + : icon = null; + + const MarginMarker.icon(MarginMarkerIcon this.icon, {this.side = MarginSide.start, this.anchor = MarginAnchor.text}) + : label = null; + + const MarginMarker._({this.label, this.icon, this.side = MarginSide.start, this.anchor = MarginAnchor.text}); + + factory MarginMarker.fromJson(final Map map) => MarginMarker._( + label: map['label'] as String?, + icon: MarginMarkerIcon.values.where((i) => i.name == map['icon']).firstOrNull, + side: MarginSide.values.where((s) => s.name == map['side']).firstOrNull ?? MarginSide.start, + anchor: MarginAnchor.values.where((a) => a.name == map['anchor']).firstOrNull ?? MarginAnchor.text, + ); + + final String? label; + final MarginMarkerIcon? icon; + final MarginSide side; + final MarginAnchor anchor; + + @override + Map toJson() => { + if (label != null) 'label': label, + if (icon != null) 'icon': icon!.name, + 'side': side.name, + 'anchor': anchor.name, + }; +} + class ReaderDecorationStyle implements JSONable { - const ReaderDecorationStyle({required this.style, this.tint, this.isActive = false}); + const ReaderDecorationStyle({required this.style, this.tint, this.isActive = false, this.marker}); final DecorationStyle style; @@ -76,23 +138,35 @@ class ReaderDecorationStyle implements JSONable { /// implemented there. final bool isActive; + /// The label or icon to show. Required when [style] is [DecorationStyle.marginMarker]; ignored otherwise. + /// + /// [tint] colours the marker, and [isActive] is ignored. + final MarginMarker? marker; + @override Map toJson() => { 'style': style.name, if (tint != null) 'tint': tint!.toCSS(), 'isActive': isActive, + if (marker != null) 'marker': marker!.toJson(), }; factory ReaderDecorationStyle.fromJson(final Map map) => ReaderDecorationStyle( style: DecorationStyle.fromString(map['style']), - tint: map['tint'] != null ? Color(map['tint'] as int) : null, + tint: map['tint'] is String ? ReadiumColorExtension.fromCSS(map['tint'] as String) : null, isActive: map['isActive'] as bool? ?? false, + marker: map['marker'] is Map ? MarginMarker.fromJson(Map.from(map['marker'] as Map)) : null, ); - ReaderDecorationStyle copyWith({Object style = unset, Object? tint = unset, Object isActive = unset}) => - ReaderDecorationStyle( - style: identical(style, unset) ? this.style : (style as DecorationStyle), - tint: identical(tint, unset) ? this.tint : tint as Color?, - isActive: identical(isActive, unset) ? this.isActive : (isActive as bool), - ); + ReaderDecorationStyle copyWith({ + Object style = unset, + Object? tint = unset, + Object isActive = unset, + Object? marker = unset, + }) => ReaderDecorationStyle( + style: identical(style, unset) ? this.style : (style as DecorationStyle), + tint: identical(tint, unset) ? this.tint : tint as Color?, + isActive: identical(isActive, unset) ? this.isActive : (isActive as bool), + marker: identical(marker, unset) ? this.marker : marker as MarginMarker?, + ); } diff --git a/flutter_readium_platform_interface/lib/src/reader/reader_epub_preferences.dart b/flutter_readium_platform_interface/lib/src/reader/reader_epub_preferences.dart index 9163451fe..91dcd5e25 100644 --- a/flutter_readium_platform_interface/lib/src/reader/reader_epub_preferences.dart +++ b/flutter_readium_platform_interface/lib/src/reader/reader_epub_preferences.dart @@ -37,6 +37,7 @@ class EPUBPreferences with Equatable implements JSONable { this.disableSynchronization = false, this.firstElementTopMargin, this.preventMOColumnBreaks = true, + this.makeSpaceForMarginDecoration = false, }); /// Default page background color. @@ -140,6 +141,11 @@ class EPUBPreferences with Equatable implements JSONable { /// would otherwise straddle a column boundary. Has no effect outside of media-overlay mode. final bool preventMOColumnBreaks; + /// Widens the side page margins so a [DecorationStyle.marginMarker] fits beside the text at any + /// font size. The extra margin follows the font size, so it changes line length and re-paginates. + /// Never narrows the margins below [pageMargins]. Ignored for fixed-layout publications. + final bool makeSpaceForMarginDecoration; + /// Readium's supported [fontSize] range (ratio; `1.0` = 100%). Matches /// swift-toolkit's `EPUBPreferencesEditor.fontSize.supportedRange` (`0.1...5.0`). /// @@ -258,6 +264,10 @@ class EPUBPreferences with Equatable implements JSONable { fallback: true, remove: true, ); + final makeSpaceForMarginDecoration = jsonObject.optBoolean( + 'makeSpaceForMarginDecoration', + remove: true, + ); return EPUBPreferences( backgroundColor: backgroundColorStr != null ? ReadiumColorExtension.fromCSS(backgroundColorStr) : null, @@ -289,6 +299,7 @@ class EPUBPreferences with Equatable implements JSONable { disableSynchronization: disableSynchronization, firstElementTopMargin: firstElementTopMargin, preventMOColumnBreaks: preventMOColumnBreaks, + makeSpaceForMarginDecoration: makeSpaceForMarginDecoration, ); } @@ -322,7 +333,8 @@ class EPUBPreferences with Equatable implements JSONable { // ignore: deprecated_member_use_from_same_package ..put('disableSynchronization', disableSynchronization) ..putOpt('firstElementTopMargin', firstElementTopMargin) - ..put('preventMOColumnBreaks', preventMOColumnBreaks); + ..put('preventMOColumnBreaks', preventMOColumnBreaks) + ..put('makeSpaceForMarginDecoration', makeSpaceForMarginDecoration); EPUBPreferences copyWith({ Color? backgroundColor, @@ -353,6 +365,7 @@ class EPUBPreferences with Equatable implements JSONable { bool? disableSynchronization, int? firstElementTopMargin, bool? preventMOColumnBreaks, + bool? makeSpaceForMarginDecoration, }) => EPUBPreferences( backgroundColor: backgroundColor ?? this.backgroundColor, columnCount: columnCount ?? this.columnCount, @@ -383,6 +396,7 @@ class EPUBPreferences with Equatable implements JSONable { disableSynchronization: disableSynchronization ?? this.disableSynchronization, firstElementTopMargin: firstElementTopMargin ?? this.firstElementTopMargin, preventMOColumnBreaks: preventMOColumnBreaks ?? this.preventMOColumnBreaks, + makeSpaceForMarginDecoration: makeSpaceForMarginDecoration ?? this.makeSpaceForMarginDecoration, ); @override @@ -416,6 +430,7 @@ class EPUBPreferences with Equatable implements JSONable { disableSynchronization, firstElementTopMargin, preventMOColumnBreaks, + makeSpaceForMarginDecoration, ]; } diff --git a/flutter_readium_platform_interface/test/models_test.dart b/flutter_readium_platform_interface/test/models_test.dart index 9d3be9ad8..cbfb93598 100644 --- a/flutter_readium_platform_interface/test/models_test.dart +++ b/flutter_readium_platform_interface/test/models_test.dart @@ -280,6 +280,20 @@ void main() { const b = EPUBPreferences(preventMOColumnBreaks: false); expect(a, isNot(equals(b))); }); + + test('round-trips makeSpaceForMarginDecoration through toJson / fromJson', () { + const prefs = EPUBPreferences(makeSpaceForMarginDecoration: true); + final json = prefs.toJson(); + expect(json['makeSpaceForMarginDecoration'], isTrue); + expect(EPUBPreferences.fromJson(json).makeSpaceForMarginDecoration, isTrue); + }); + + test('makeSpaceForMarginDecoration defaults to false and survives copyWith', () { + expect(EPUBPreferences.fromJson({}).makeSpaceForMarginDecoration, isFalse); + const prefs = EPUBPreferences(makeSpaceForMarginDecoration: true); + expect(prefs.copyWith().makeSpaceForMarginDecoration, isTrue); + expect(prefs.copyWith(makeSpaceForMarginDecoration: false), isNot(equals(prefs))); + }); }); group('PDFPreferences', () { @@ -1088,6 +1102,75 @@ void main() { }); }); + // --------------------------------------------------------------------------- + // marginMarker decoration + // --------------------------------------------------------------------------- + group('marginMarker decoration', () { + const locator = Locator(href: '/ch.xhtml', type: 'application/xhtml+xml'); + + ReaderDecoration roundTrip(ReaderDecoration decoration) => ReaderDecoration.fromJson( + json.decode(json.encode(decoration.toJson())) as Map, + ); + + test('label marker round-trips through toJson/fromJson', () { + final decoration = ReaderDecoration( + id: 'p12', + locator: locator, + style: const ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.label('12', side: MarginSide.end), + ), + ); + final restored = roundTrip(decoration); + expect(restored.style.style, DecorationStyle.marginMarker); + expect(restored.style.marker?.label, '12'); + expect(restored.style.marker?.icon, isNull); + expect(restored.style.marker?.side, MarginSide.end); + }); + + test('tinted icon marker round-trips and defaults to the start side', () { + final decoration = ReaderDecoration( + id: 'bm', + locator: locator, + style: const ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + tint: Color(0xFF2E7D32), + marker: MarginMarker.icon(MarginMarkerIcon.bookmark), + ), + ); + expect(decoration.style.toJson()['marker'], { + 'icon': 'bookmark', + 'side': 'start', + 'anchor': 'text', + }); + final restored = roundTrip(decoration); + expect(restored.style.marker?.icon, MarginMarkerIcon.bookmark); + expect(restored.style.marker?.label, isNull); + expect(restored.style.marker?.side, MarginSide.start); + expect(restored.style.tint, const Color(0xFF2E7D32)); + }); + + test('page anchor round-trips; a missing or unknown anchor reads as text', () { + const marker = MarginMarker.label('3', anchor: MarginAnchor.page); + expect(MarginMarker.fromJson(marker.toJson()).anchor, MarginAnchor.page); + expect(MarginMarker.fromJson({'label': '3'}).anchor, MarginAnchor.text); + expect(MarginMarker.fromJson({'label': '3', 'anchor': 'gutter'}).anchor, MarginAnchor.text); + }); + + test('copyWith keeps, replaces and clears the marker', () { + const style = ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.label('1'), + ); + expect(style.copyWith().marker?.label, '1'); + expect( + style.copyWith(marker: const MarginMarker.label('2')).marker?.label, + '2', + ); + expect(style.copyWith(marker: null).marker, isNull); + }); + }); + // --------------------------------------------------------------------------- // ReadiumTimebasedState copyWith // ---------------------------------------------------------------------------