From 6474a6c0817a8e0b00adbeb218f56e44cc059220 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Wed, 18 Nov 2026 14:33:06 +0100 Subject: [PATCH 01/21] docs(plans): add margin marker decorations plan Plan a built-in `marginMarker` decoration style that shows a text label or built-in icon in the page margin on iOS, Android and web, with example recipes for pageList page numbers and bookmarked highlights. Styles are inline with !important, because ts-toolkit renders decorations in a shadow root and Readium CSS theme rules beat class rules on native. Markers need no tap suppression: data-activable keeps their tap area in the margin. Also covers the Android crash on a decoration without a tint. Co-Authored-By: Claude Opus 5.5 --- docs/plans/README.md | 1 + docs/plans/todo/margin-marker-decorations.md | 143 +++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 docs/plans/todo/margin-marker-decorations.md diff --git a/docs/plans/README.md b/docs/plans/README.md index 173c2310..18d04a53 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -30,6 +30,7 @@ This directory holds implementation plans, parity audits, and retained reference *(Maintainability / L)* - **[todo/highlight-modes.md](todo/highlight-modes.md)** — `highlight`, `underline` and `spotlight` decoration styles exist; the `ruler` style does not. *(Feature / M)* +- **[todo/margin-marker-decorations.md](todo/margin-marker-decorations.md)** — a built-in `marginMarker` decoration style (text label or icon in the page margin) on iOS, Android and web, with page-number and bookmarked-highlight recipes. *(Feature / M)* ## Upstream plans (`upstream/`) diff --git a/docs/plans/todo/margin-marker-decorations.md b/docs/plans/todo/margin-marker-decorations.md new file mode 100644 index 00000000..57d4a8a5 --- /dev/null +++ b/docs/plans/todo/margin-marker-decorations.md @@ -0,0 +1,143 @@ +# Margin Marker Decorations + +**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.13.2, injectables 2.9.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** (text, border 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, a small margin and padding, `font-size: 0.75em`, `line-height: 1.4`, `border: 1px solid currentColor`, `border-radius: 3px`, `background-color: var(--USER__backgroundColor, var(--RS__backgroundColor))`, `opacity: 0.85`, and `color: {tint}` when a tint is set. `--RS__backgroundColor` alone is always white, so it is only the fallback. The SVG carries `width="1em" height="1em"`. 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. + +## 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.13.2 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 + +- A Dart-side API for app-defined templates (the possible follow-up described above). +- 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). From 19baf6efc85432ea608b465f488437e145aea7e2 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:12:53 +0100 Subject: [PATCH 02/21] fix(android): accept decorations without a tint decorationFromJson called getString("tint"), which throws when the key is absent, so any decoration style without a tint was dropped even though tint is optional in the Dart model. Read it as optional. Co-Authored-By: Claude Sonnet 5.5 --- .../main/kotlin/dk/nota/flutterreadium/ReadiumExtensions.kt | 3 ++- .../changelog.d/+android-decoration-without-tint.fixed.md | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 flutter_readium/changelog.d/+android-decoration-without-tint.fixed.md 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 472d2fed..2dabfe61 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 @@ -103,7 +103,8 @@ fun decorationFromJson(jsonString: String): Decoration? = decorationStyleFromMap( mapOf( "style" to styleJson.getString("style"), - "tint" to styleJson.getString("tint"), + // `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), ), ) ?: throw Exception("Failed to deserialize decoration style") 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 00000000..bf27509a --- /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. From cf64e0066e506aa9991fb3ae8f50ac633cd25f94 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:16:27 +0100 Subject: [PATCH 03/21] feat(platform_interface): add marginMarker decoration style Add DecorationStyle.marginMarker with MarginMarker (label or built-in icon, logical side), MarginMarkerIcon and MarginSide, plus an optional ReaderDecorationStyle.marker. fromString maps the new wire value instead of falling back to highlight, and copyWith uses the shared unset sentinel. FlutterReadium.applyDecorations asserts in debug that marginMarker decorations carry a marker. Native sides skip such decorations. Co-Authored-By: Claude Sonnet 5.5 --- flutter_readium/lib/flutter_readium.dart | 10 ++- .../lib/src/reader/reader_decoration.dart | 69 +++++++++++++-- .../test/models_test.dart | 83 +++++++++++++++++++ 3 files changed, 152 insertions(+), 10 deletions(-) diff --git a/flutter_readium/lib/flutter_readium.dart b/flutter_readium/lib/flutter_readium.dart index 588177f0..16d43f0a 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]; native 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_platform_interface/lib/src/reader/reader_decoration.dart b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart index 1f7c00f8..81872868 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,40 @@ class ReaderDecoration implements JSONable { ); } +/// Built-in icons for [MarginMarker.icon]. Icons are a closed set so that Dart never supplies markup. +enum MarginMarkerIcon { bookmark } + +/// 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 } + +/// 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}) : icon = null; + + const MarginMarker.icon(MarginMarkerIcon this.icon, {this.side = MarginSide.start}) : label = null; + + const MarginMarker._({this.label, this.icon, this.side = MarginSide.start}); + + 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, + ); + + final String? label; + final MarginMarkerIcon? icon; + final MarginSide side; + + @override + Map toJson() => { + if (label != null) 'label': label, + if (icon != null) 'icon': icon!.name, + 'side': side.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 +115,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, 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/test/models_test.dart b/flutter_readium_platform_interface/test/models_test.dart index 9d3be9ad..1fdeb465 100644 --- a/flutter_readium_platform_interface/test/models_test.dart +++ b/flutter_readium_platform_interface/test/models_test.dart @@ -1088,6 +1088,89 @@ 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('DecorationStyle.fromString maps the wire value', () { + expect( + DecorationStyle.fromString('marginMarker'), + DecorationStyle.marginMarker, + ); + expect(DecorationStyle.marginMarker.name, 'marginMarker'); + }); + + 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('icon marker round-trips and defaults to the start side', () { + final decoration = ReaderDecoration( + id: 'bm', + locator: locator, + style: const ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.icon(MarginMarkerIcon.bookmark), + ), + ); + expect(decoration.style.toJson()['marker'], { + 'icon': 'bookmark', + 'side': 'start', + }); + final restored = roundTrip(decoration); + expect(restored.style.marker?.icon, MarginMarkerIcon.bookmark); + expect(restored.style.marker?.label, isNull); + expect(restored.style.marker?.side, MarginSide.start); + }); + + test('other styles omit the marker key', () { + expect( + const ReaderDecorationStyle(style: DecorationStyle.highlight).toJson().containsKey('marker'), + isFalse, + ); + }); + + test('tint is sent as a CSS colour', () { + final style = ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + tint: const Color(0xFF2E7D32), + marker: const MarginMarker.icon(MarginMarkerIcon.bookmark), + ); + expect(style.toJson()['tint'], isA()); + }); + + 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 // --------------------------------------------------------------------------- From 3fc63d2cc1f68e98d3ec51b0ec8f20ec426c185c Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:20:22 +0100 Subject: [PATCH 04/21] feat(ios): render marginMarker decorations Register an HTML decoration template for the marginMarker style. It floats a label or built-in bookmark icon into the page margin using inline !important styles, so Readium CSS theme rules cannot hide it, and marks the span data-activable so text taps still reach the decoration underneath. Decoration.Style.init(fromMap:) builds a MarginMarkerConfig from the marker map and throws for a marker without a label or known icon. applyDecorations now skips a decoration that fails to parse instead of dropping the whole group, and setDecorationStyle no longer crashes (try!) on a style it cannot parse. Co-Authored-By: Claude Sonnet 5.5 --- .../FlutterReadiumPlugin.swift | 4 +- .../reader/EPUBReaderView+Decorations.swift | 61 ++++++++++++++++++- .../reader/EPUBReaderView+MethodChannel.swift | 13 ++-- .../reader/EPUBReaderView.swift | 1 + .../utils/ReadiumExtensions.swift | 21 ++++++- 5 files changed, 90 insertions(+), 10 deletions(-) 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 4809a202..631c5c87 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 { try? Decoration.Style(fromMap: $0) } + ttsRangeDecorationStyle = (args[1] as? [String: Any]).flatMap { try? Decoration.Style(fromMap: $0) } Task { @MainActor in self.timebasedNavigator?.decorationsUpdated() } 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 8548cfbb..a52faf16 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,26 @@ 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". +struct MarginMarkerConfig: Hashable { + var label: String? + var icon: String? + var side: String + var tint: UIColor? + + /// Icon names the template can render. Keep in sync with `MarginMarkerIcon` on the Dart side. + static let knownIcons: Set = ["bookmark"] +} /// 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 +111,45 @@ extension EPUBReaderView { } ) } + + /// Margin marker: a small label or icon floated into the page margin, level with the + /// first line of the range. + /// + /// `.bounds` + `.page` makes the row span the page, so the span can float into either + /// margin. The styles are inline and `!important` because Readium CSS theme rules force + /// backgrounds to transparent and colours to inherit, and they beat class rules. + /// `data-activable` limits the tap area to the span, so taps on the text still reach + /// the highlight underneath. Keep the markup identical to the Android and web templates. + 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 + if let label = config.label { + content = Self.escapeHtmlAttr(label) + } else if config.icon == "bookmark" { + content = "" + } else { + return "
" + } + let physical = config.side == "end" ? "right" : "left" + let logical = config.side == "end" ? "inline-end" : "inline-start" + var css = "float: \(physical) !important; float: \(logical) !important;" + css += " margin: 0 2px !important; padding: 0 4px !important;" + css += " font-size: 0.75em !important; line-height: 1.4 !important;" + css += " border: 1px solid currentColor !important; border-radius: 3px !important;" + css += " background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;" + css += " opacity: 0.85 !important;" + if let tint = config.tint { + css += " color: \(tint.cssValue()) !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 0bb96ed5..ff13b973 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.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView.swift index 3bd4d8d4..cd54019a 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 f1297ef1..864556c1 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" } (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,24 @@ 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.knownIcons.contains($0) ? $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" + self.init( + id: .marginMarker, + config: MarginMarkerConfig(label: label, icon: icon, side: side, tint: tintColor?.uiColor) + ) + return + } + try self.init(withStyle: styleStr, tintColor: tintColor, isActive: isActive) } } From b6d6ff474c59feb672cc4af2ad5a935ba4d252dd Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:21:04 +0100 Subject: [PATCH 05/21] feat(android): render marginMarker decorations Add MarginMarkerStyle and an HTML decoration template that floats a label or built-in bookmark icon into the page margin. It uses inline !important styles, so Readium CSS theme rules cannot hide it, and marks the span data-activable so text taps still reach the decoration underneath. decorationFromJson now passes the nested marker object on as a Map, so decorationStyleFromMap sees the same shape on the applyDecorations and the TTS setDecorationStyle paths. A marker without a label or known icon is logged and the decoration skipped. escAttr moves out of the spotlight template so both templates share it. Co-Authored-By: Claude Sonnet 5.5 --- .../nota/flutterreadium/MarginMarkerStyle.kt | 25 ++++++ .../nota/flutterreadium/ReadiumExtensions.kt | 35 ++++++++- .../fragments/EpubReaderFragment.kt | 76 +++++++++++++++++-- 3 files changed, 127 insertions(+), 9 deletions(-) create mode 100644 flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt 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 00000000..252e2d30 --- /dev/null +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt @@ -0,0 +1,25 @@ +package dk.nota.flutterreadium + +import android.os.Parcelable +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). + * A transparent [tint] means no tint was set. + */ +@Parcelize +data class MarginMarkerStyle( + val label: String?, + val icon: String?, + val side: String, + @ColorInt override val tint: Int, +) : Decoration.Style, + Decoration.Style.Tinted { + companion object { + /** Icon names the template can render. Keep in sync with `MarginMarkerIcon` on the Dart side. */ + val KNOWN_ICONS = setOf("bookmark") + } +} 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 2dabfe61..994a1c88 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,33 @@ 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.KNOWN_ICONS } + 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" + MarginMarkerStyle(label, icon, side, tint) + } + + else -> { + Decoration.Style.Highlight(tint, isActive) + } // "highlight" + unknown } return style } catch (ex: Exception) { 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 dafe9671..c8154c57 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,73 @@ 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: a small label or icon floated into the page margin, level with the + * first line of the range. + * + * BOUNDS + PAGE makes the row span the page, so the span can float into either margin. + * The styles are inline and `!important` because Readium CSS theme rules force + * backgrounds to transparent and colours to inherit, and they beat class rules. + * `data-activable` limits the tap area to the span, so taps on the text still reach + * the highlight underneath. Keep the markup identical to the iOS and web templates. + */ + 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 == "bookmark" -> { + """""" + } + + else -> { + null + } + } + if (style == null || content == null) { + "
" + } else { + val physical = if (style.side == "end") "right" else "left" + val logical = if (style.side == "end") "inline-end" else "inline-start" + 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;" + } + val css = + "float: $physical !important; float: $logical !important;" + + " margin: 0 2px !important; padding: 0 4px !important;" + + " font-size: 0.75em !important; line-height: 1.4 !important;" + + " border: 1px solid currentColor !important; border-radius: 3px !important;" + + " background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;" + + " opacity: 0.85 !important;" + + color + """
$content
""" + } + }, + ) } } From 44ec57c1a612fd6e2df4c2d048b605f3482c4bea Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:22:51 +0100 Subject: [PATCH 06/21] feat(web): render marginMarker decorations Render marginMarker decorations as a bounds/page template in the decoration's own group, with the same inline !important markup as the iOS and Android templates. A marker without a label or known icon is logged and skipped. The marker payload and tint go into the decoration's extras, because ts-toolkit ignores a template's element when diffing and a changed label, icon, side or tint would otherwise never re-render. Co-Authored-By: Claude Sonnet 5.5 --- .../__tests__/DecorationController.test.ts | 110 ++++++++++++++++++ .../src/decorations/DecorationController.ts | 80 ++++++++++++- 2 files changed, 188 insertions(+), 2 deletions(-) diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index 0ae7a3d5..39606ddc 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -129,6 +129,116 @@ 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 } }); + + 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("background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !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" } })]) + ); + + 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, + "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" }, tint: "#ff0000ff" }); + expect(second.extras).toEqual({ marker: { label: "1", side: "start" }, 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: "star" } }), + marker("ok", label("7")), + ]) + ); + + expect(appliedTo(nav, "page-list").map((d) => d.id)).toEqual(["ok"]); + expect(warn).toHaveBeenCalledTimes(3); + 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/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index 9d874231..4ff8380b 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,58 @@ 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; +} + +/** Icon markup by `MarginMarkerIcon` name. Keep in sync with the iOS and Android templates. */ +const MARGIN_MARKER_ICONS: Record = { + bookmark: + '', +}; + +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. + * + * The styles are inline and `!important` because the decoration renders in a shadow root where + * document stylesheets don't apply, and Readium CSS theme rules beat class rules. `data-activable` + * limits the tap area to the span, so taps on the text still reach the highlight underneath. + * Keep the markup identical to the iOS and Android templates. + */ +function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undefined): string | null { + const content = marker?.label + ? escapeHtml(marker.label) + : marker?.icon !== undefined + ? MARGIN_MARKER_ICONS[marker.icon] + : undefined; + if (!content) return null; + + const end = marker?.side === "end"; + let css = + `float: ${end ? "right" : "left"} !important; float: ${end ? "inline-end" : "inline-start"} !important;` + + " margin: 0 2px !important; padding: 0 4px !important;" + + " font-size: 0.75em !important; line-height: 1.4 !important;" + + " border: 1px solid currentColor !important; border-radius: 3px !important;" + + " background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;" + + " opacity: 0.85 !important;"; + if (tint) css += ` color: ${escapeHtml(tint)} !important;`; + return `
${content}
`; +} export interface ApplyDecorationsOptions { /** @@ -68,7 +121,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 +132,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, From 71d587399dff146230fd7a230fcb01c6078a1397 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:23:59 +0100 Subject: [PATCH 07/21] feat(example): add page-number and bookmark margin marker recipes Add a "Page numbers in margin" toggle (page_numbers_toggle) to the player app bar, shown when the publication has a page list. It applies a page-list group with one end-side label marker per entry. Each user highlight now also gets a bookmark marker in a highlight-markers group, on the same locator. Taps on the highlighted text still reach the highlight decoration. Co-Authored-By: Claude Sonnet 5.5 --- .../example/lib/pages/player.page.dart | 46 ++++++++++++++++++- .../example/lib/state/highlight.dart | 16 +++++++ .../example/lib/state/publication_bloc.dart | 1 + 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/flutter_readium/example/lib/pages/player.page.dart b/flutter_readium/example/lib/pages/player.page.dart index 93ff5a9e..4c85d319 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), + ), + ), + ); + } + } + 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 a2e05185..3e748779 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,19 @@ class Highlight { Color? get tint => decoration.style.tint; + /// A bookmark icon in the margin, level with the first line of the highlight. + /// + /// Green, as the marker colour is independent of the highlight's own tint. + ReaderDecoration get marker => ReaderDecoration( + id: '${id}_marker', + locator: decoration.locator, + style: const ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + tint: Color(0xFF2E7D32), + 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 88672025..6456801e 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() { From fb24e1b49e56b6cc0f277b60eba2a74b0fd3be49 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:24:37 +0100 Subject: [PATCH 08/21] docs: add margin markers guide Add a guide with the page-number and bookmarked-highlight recipes, and notes on side, tint, taps and margin width. Link it from the decorations API reference (marginMarker and MarginMarker rows only) and the highlights guide. Add changelog fragments for both packages. Co-Authored-By: Claude Sonnet 5.5 --- docs/api-reference/decorations.md | 13 ++- docs/guides/highlights-annotations.md | 4 + docs/guides/margin-markers.md | 103 ++++++++++++++++++ .../+margin-marker-decorations.added.md | 3 + .../+margin-marker-decorations.added.md | 3 + 5 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 docs/guides/margin-markers.md create mode 100644 flutter_readium/changelog.d/+margin-marker-decorations.added.md create mode 100644 flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md diff --git a/docs/api-reference/decorations.md b/docs/api-reference/decorations.md index 3b00f16e..414a755b 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,16 @@ 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})` | Text label, such as a page number | +| `MarginMarker.icon(MarginMarkerIcon, {side})` | Built-in icon (`MarginMarkerIcon.bookmark`) | + +`side` is `MarginSide.start` (default) or `MarginSide.end`, and flips in right-to-left text. ## Applying decorations diff --git a/docs/guides/highlights-annotations.md b/docs/guides/highlights-annotations.md index 037201e4..644e98e9 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 00000000..b2f06be3 --- /dev/null +++ b/docs/guides/margin-markers.md @@ -0,0 +1,103 @@ +# 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) +const MarginMarker.icon(MarginMarkerIcon.bookmark) // side defaults to MarginSide.start +``` + +| Field | Description | +|-------|-------------| +| `label` | Short text, such as a page number. Escaped before rendering | +| `icon` | One of the built-in icons (`MarginMarkerIcon.bookmark`). The set is closed: the plugin never renders app-supplied markup | +| `side` | `MarginSide.start` or `MarginSide.end`. Logical, so `start` is the left margin in left-to-right text and the right margin in right-to-left text | + +`tint` colours the marker's text, border and icon. Without a tint the marker uses the publication's text colour. `isActive` is ignored. The marker background follows the reader theme. + +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) + if (link.title != null && publication.locatorFromLink(link) != null) + ReaderDecoration( + id: 'page_$index', + locator: publication.locatorFromLink(link)!, + style: ReaderDecorationStyle( + style: DecorationStyle.marginMarker, + marker: MarginMarker.label(link.title!, side: MarginSide.end), + ), + ), + ]; + 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. + +## Layout notes + +- **Margin width.** Markers sit in the page margin. Icons need a little more room than page numbers, and with small `pageMargins` a marker can overlap the text. The plugin does not compensate for this. +- **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/flutter_readium/changelog.d/+margin-marker-decorations.added.md b/flutter_readium/changelog.d/+margin-marker-decorations.added.md new file mode 100644 index 00000000..c4010b98 --- /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 built-in bookmark icon in the page margin, level with the first line of a locator, on iOS, Android and web. +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/changelog.d/+margin-marker-decorations.added.md b/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md new file mode 100644 index 00000000..c4010b98 --- /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 built-in bookmark icon in the page margin, level with the first line of a locator, on iOS, Android and web. +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). From c6121ee33ceb02aae64df565c0b9c2f3c9e89875 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:41:08 +0100 Subject: [PATCH 09/21] docs(flutter_readium): note that marginMarker needs a marker Co-Authored-By: Claude Opus 5.5 --- flutter_readium/lib/flutter_readium.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flutter_readium/lib/flutter_readium.dart b/flutter_readium/lib/flutter_readium.dart index 16d43f0a..f6a1a130 100644 --- a/flutter_readium/lib/flutter_readium.dart +++ b/flutter_readium/lib/flutter_readium.dart @@ -166,7 +166,7 @@ class FlutterReadium { /// /// 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]; native platforms skip one without. + /// A [DecorationStyle.marginMarker] decoration needs a [ReaderDecorationStyle.marker]; all platforms skip one without. Future applyDecorations( String id, List decorations, From e6e046ba8fcc9fd37363f26b112747220ba77b39 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:54:21 +0100 Subject: [PATCH 10/21] fix(platform_interface): parse CSS tint in ReaderDecorationStyle.fromJson toJson sends tint as a CSS colour string, but fromJson cast it to int, so round-tripping any tinted style threw. Also drop three marker tests that only re-checked enum names and collection-ifs. Co-Authored-By: Claude Opus 5.5 --- .../{todo => }/margin-marker-decorations.md | 0 .../+decoration-style-fromjson-tint.fixed.md | 2 ++ .../lib/src/reader/reader_decoration.dart | 2 +- .../test/models_test.dart | 28 ++----------------- 4 files changed, 6 insertions(+), 26 deletions(-) rename docs/plans/{todo => }/margin-marker-decorations.md (100%) create mode 100644 flutter_readium_platform_interface/changelog.d/+decoration-style-fromjson-tint.fixed.md diff --git a/docs/plans/todo/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md similarity index 100% rename from docs/plans/todo/margin-marker-decorations.md rename to docs/plans/margin-marker-decorations.md 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 00000000..18199863 --- /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/lib/src/reader/reader_decoration.dart b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart index 81872868..43d87b8f 100644 --- a/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart +++ b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart @@ -130,7 +130,7 @@ class ReaderDecorationStyle implements JSONable { 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, ); diff --git a/flutter_readium_platform_interface/test/models_test.dart b/flutter_readium_platform_interface/test/models_test.dart index 1fdeb465..2b9f245d 100644 --- a/flutter_readium_platform_interface/test/models_test.dart +++ b/flutter_readium_platform_interface/test/models_test.dart @@ -1098,14 +1098,6 @@ void main() { json.decode(json.encode(decoration.toJson())) as Map, ); - test('DecorationStyle.fromString maps the wire value', () { - expect( - DecorationStyle.fromString('marginMarker'), - DecorationStyle.marginMarker, - ); - expect(DecorationStyle.marginMarker.name, 'marginMarker'); - }); - test('label marker round-trips through toJson/fromJson', () { final decoration = ReaderDecoration( id: 'p12', @@ -1122,12 +1114,13 @@ void main() { expect(restored.style.marker?.side, MarginSide.end); }); - test('icon marker round-trips and defaults to the start side', () { + 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), ), ); @@ -1139,22 +1132,7 @@ void main() { expect(restored.style.marker?.icon, MarginMarkerIcon.bookmark); expect(restored.style.marker?.label, isNull); expect(restored.style.marker?.side, MarginSide.start); - }); - - test('other styles omit the marker key', () { - expect( - const ReaderDecorationStyle(style: DecorationStyle.highlight).toJson().containsKey('marker'), - isFalse, - ); - }); - - test('tint is sent as a CSS colour', () { - final style = ReaderDecorationStyle( - style: DecorationStyle.marginMarker, - tint: const Color(0xFF2E7D32), - marker: const MarginMarker.icon(MarginMarkerIcon.bookmark), - ); - expect(style.toJson()['tint'], isA()); + expect(restored.style.tint, const Color(0xFF2E7D32)); }); test('copyWith keeps, replaces and clears the marker', () { From 8ec34e47537439a39c1710251d046f524fe888c8 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 16:54:24 +0100 Subject: [PATCH 11/21] refactor: apply review feedback on margin markers - Shorten the template doc comments to point at the plan. - Log unparsable TTS decoration styles on iOS instead of silently clearing them. - Remove an unused import in MarginMarkerStyle.kt. - Guide: bind locatorFromLink once and link to the API reference instead of repeating its field table. - Move the plan to docs/plans/ as implemented. Co-Authored-By: Claude Opus 5.5 --- docs/api-reference/decorations.md | 2 +- docs/guides/margin-markers.md | 32 +++++++++---------- docs/plans/README.md | 2 +- docs/plans/margin-marker-decorations.md | 6 ++-- .../nota/flutterreadium/MarginMarkerStyle.kt | 1 - .../fragments/EpubReaderFragment.kt | 10 ++---- .../FlutterReadiumPlugin.swift | 14 ++++++-- .../reader/EPUBReaderView+Decorations.swift | 10 ++---- .../src/decorations/DecorationController.ts | 8 ++--- 9 files changed, 40 insertions(+), 45 deletions(-) diff --git a/docs/api-reference/decorations.md b/docs/api-reference/decorations.md index 414a755b..fb80d431 100644 --- a/docs/api-reference/decorations.md +++ b/docs/api-reference/decorations.md @@ -44,7 +44,7 @@ ReaderDecoration( | `MarginMarker.label(String, {side})` | Text label, such as a page number | | `MarginMarker.icon(MarginMarkerIcon, {side})` | Built-in icon (`MarginMarkerIcon.bookmark`) | -`side` is `MarginSide.start` (default) or `MarginSide.end`, and flips in right-to-left text. +`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. ## Applying decorations diff --git a/docs/guides/margin-markers.md b/docs/guides/margin-markers.md index b2f06be3..3634f77a 100644 --- a/docs/guides/margin-markers.md +++ b/docs/guides/margin-markers.md @@ -13,11 +13,7 @@ const MarginMarker.label('12', side: MarginSide.end) const MarginMarker.icon(MarginMarkerIcon.bookmark) // side defaults to MarginSide.start ``` -| Field | Description | -|-------|-------------| -| `label` | Short text, such as a page number. Escaped before rendering | -| `icon` | One of the built-in icons (`MarginMarkerIcon.bookmark`). The set is closed: the plugin never renders app-supplied markup | -| `side` | `MarginSide.start` or `MarginSide.end`. Logical, so `start` is the left margin in left-to-right text and the right margin in right-to-left text | +The fields are described in the [API reference](../api-reference/decorations.md#marginmarker). `tint` colours the marker's text, border and icon. Without a tint the marker uses the publication's text colour. `isActive` is ignored. The marker background follows the reader theme. @@ -29,18 +25,22 @@ Print-equivalent EPUBs carry a `pageList` navigation document. Map each entry to ```dart Future showPageNumbers(Publication publication) { - final decorations = [ - for (final (index, link) in publication.pageList.indexed) - if (link.title != null && publication.locatorFromLink(link) != null) - ReaderDecoration( - id: 'page_$index', - locator: publication.locatorFromLink(link)!, - style: ReaderDecorationStyle( - style: DecorationStyle.marginMarker, - marker: MarginMarker.label(link.title!, side: MarginSide.end), - ), + 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), ), - ]; + ), + ); + } return FlutterReadium().applyDecorations('page-list', decorations); } diff --git a/docs/plans/README.md b/docs/plans/README.md index 18d04a53..62d8de7d 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -30,7 +30,6 @@ This directory holds implementation plans, parity audits, and retained reference *(Maintainability / L)* - **[todo/highlight-modes.md](todo/highlight-modes.md)** — `highlight`, `underline` and `spotlight` decoration styles exist; the `ruler` style does not. *(Feature / M)* -- **[todo/margin-marker-decorations.md](todo/margin-marker-decorations.md)** — a built-in `marginMarker` decoration style (text label or icon in the page margin) on iOS, Android and web, with page-number and bookmarked-highlight recipes. *(Feature / M)* ## Upstream plans (`upstream/`) @@ -48,6 +47,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 index 57d4a8a5..90638ce6 100644 --- a/docs/plans/margin-marker-decorations.md +++ b/docs/plans/margin-marker-decorations.md @@ -1,5 +1,7 @@ # 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 @@ -17,7 +19,7 @@ Both upstream toolkits do page numbers in their test apps with a custom decorati - 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.13.2, injectables 2.9.1) include all of this. +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 @@ -103,7 +105,7 @@ Design decisions: - `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.13.2 typings that `element` is a function at the navigator level (it is a string in injectables) and that `extras` is available. +- 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) 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 index 252e2d30..4342bb24 100644 --- a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt @@ -1,6 +1,5 @@ package dk.nota.flutterreadium -import android.os.Parcelable import androidx.annotation.ColorInt import kotlinx.parcelize.Parcelize import org.readium.r2.navigator.Decoration 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 c8154c57..d998a97c 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 @@ -1053,14 +1053,8 @@ class EpubReaderFragment : ) /** - * Margin marker: a small label or icon floated into the page margin, level with the - * first line of the range. - * - * BOUNDS + PAGE makes the row span the page, so the span can float into either margin. - * The styles are inline and `!important` because Readium CSS theme rules force - * backgrounds to transparent and colours to inherit, and they beat class rules. - * `data-activable` limits the tap area to the span, so taps on the text still reach - * the highlight underneath. Keep the markup identical to the iOS and web templates. + * Margin marker floated into the page margin. 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( 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 631c5c87..8c16a57d 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]).flatMap { try? Decoration.Style(fromMap: $0) } - ttsRangeDecorationStyle = (args[1] as? [String: Any]).flatMap { 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/reader/EPUBReaderView+Decorations.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift index a52faf16..2447d25c 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 @@ -112,14 +112,8 @@ extension EPUBReaderView { ) } - /// Margin marker: a small label or icon floated into the page margin, level with the - /// first line of the range. - /// - /// `.bounds` + `.page` makes the row span the page, so the span can float into either - /// margin. The styles are inline and `!important` because Readium CSS theme rules force - /// backgrounds to transparent and colours to inherit, and they beat class rules. - /// `data-activable` limits the tap area to the span, so taps on the text still reach - /// the highlight underneath. Keep the markup identical to the Android and web templates. + /// Margin marker floated into the page margin. 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, diff --git a/flutter_readium/web/src/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index 4ff8380b..d1c4607e 100644 --- a/flutter_readium/web/src/decorations/DecorationController.ts +++ b/flutter_readium/web/src/decorations/DecorationController.ts @@ -48,12 +48,8 @@ function escapeHtml(s: string): string { } /** - * Builds the margin marker element, or `null` when there is nothing to show. - * - * The styles are inline and `!important` because the decoration renders in a shadow root where - * document stylesheets don't apply, and Readium CSS theme rules beat class rules. `data-activable` - * limits the tap area to the span, so taps on the text still reach the highlight underneath. - * Keep the markup identical to the iOS and Android templates. + * Builds the margin marker element, or `null` when there is nothing to show. 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 From 5b42b0654cce9d5b8728a1db8ebc463b6d85e9b2 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 21:16:17 +0100 Subject: [PATCH 12/21] feat: add note and star margin marker icons MarginMarkerIcon gains note and star next to bookmark. Each platform now keeps one name -> SVG path map that both the parser and the template read, so a listed icon can no longer parse but render empty. On web the lookup uses a Map, so names like "constructor" no longer resolve through the prototype chain. Co-Authored-By: Claude Opus 5.5 --- docs/api-reference/decorations.md | 2 +- .../nota/flutterreadium/MarginMarkerStyle.kt | 9 +++++++-- .../nota/flutterreadium/ReadiumExtensions.kt | 2 +- .../fragments/EpubReaderFragment.kt | 4 ++-- .../+margin-marker-decorations.added.md | 2 +- .../reader/EPUBReaderView+Decorations.swift | 12 +++++++---- .../utils/ReadiumExtensions.swift | 2 +- .../__tests__/DecorationController.test.ts | 14 +++++++++++-- .../src/decorations/DecorationController.ts | 20 +++++++++++++------ .../+margin-marker-decorations.added.md | 2 +- .../lib/src/reader/reader_decoration.dart | 11 +++++++++- 11 files changed, 58 insertions(+), 22 deletions(-) diff --git a/docs/api-reference/decorations.md b/docs/api-reference/decorations.md index fb80d431..64353713 100644 --- a/docs/api-reference/decorations.md +++ b/docs/api-reference/decorations.md @@ -42,7 +42,7 @@ ReaderDecoration( | Constructor | Description | |-------------|-------------| | `MarginMarker.label(String, {side})` | Text label, such as a page number | -| `MarginMarker.icon(MarginMarkerIcon, {side})` | Built-in icon (`MarginMarkerIcon.bookmark`) | +| `MarginMarker.icon(MarginMarkerIcon, {side})` | 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. 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 index 4342bb24..19d1098b 100644 --- a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt @@ -18,7 +18,12 @@ data class MarginMarkerStyle( ) : Decoration.Style, Decoration.Style.Tinted { companion object { - /** Icon names the template can render. Keep in sync with `MarginMarkerIcon` on the Dart side. */ - val KNOWN_ICONS = setOf("bookmark") + /** 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 994a1c88..75ab7d71 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 @@ -163,7 +163,7 @@ fun decorationStyleFromMap(decoMap: Map<*, *>?): Decoration.Style? { "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.KNOWN_ICONS } + 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( 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 d998a97c..f2f9a5ad 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 @@ -1072,8 +1072,8 @@ class EpubReaderFragment : style.label.escAttr() } - style.icon == "bookmark" -> { - """""" + style.icon in MarginMarkerStyle.ICON_PATHS -> { + """""" } else -> { diff --git a/flutter_readium/changelog.d/+margin-marker-decorations.added.md b/flutter_readium/changelog.d/+margin-marker-decorations.added.md index c4010b98..4cf4434d 100644 --- a/flutter_readium/changelog.d/+margin-marker-decorations.added.md +++ b/flutter_readium/changelog.d/+margin-marker-decorations.added.md @@ -1,3 +1,3 @@ **Margin marker decorations.** -`DecorationStyle.marginMarker` shows a text label or built-in bookmark icon in the page margin, level with the first line of a locator, on iOS, Android and web. +`DecorationStyle.marginMarker` shows a text label or a built-in icon (bookmark, note or star) in the page margin, level with the first line of a locator, on iOS, Android and web. 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/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Decorations.swift index 2447d25c..7d0c6c5f 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 @@ -14,8 +14,12 @@ struct MarginMarkerConfig: Hashable { var side: String var tint: UIColor? - /// Icon names the template can render. Keep in sync with `MarginMarkerIcon` on the Dart side. - static let knownIcons: Set = ["bookmark"] + /// 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 @@ -126,8 +130,8 @@ extension EPUBReaderView { let content: String if let label = config.label { content = Self.escapeHtmlAttr(label) - } else if config.icon == "bookmark" { - content = "" + } else if let path = config.icon.flatMap({ MarginMarkerConfig.iconPaths[$0] }) { + content = "" } else { return "
" } 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 864556c1..f24a7dda 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 @@ -509,7 +509,7 @@ extension Decoration.Style { // 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.knownIcons.contains($0) ? $0 : nil } + 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) diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index 39606ddc..63c3abc5 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -177,6 +177,15 @@ describe("DecorationController", () => { expect(html).toContain("color: #2e7d32ff !important;"); }); + it.each(["bookmark", "note", "star"])("renders the built-in %s icon", (icon) => { + 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(); @@ -209,13 +218,14 @@ describe("DecorationController", () => { JSON.stringify([ marker("none", {}), marker("empty", { marker: { side: "end" } }), - marker("unknown-icon", { marker: { icon: "star" } }), + 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(3); + expect(warn).toHaveBeenCalledTimes(4); warn.mockRestore(); }); diff --git a/flutter_readium/web/src/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index d1c4607e..a001f36f 100644 --- a/flutter_readium/web/src/decorations/DecorationController.ts +++ b/flutter_readium/web/src/decorations/DecorationController.ts @@ -33,11 +33,19 @@ interface MarginMarker { side?: string; } -/** Icon markup by `MarginMarkerIcon` name. Keep in sync with the iOS and Android templates. */ -const MARGIN_MARKER_ICONS: Record = { - bookmark: - '', -}; +/** 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 @@ -55,7 +63,7 @@ function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undef const content = marker?.label ? escapeHtml(marker.label) : marker?.icon !== undefined - ? MARGIN_MARKER_ICONS[marker.icon] + ? marginMarkerIconSvg(marker.icon) : undefined; if (!content) return null; 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 index c4010b98..4cf4434d 100644 --- a/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md +++ b/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md @@ -1,3 +1,3 @@ **Margin marker decorations.** -`DecorationStyle.marginMarker` shows a text label or built-in bookmark icon in the page margin, level with the first line of a locator, on iOS, Android and web. +`DecorationStyle.marginMarker` shows a text label or a built-in icon (bookmark, note or star) in the page margin, level with the first line of a locator, on iOS, Android and web. 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 43d87b8f..33eb8c84 100644 --- a/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart +++ b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart @@ -65,7 +65,16 @@ class ReaderDecoration implements JSONable { } /// Built-in icons for [MarginMarker.icon]. Icons are a closed set so that Dart never supplies markup. -enum MarginMarkerIcon { bookmark } +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 } From 1cd4ff6b70a81a657d425131c0d8728725770e30 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 21:16:21 +0100 Subject: [PATCH 13/21] docs(ios): add changelog entry for skipping invalid decorations Co-Authored-By: Claude Opus 5.5 --- .../changelog.d/+ios-apply-decorations-skip-invalid.fixed.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 flutter_readium/changelog.d/+ios-apply-decorations-skip-invalid.fixed.md 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 00000000..275e06f5 --- /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. From 38909b0ba63f59e99686450bf978eab8b98caa0a Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 21:16:22 +0100 Subject: [PATCH 14/21] docs(plans): park a plan for app-supplied margin marker icons Co-Authored-By: Claude Opus 5.5 --- docs/plans/README.md | 1 + docs/plans/margin-marker-decorations.md | 2 +- docs/plans/todo/margin-marker-custom-icons.md | 48 +++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 docs/plans/todo/margin-marker-custom-icons.md diff --git a/docs/plans/README.md b/docs/plans/README.md index 62d8de7d..4f1124f5 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)* diff --git a/docs/plans/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md index 90638ce6..70fa924a 100644 --- a/docs/plans/margin-marker-decorations.md +++ b/docs/plans/margin-marker-decorations.md @@ -139,7 +139,7 @@ Design decisions: ## Out of scope -- A Dart-side API for app-defined templates (the possible follow-up described above). +- 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 00000000..ea54cc0c --- /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. From 24677c7c5eade50ef24a5ea630692a170fddc650 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 22:23:14 +0100 Subject: [PATCH 15/21] feat: draw margin markers without a box The bordered box made icons look like tiny checkboxes, and its padding pushed markers into the text on narrow phone margins. Icons now render at about one body em in the full marker colour; labels stay small and are muted like printed page numbers. The example's bookmark drops its green tint, so it takes the text colour and follows the theme. Co-Authored-By: Claude Opus 5.5 --- docs/guides/margin-markers.md | 2 +- docs/plans/margin-marker-decorations.md | 4 ++-- docs/plans/todo/margin-marker-custom-icons.md | 2 +- .../flutterreadium/fragments/EpubReaderFragment.kt | 11 +++++------ flutter_readium/example/lib/state/highlight.dart | 3 +-- .../reader/EPUBReaderView+Decorations.swift | 12 ++++++------ .../web/src/__tests__/DecorationController.test.ts | 5 +++-- .../web/src/decorations/DecorationController.ts | 10 ++++------ 8 files changed, 23 insertions(+), 26 deletions(-) diff --git a/docs/guides/margin-markers.md b/docs/guides/margin-markers.md index 3634f77a..dd062e81 100644 --- a/docs/guides/margin-markers.md +++ b/docs/guides/margin-markers.md @@ -15,7 +15,7 @@ const MarginMarker.icon(MarginMarkerIcon.bookmark) // side defaults to MarginSid The fields are described in the [API reference](../api-reference/decorations.md#marginmarker). -`tint` colours the marker's text, border and icon. Without a tint the marker uses the publication's text colour. `isActive` is ignored. The marker background follows the reader theme. +`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. A `marginMarker` decoration without a label or icon is skipped and logged. In debug builds, `applyDecorations` asserts that the marker is present. diff --git a/docs/plans/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md index 70fa924a..7d30be40 100644 --- a/docs/plans/margin-marker-decorations.md +++ b/docs/plans/margin-marker-decorations.md @@ -65,7 +65,7 @@ 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** (text, border and icon fill through `color`). Without a tint, `color` is omitted and the marker uses the text colour. `isActive` is ignored. +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`). @@ -73,7 +73,7 @@ Design decisions: ```html
{escaped label | built-in SVG}
``` - Inline styles on the span, each with `!important`: the two `float` declarations from decision 5, a small margin and padding, `font-size: 0.75em`, `line-height: 1.4`, `border: 1px solid currentColor`, `border-radius: 3px`, `background-color: var(--USER__backgroundColor, var(--RS__backgroundColor))`, `opacity: 0.85`, and `color: {tint}` when a tint is set. `--RS__backgroundColor` alone is always white, so it is only the fallback. The SVG carries `width="1em" height="1em"`. 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. + Inline styles on the span, each with `!important`: the two `float` declarations from decision 5, a small margin, `font-size: 0.75em`, `line-height: 1.4`, `opacity: 0.6` 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. diff --git a/docs/plans/todo/margin-marker-custom-icons.md b/docs/plans/todo/margin-marker-custom-icons.md index ea54cc0c..76e348b9 100644 --- a/docs/plans/todo/margin-marker-custom-icons.md +++ b/docs/plans/todo/margin-marker-custom-icons.md @@ -13,7 +13,7 @@ - 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. +Each template wraps the path in the same element: ``. Today a new icon needs a plugin release. ## Proposal: app-supplied SVG path 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 f2f9a5ad..9737d988 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 @@ -1073,7 +1073,7 @@ class EpubReaderFragment : } style.icon in MarginMarkerStyle.ICON_PATHS -> { - """""" + """""" } else -> { @@ -1094,13 +1094,12 @@ class EpubReaderFragment : 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.6 !important;" else "" val css = "float: $physical !important; float: $logical !important;" + - " margin: 0 2px !important; padding: 0 4px !important;" + - " font-size: 0.75em !important; line-height: 1.4 !important;" + - " border: 1px solid currentColor !important; border-radius: 3px !important;" + - " background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;" + - " opacity: 0.85 !important;" + + " margin: 0 2px !important; font-size: 0.75em !important; line-height: 1.4 !important;" + + opacity + color """
$content
""" } diff --git a/flutter_readium/example/lib/state/highlight.dart b/flutter_readium/example/lib/state/highlight.dart index 3e748779..47c524f2 100644 --- a/flutter_readium/example/lib/state/highlight.dart +++ b/flutter_readium/example/lib/state/highlight.dart @@ -25,13 +25,12 @@ class Highlight { /// A bookmark icon in the margin, level with the first line of the highlight. /// - /// Green, as the marker colour is independent of the highlight's own tint. + /// 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, - tint: Color(0xFF2E7D32), marker: MarginMarker.icon(MarginMarkerIcon.bookmark), ), ); 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 7d0c6c5f..7400b7c2 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 @@ -128,21 +128,21 @@ extension EPUBReaderView { 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.6 !important;" } else if let path = config.icon.flatMap({ MarginMarkerConfig.iconPaths[$0] }) { - content = "" + content = "" } else { return "
" } let physical = config.side == "end" ? "right" : "left" let logical = config.side == "end" ? "inline-end" : "inline-start" var css = "float: \(physical) !important; float: \(logical) !important;" - css += " margin: 0 2px !important; padding: 0 4px !important;" - css += " font-size: 0.75em !important; line-height: 1.4 !important;" - css += " border: 1px solid currentColor !important; border-radius: 3px !important;" - css += " background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;" - css += " opacity: 0.85 !important;" + css += " margin: 0 2px !important; font-size: 0.75em !important; line-height: 1.4 !important;" + css += opacity if let tint = config.tint { css += " color: \(tint.cssValue()) !important;" } diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index 63c3abc5..6d82ceed 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -146,7 +146,7 @@ describe("DecorationController", () => { expect(html).toContain('data-activable="1"'); expect(html).toContain(">12"); expect(html).toContain("float: right !important; float: inline-end !important;"); - expect(html).toContain("background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;"); + expect(html).toContain("opacity: 0.6 !important;"); expect(html).not.toContain(" color:"); expect(appliedTo(nav, "page-list__spotlight")).toEqual([]); }); @@ -172,7 +172,8 @@ describe("DecorationController", () => { const [deco] = appliedTo(nav, "highlight-markers"); const html: string = deco.style.element(deco); expect(html).toContain("`; + : ``; } function escapeHtml(s: string): string { @@ -70,11 +70,9 @@ function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undef const end = marker?.side === "end"; let css = `float: ${end ? "right" : "left"} !important; float: ${end ? "inline-end" : "inline-start"} !important;` + - " margin: 0 2px !important; padding: 0 4px !important;" + - " font-size: 0.75em !important; line-height: 1.4 !important;" + - " border: 1px solid currentColor !important; border-radius: 3px !important;" + - " background-color: var(--USER__backgroundColor, var(--RS__backgroundColor)) !important;" + - " opacity: 0.85 !important;"; + " margin: 0 2px !important; 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.6 !important;"; if (tint) css += ` color: ${escapeHtml(tint)} !important;`; return `
${content}
`; } From 4ce2cb5327e72690d8501d457954920e4d8c132c Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Thu, 19 Nov 2026 23:44:24 +0100 Subject: [PATCH 16/21] feat: keep margin markers off the screen edge Markers sat 2px from the screen edge, which looked cramped on tablets. The edge margin is now 1.5% of the page width with a 4px floor, so phones, whose margins are narrow, don't get pushed into the text. Labels go from 0.6 to 0.8 opacity, so page numbers read more easily. Co-Authored-By: Claude Opus 5.5 --- docs/plans/margin-marker-decorations.md | 2 +- .../dk/nota/flutterreadium/fragments/EpubReaderFragment.kt | 4 ++-- .../flutter_readium/reader/EPUBReaderView+Decorations.swift | 4 ++-- .../web/src/__tests__/DecorationController.test.ts | 2 +- flutter_readium/web/src/decorations/DecorationController.ts | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/plans/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md index 7d30be40..24b744cf 100644 --- a/docs/plans/margin-marker-decorations.md +++ b/docs/plans/margin-marker-decorations.md @@ -73,7 +73,7 @@ Design decisions: ```html
{escaped label | built-in SVG}
``` - Inline styles on the span, each with `!important`: the two `float` declarations from decision 5, a small margin, `font-size: 0.75em`, `line-height: 1.4`, `opacity: 0.6` 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. + 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. 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 9737d988..3fcfc709 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 @@ -1095,10 +1095,10 @@ class EpubReaderFragment : " 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.6 !important;" else "" + val opacity = if (style.label != null) " opacity: 0.8 !important;" else "" val css = "float: $physical !important; float: $logical !important;" + - " margin: 0 2px !important; font-size: 0.75em !important; line-height: 1.4 !important;" + + " margin: 0 max(4px, 1.5%) !important; font-size: 0.75em !important; line-height: 1.4 !important;" + opacity + color """
$content
""" 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 7400b7c2..46c09e7f 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 @@ -132,7 +132,7 @@ extension EPUBReaderView { var opacity = "" if let label = config.label { content = Self.escapeHtmlAttr(label) - opacity = " opacity: 0.6 !important;" + opacity = " opacity: 0.8 !important;" } else if let path = config.icon.flatMap({ MarginMarkerConfig.iconPaths[$0] }) { content = "" } else { @@ -141,7 +141,7 @@ extension EPUBReaderView { let physical = config.side == "end" ? "right" : "left" let logical = config.side == "end" ? "inline-end" : "inline-start" var css = "float: \(physical) !important; float: \(logical) !important;" - css += " margin: 0 2px !important; font-size: 0.75em !important; line-height: 1.4 !important;" + css += " margin: 0 max(4px, 1.5%) !important; font-size: 0.75em !important; line-height: 1.4 !important;" css += opacity if let tint = config.tint { css += " color: \(tint.cssValue()) !important;" diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index 6d82ceed..bbb73618 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -146,7 +146,7 @@ describe("DecorationController", () => { 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.6 !important;"); + expect(html).toContain("opacity: 0.8 !important;"); expect(html).not.toContain(" color:"); expect(appliedTo(nav, "page-list__spotlight")).toEqual([]); }); diff --git a/flutter_readium/web/src/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index 0b716959..7eba1543 100644 --- a/flutter_readium/web/src/decorations/DecorationController.ts +++ b/flutter_readium/web/src/decorations/DecorationController.ts @@ -70,9 +70,9 @@ function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undef const end = marker?.side === "end"; let css = `float: ${end ? "right" : "left"} !important; float: ${end ? "inline-end" : "inline-start"} !important;` + - " margin: 0 2px !important; font-size: 0.75em !important; line-height: 1.4 !important;"; + " margin: 0 max(4px, 1.5%) !important; 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.6 !important;"; + if (marker?.label) css += " opacity: 0.8 !important;"; if (tint) css += ` color: ${escapeHtml(tint)} !important;`; return `
${content}
`; } From 72e136b1352359f8857769e6e943778e1e365150 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Mon, 23 Nov 2026 23:56:13 +0100 Subject: [PATCH 17/21] feat: anchor margin markers to the text column Add MarginMarker.anchor. The default, page, keeps the marker near the page (or column) edge. The new text anchor keeps it a small gap from the text column however wide the margin is, which reads better on wide screens. flutterReadiumTools.js measures the body's margin, border and padding and publishes them as --flutter-readium-text-inset-start/end. The iOS, Android and web templates size a flex cell to that inset and push the marker against its text side, so a too-narrow margin makes the marker overflow toward the text, never off the page. The example app uses the text anchor for bookmarks and keeps page numbers on the page anchor. Co-Authored-By: Claude Opus 5.5 --- docs/api-reference/decorations.md | 6 ++-- docs/guides/margin-markers.md | 14 ++++++-- docs/plans/margin-marker-decorations.md | 10 ++++++ .../nota/flutterreadium/MarginMarkerStyle.kt | 2 ++ .../nota/flutterreadium/ReadiumExtensions.kt | 3 +- .../fragments/EpubReaderFragment.kt | 33 +++++++++++++------ .../src/FlutterReadiumTools.ts | 26 +++++++++++++++ .../+margin-marker-anchor.added.md | 3 ++ .../example/lib/state/highlight.dart | 4 +-- .../reader/EPUBReaderView+Decorations.swift | 27 ++++++++++----- .../utils/ReadiumExtensions.swift | 5 +-- .../__tests__/DecorationController.test.ts | 20 +++++++++++ .../src/decorations/DecorationController.ts | 25 ++++++++++---- .../+margin-marker-anchor.added.md | 3 ++ .../lib/src/reader/reader_decoration.dart | 20 +++++++++-- .../test/models_test.dart | 8 +++++ 16 files changed, 172 insertions(+), 37 deletions(-) create mode 100644 flutter_readium/changelog.d/+margin-marker-anchor.added.md create mode 100644 flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md diff --git a/docs/api-reference/decorations.md b/docs/api-reference/decorations.md index 64353713..3884ecc8 100644 --- a/docs/api-reference/decorations.md +++ b/docs/api-reference/decorations.md @@ -41,11 +41,13 @@ ReaderDecoration( | Constructor | Description | |-------------|-------------| -| `MarginMarker.label(String, {side})` | Text label, such as a page number | -| `MarginMarker.icon(MarginMarkerIcon, {side})` | Built-in icon: `MarginMarkerIcon.bookmark`, `.note` or `.star` | +| `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.page` (default), which puts the marker near the page or column edge, or `MarginAnchor.text`, which keeps it a small gap from the text column however wide the margin is. See [Margin Markers](../guides/margin-markers.md#anchoring). + ## Applying decorations ```dart diff --git a/docs/guides/margin-markers.md b/docs/guides/margin-markers.md index dd062e81..43ce8cca 100644 --- a/docs/guides/margin-markers.md +++ b/docs/guides/margin-markers.md @@ -11,12 +11,22 @@ Markers are decorations with the `DecorationStyle.marginMarker` style, so they f ```dart const MarginMarker.label('12', side: MarginSide.end) const MarginMarker.icon(MarginMarkerIcon.bookmark) // side defaults to MarginSide.start +const MarginMarker.icon(MarginMarkerIcon.bookmark, anchor: 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` (default) 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` 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. 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 @@ -71,7 +81,7 @@ await reader.applyDecorations('highlight-markers', [ style: const ReaderDecorationStyle( style: DecorationStyle.marginMarker, tint: Color(0xFF2E7D32), - marker: MarginMarker.icon(MarginMarkerIcon.bookmark), + marker: MarginMarker.icon(MarginMarkerIcon.bookmark, anchor: MarginAnchor.text), ), ), ]); @@ -94,7 +104,7 @@ Pair a marker with a text decoration if tapping the location should do something ## Layout notes -- **Margin width.** Markers sit in the page margin. Icons need a little more room than page numbers, and with small `pageMargins` a marker can overlap the text. The plugin does not compensate for this. +- **Margin width.** Markers sit in the page margin, whatever their anchor. Icons need a little more room than page numbers, and with small `pageMargins` a marker can overlap the text. The plugin does not compensate for this. - **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. diff --git a/docs/plans/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md index 24b744cf..17851298 100644 --- a/docs/plans/margin-marker-decorations.md +++ b/docs/plans/margin-marker-decorations.md @@ -76,6 +76,16 @@ Design decisions: 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` (default) is the float template above. `MarginAnchor.text` 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. ## Implementation steps 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 index 19d1098b..53734ab1 100644 --- a/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt +++ b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/MarginMarkerStyle.kt @@ -7,6 +7,7 @@ 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 @@ -14,6 +15,7 @@ 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 { 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 75ab7d71..be4462cc 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 @@ -173,7 +173,8 @@ fun decorationStyleFromMap(decoMap: Map<*, *>?): Decoration.Style? { return null } val side = if (marker?.get("side") == "end") "end" else "start" - MarginMarkerStyle(label, icon, side, tint) + val anchor = if (marker?.get("anchor") == "text") "text" else "page" + MarginMarkerStyle(label, icon, side, anchor, tint) } else -> { 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 3fcfc709..b22dd3d7 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 @@ -1053,8 +1053,9 @@ class EpubReaderFragment : ) /** - * Margin marker floated into the page margin. Keep the markup identical to the iOS and web - * templates; the design is in docs/plans/margin-marker-decorations.md. + * 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( @@ -1083,8 +1084,7 @@ class EpubReaderFragment : if (style == null || content == null) { "
" } else { - val physical = if (style.side == "end") "right" else "left" - val logical = if (style.side == "end") "inline-end" else "inline-start" + val end = style.side == "end" val color = if (android.graphics.Color.alpha(style.tint) == 0) { "" @@ -1096,12 +1096,25 @@ class EpubReaderFragment : } // 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 = - "float: $physical !important; float: $logical !important;" + - " margin: 0 max(4px, 1.5%) !important; font-size: 0.75em !important; line-height: 1.4 !important;" + - opacity + - color - """
$content
""" + 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/assets/_helper_scripts/src/FlutterReadiumTools.ts b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts index b8f7bf1f..f66c44cc 100644 --- a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts +++ b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts @@ -421,9 +421,35 @@ function Setup() { initResponsiveTables(); startSpotlightObserver(document); + startTextInsetObserver(document); }); } +/** + * 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); +} + if (document.readyState !== 'loading') { window.setTimeout(Setup); } else { diff --git a/flutter_readium/changelog.d/+margin-marker-anchor.added.md b/flutter_readium/changelog.d/+margin-marker-anchor.added.md new file mode 100644 index 00000000..7cdafe5a --- /dev/null +++ b/flutter_readium/changelog.d/+margin-marker-anchor.added.md @@ -0,0 +1,3 @@ +**Text-anchored margin markers.** +`MarginMarker(..., anchor: MarginAnchor.text)` keeps a marker a small gap from the text column instead of at the page edge, which on wide screens can be far from the text. +It follows font size, page margins and scroll mode on iOS, Android and web. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#anchoring). diff --git a/flutter_readium/example/lib/state/highlight.dart b/flutter_readium/example/lib/state/highlight.dart index 47c524f2..d65c4e5f 100644 --- a/flutter_readium/example/lib/state/highlight.dart +++ b/flutter_readium/example/lib/state/highlight.dart @@ -23,7 +23,7 @@ class Highlight { Color? get tint => decoration.style.tint; - /// A bookmark icon in the margin, level with the first line of the highlight. + /// 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( @@ -31,7 +31,7 @@ class Highlight { locator: decoration.locator, style: const ReaderDecorationStyle( style: DecorationStyle.marginMarker, - marker: MarginMarker.icon(MarginMarkerIcon.bookmark), + marker: MarginMarker.icon(MarginMarkerIcon.bookmark, anchor: MarginAnchor.text), ), ); 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 46c09e7f..c6851ac6 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 @@ -7,11 +7,12 @@ extension Decoration.Style.Id { static let marginMarker: Decoration.Style.Id = "marginMarker" } -/// Payload of a `marginMarker` decoration style. `side` is "start" or "end". +/// 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. @@ -116,8 +117,8 @@ extension EPUBReaderView { ) } - /// Margin marker floated into the page margin. Keep the markup identical to the Android and web - /// templates; the design is in docs/plans/margin-marker-decorations.md. + /// 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, @@ -138,15 +139,23 @@ extension EPUBReaderView { } else { return "
" } - let physical = config.side == "end" ? "right" : "left" - let logical = config.side == "end" ? "inline-end" : "inline-start" - var css = "float: \(physical) !important; float: \(logical) !important;" - css += " margin: 0 max(4px, 1.5%) !important; font-size: 0.75em !important; line-height: 1.4 !important;" - css += opacity + 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;" } - return "
\(content)
" + 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/utils/ReadiumExtensions.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/utils/ReadiumExtensions.swift index f24a7dda..4bcda0d9 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 @@ -493,7 +493,7 @@ extension Decoration.Style { // Accepts the flat style map produced by ReaderDecorationStyle.toJson() on the Dart side: // { "style": "highlight", "tint": "#RRGGBB" (optional), "isActive": true/false, - // "marker": { "label"|"icon", "side" } (only for "marginMarker") } + // "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, @@ -515,9 +515,10 @@ extension Decoration.Style { throw JSONError.parsing(Self.self) } let side = marker?["side"] as? String == "end" ? "end" : "start" + let anchor = marker?["anchor"] as? String == "text" ? "text" : "page" self.init( id: .marginMarker, - config: MarginMarkerConfig(label: label, icon: icon, side: side, tint: tintColor?.uiColor) + config: MarginMarkerConfig(label: label, icon: icon, side: side, anchor: anchor, tint: tintColor?.uiColor) ) return } diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index bbb73618..9e949d0a 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -178,6 +178,26 @@ describe("DecorationController", () => { expect(html).toContain("color: #2e7d32ff !important;"); }); + it.each([ + ["start", "row", "--flutter-readium-text-inset-start", "margin-inline-start: auto"], + ["end", "row-reverse", "--flutter-readium-text-inset-end", "margin-inline-end: auto"], + ])("sizes a text-anchored %s marker's cell from the measured inset", (side, direction, inset, push) => { + const { controller, nav } = setup(); + + controller.applyDecorations( + nav as any, + "highlight-markers", + JSON.stringify([marker("t", { marker: { icon: "bookmark", side, anchor: "text" } })]) + ); + + 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(); diff --git a/flutter_readium/web/src/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index 7eba1543..efa6393a 100644 --- a/flutter_readium/web/src/decorations/DecorationController.ts +++ b/flutter_readium/web/src/decorations/DecorationController.ts @@ -31,6 +31,7 @@ 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. */ @@ -56,8 +57,9 @@ function escapeHtml(s: string): string { } /** - * Builds the margin marker element, or `null` when there is nothing to show. Keep the markup identical - * to the iOS and Android templates; the design is in docs/plans/margin-marker-decorations.md. + * 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 @@ -68,13 +70,24 @@ function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undef if (!content) return null; const end = marker?.side === "end"; - let css = - `float: ${end ? "right" : "left"} !important; float: ${end ? "inline-end" : "inline-start"} !important;` + - " margin: 0 max(4px, 1.5%) !important; font-size: 0.75em !important; line-height: 1.4 !important;"; + 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;`; - return `
${content}
`; + if (marker?.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. + 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 { diff --git a/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md b/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md new file mode 100644 index 00000000..273c4f81 --- /dev/null +++ b/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md @@ -0,0 +1,3 @@ +**`MarginMarker.anchor`.** +`MarginAnchor.text` places a margin marker a small gap from the text column instead of at the page edge (`MarginAnchor.page`, the default). +See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#anchoring). 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 33eb8c84..6387ce9b 100644 --- a/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart +++ b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart @@ -79,29 +79,43 @@ enum MarginMarkerIcon { /// 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). + page, + + /// A small gap from the text column, however wide the margin is. + 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}) : icon = null; + const MarginMarker.label(String this.label, {this.side = MarginSide.start, this.anchor = MarginAnchor.page}) + : icon = null; - const MarginMarker.icon(MarginMarkerIcon this.icon, {this.side = MarginSide.start}) : label = null; + const MarginMarker.icon(MarginMarkerIcon this.icon, {this.side = MarginSide.start, this.anchor = MarginAnchor.page}) + : label = null; - const MarginMarker._({this.label, this.icon, this.side = MarginSide.start}); + const MarginMarker._({this.label, this.icon, this.side = MarginSide.start, this.anchor = MarginAnchor.page}); 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.page, ); 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, }; } diff --git a/flutter_readium_platform_interface/test/models_test.dart b/flutter_readium_platform_interface/test/models_test.dart index 2b9f245d..79cfe6a7 100644 --- a/flutter_readium_platform_interface/test/models_test.dart +++ b/flutter_readium_platform_interface/test/models_test.dart @@ -1127,6 +1127,7 @@ void main() { expect(decoration.style.toJson()['marker'], { 'icon': 'bookmark', 'side': 'start', + 'anchor': 'page', }); final restored = roundTrip(decoration); expect(restored.style.marker?.icon, MarginMarkerIcon.bookmark); @@ -1135,6 +1136,13 @@ void main() { expect(restored.style.tint, const Color(0xFF2E7D32)); }); + test('text anchor round-trips; a missing or unknown anchor reads as page', () { + const marker = MarginMarker.icon(MarginMarkerIcon.note, anchor: MarginAnchor.text); + expect(MarginMarker.fromJson(marker.toJson()).anchor, MarginAnchor.text); + expect(MarginMarker.fromJson({'label': '3'}).anchor, MarginAnchor.page); + expect(MarginMarker.fromJson({'label': '3', 'anchor': 'gutter'}).anchor, MarginAnchor.page); + }); + test('copyWith keeps, replaces and clears the marker', () { const style = ReaderDecorationStyle( style: DecorationStyle.marginMarker, From 1e533a11d5ce50ab5a4a4c7a2a495c4dcd5dc252 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Tue, 24 Nov 2026 00:06:44 +0100 Subject: [PATCH 18/21] feat: anchor margin markers to the text by default Make MarginAnchor.text the default. On wide screens a page-anchored marker drifts far from its passage; on narrow margins the two anchors look the same. A missing or unknown anchor now reads as text on every platform. The example app's page numbers opt into MarginAnchor.page; bookmarks use the default. Co-Authored-By: Claude Opus 5.5 --- docs/api-reference/decorations.md | 2 +- docs/guides/margin-markers.md | 13 ++++++------- docs/plans/margin-marker-decorations.md | 3 ++- .../dk/nota/flutterreadium/ReadiumExtensions.kt | 2 +- .../changelog.d/+margin-marker-anchor.added.md | 4 ++-- flutter_readium/example/lib/pages/player.page.dart | 2 +- flutter_readium/example/lib/state/highlight.dart | 2 +- .../flutter_readium/utils/ReadiumExtensions.swift | 2 +- .../web/src/__tests__/DecorationController.test.ts | 12 ++++++------ .../web/src/decorations/DecorationController.ts | 2 +- .../changelog.d/+margin-marker-anchor.added.md | 2 +- .../lib/src/reader/reader_decoration.dart | 12 ++++++------ .../test/models_test.dart | 12 ++++++------ 13 files changed, 35 insertions(+), 35 deletions(-) diff --git a/docs/api-reference/decorations.md b/docs/api-reference/decorations.md index 3884ecc8..ca7e83a6 100644 --- a/docs/api-reference/decorations.md +++ b/docs/api-reference/decorations.md @@ -46,7 +46,7 @@ ReaderDecoration( `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.page` (default), which puts the marker near the page or column edge, or `MarginAnchor.text`, which keeps it a small gap from the text column however wide the margin is. See [Margin Markers](../guides/margin-markers.md#anchoring). +`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/guides/margin-markers.md b/docs/guides/margin-markers.md index 43ce8cca..56489970 100644 --- a/docs/guides/margin-markers.md +++ b/docs/guides/margin-markers.md @@ -9,9 +9,8 @@ Markers are decorations with the `DecorationStyle.marginMarker` style, so they f `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) -const MarginMarker.icon(MarginMarkerIcon.bookmark) // side defaults to MarginSide.start -const MarginMarker.icon(MarginMarkerIcon.bookmark, anchor: MarginAnchor.text) +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). @@ -22,8 +21,8 @@ The fields are described in the [API reference](../api-reference/decorations.md# `anchor` decides where the marker sits inside the margin: -- `MarginAnchor.page` (default) 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` 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. +- `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. It lines up with the body's text column, so paragraphs that the publisher indents further keep their extra indent. @@ -46,7 +45,7 @@ Future showPageNumbers(Publication publication) { locator: locator, style: ReaderDecorationStyle( style: DecorationStyle.marginMarker, - marker: MarginMarker.label(title, side: MarginSide.end), + marker: MarginMarker.label(title, side: MarginSide.end, anchor: MarginAnchor.page), ), ), ); @@ -81,7 +80,7 @@ await reader.applyDecorations('highlight-markers', [ style: const ReaderDecorationStyle( style: DecorationStyle.marginMarker, tint: Color(0xFF2E7D32), - marker: MarginMarker.icon(MarginMarkerIcon.bookmark, anchor: MarginAnchor.text), + marker: MarginMarker.icon(MarginMarkerIcon.bookmark), ), ), ]); diff --git a/docs/plans/margin-marker-decorations.md b/docs/plans/margin-marker-decorations.md index 17851298..f021ac2f 100644 --- a/docs/plans/margin-marker-decorations.md +++ b/docs/plans/margin-marker-decorations.md @@ -76,7 +76,7 @@ Design decisions: 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` (default) is the float template above. `MarginAnchor.text` makes the span a child of a flex cell as wide as the margin, with the span pushed against the cell's text side: +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
…
``` @@ -86,6 +86,7 @@ Design decisions: - **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 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 be4462cc..ed1234f4 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 @@ -173,7 +173,7 @@ fun decorationStyleFromMap(decoMap: Map<*, *>?): Decoration.Style? { return null } val side = if (marker?.get("side") == "end") "end" else "start" - val anchor = if (marker?.get("anchor") == "text") "text" else "page" + val anchor = if (marker?.get("anchor") == "page") "page" else "text" MarginMarkerStyle(label, icon, side, anchor, tint) } diff --git a/flutter_readium/changelog.d/+margin-marker-anchor.added.md b/flutter_readium/changelog.d/+margin-marker-anchor.added.md index 7cdafe5a..8bf819c0 100644 --- a/flutter_readium/changelog.d/+margin-marker-anchor.added.md +++ b/flutter_readium/changelog.d/+margin-marker-anchor.added.md @@ -1,3 +1,3 @@ -**Text-anchored margin markers.** -`MarginMarker(..., anchor: MarginAnchor.text)` keeps a marker a small gap from the text column instead of at the page edge, which on wide screens can be far from the text. +**Margin markers sit next to the text by default.** +A margin marker now keeps a small gap from the text column (`MarginAnchor.text`) instead of sitting at the page edge, which on wide screens can be far from the text. Pass `anchor: MarginAnchor.page` to keep a marker at the page edge, as suits page numbers. It follows font size, page margins and scroll mode on iOS, Android and web. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#anchoring). diff --git a/flutter_readium/example/lib/pages/player.page.dart b/flutter_readium/example/lib/pages/player.page.dart index 4c85d319..6e67490f 100644 --- a/flutter_readium/example/lib/pages/player.page.dart +++ b/flutter_readium/example/lib/pages/player.page.dart @@ -122,7 +122,7 @@ class _PlayerPageState extends State with RestorationMixin { locator: locator, style: ReaderDecorationStyle( style: DecorationStyle.marginMarker, - marker: MarginMarker.label(title, side: MarginSide.end), + marker: MarginMarker.label(title, side: MarginSide.end, anchor: MarginAnchor.page), ), ), ); diff --git a/flutter_readium/example/lib/state/highlight.dart b/flutter_readium/example/lib/state/highlight.dart index d65c4e5f..cbc5878e 100644 --- a/flutter_readium/example/lib/state/highlight.dart +++ b/flutter_readium/example/lib/state/highlight.dart @@ -31,7 +31,7 @@ class Highlight { locator: decoration.locator, style: const ReaderDecorationStyle( style: DecorationStyle.marginMarker, - marker: MarginMarker.icon(MarginMarkerIcon.bookmark, anchor: MarginAnchor.text), + marker: MarginMarker.icon(MarginMarkerIcon.bookmark), ), ); 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 4bcda0d9..414e1e3c 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 @@ -515,7 +515,7 @@ extension Decoration.Style { throw JSONError.parsing(Self.self) } let side = marker?["side"] as? String == "end" ? "end" : "start" - let anchor = marker?["anchor"] as? String == "text" ? "text" : "page" + 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) diff --git a/flutter_readium/web/src/__tests__/DecorationController.test.ts b/flutter_readium/web/src/__tests__/DecorationController.test.ts index 9e949d0a..7015d10b 100644 --- a/flutter_readium/web/src/__tests__/DecorationController.test.ts +++ b/flutter_readium/web/src/__tests__/DecorationController.test.ts @@ -133,7 +133,7 @@ describe("DecorationController", () => { 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 } }); + 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(); @@ -166,7 +166,7 @@ describe("DecorationController", () => { controller.applyDecorations( nav as any, "highlight-markers", - JSON.stringify([marker("b", { tint: "#ff2e7d32", marker: { icon: "bookmark", side: "start" } })]) + JSON.stringify([marker("b", { tint: "#ff2e7d32", marker: { icon: "bookmark", side: "start", anchor: "page" } })]) ); const [deco] = appliedTo(nav, "highlight-markers"); @@ -181,13 +181,13 @@ describe("DecorationController", () => { it.each([ ["start", "row", "--flutter-readium-text-inset-start", "margin-inline-start: auto"], ["end", "row-reverse", "--flutter-readium-text-inset-end", "margin-inline-end: auto"], - ])("sizes a text-anchored %s marker's cell from the measured inset", (side, direction, inset, push) => { + ])("sizes a text-anchored (default) %s marker's cell from the measured inset", (side, direction, inset, push) => { const { controller, nav } = setup(); controller.applyDecorations( nav as any, "highlight-markers", - JSON.stringify([marker("t", { marker: { icon: "bookmark", side, anchor: "text" } })]) + JSON.stringify([marker("t", { marker: { icon: "bookmark", side } })]) ); const [deco] = appliedTo(nav, "highlight-markers"); @@ -224,8 +224,8 @@ describe("DecorationController", () => { 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" }, tint: "#ff0000ff" }); - expect(second.extras).toEqual({ marker: { label: "1", side: "start" }, tint: "#00ff00ff" }); + 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)); }); diff --git a/flutter_readium/web/src/decorations/DecorationController.ts b/flutter_readium/web/src/decorations/DecorationController.ts index efa6393a..2c3df900 100644 --- a/flutter_readium/web/src/decorations/DecorationController.ts +++ b/flutter_readium/web/src/decorations/DecorationController.ts @@ -74,7 +74,7 @@ function marginMarkerHtml(marker: MarginMarker | undefined, tint: string | undef // 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 === "text") { + 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 = diff --git a/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md b/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md index 273c4f81..70f5eb67 100644 --- a/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md +++ b/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md @@ -1,3 +1,3 @@ **`MarginMarker.anchor`.** -`MarginAnchor.text` places a margin marker a small gap from the text column instead of at the page edge (`MarginAnchor.page`, the default). +`MarginAnchor.text` (the default) places a margin marker a small gap from the text column; `MarginAnchor.page` places it at the page edge. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#anchoring). 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 6387ce9b..f79f818d 100644 --- a/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart +++ b/flutter_readium_platform_interface/lib/src/reader/reader_decoration.dart @@ -81,28 +81,28 @@ 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). + /// 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. + /// 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.page}) + 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.page}) + 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.page}); + 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.page, + anchor: MarginAnchor.values.where((a) => a.name == map['anchor']).firstOrNull ?? MarginAnchor.text, ); final String? label; diff --git a/flutter_readium_platform_interface/test/models_test.dart b/flutter_readium_platform_interface/test/models_test.dart index 79cfe6a7..d038b496 100644 --- a/flutter_readium_platform_interface/test/models_test.dart +++ b/flutter_readium_platform_interface/test/models_test.dart @@ -1127,7 +1127,7 @@ void main() { expect(decoration.style.toJson()['marker'], { 'icon': 'bookmark', 'side': 'start', - 'anchor': 'page', + 'anchor': 'text', }); final restored = roundTrip(decoration); expect(restored.style.marker?.icon, MarginMarkerIcon.bookmark); @@ -1136,11 +1136,11 @@ void main() { expect(restored.style.tint, const Color(0xFF2E7D32)); }); - test('text anchor round-trips; a missing or unknown anchor reads as page', () { - const marker = MarginMarker.icon(MarginMarkerIcon.note, anchor: MarginAnchor.text); - expect(MarginMarker.fromJson(marker.toJson()).anchor, MarginAnchor.text); - expect(MarginMarker.fromJson({'label': '3'}).anchor, MarginAnchor.page); - expect(MarginMarker.fromJson({'label': '3', 'anchor': 'gutter'}).anchor, MarginAnchor.page); + 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', () { From f5dc0ee91622ce8e8442fac48f1542f3b14b9730 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Tue, 24 Nov 2026 00:15:13 +0100 Subject: [PATCH 19/21] fix(ios): relayout decorations after the viewport resizes The toolkit decorator relays out only from a body ResizeObserver. On iPad rotation WebKit fires it while window.innerWidth still reports the old viewport, so `width: page` decorations (margin markers) get the old page width and position. They stayed stale unless a later body-size change happened to trigger a second pass. Relayout every decoration group from the helper script on window `resize`, which fires with the new viewport size. The helper is shared, so Android gets the same relayout; kotlin-toolkit's decorator has the same ResizeObserver-only trigger. Co-Authored-By: Claude Opus 5.5 --- .../_helper_scripts/src/FlutterReadiumTools.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts index f66c44cc..5faa93bf 100644 --- a/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts +++ b/flutter_readium/assets/_helper_scripts/src/FlutterReadiumTools.ts @@ -422,6 +422,7 @@ function Setup() { initResponsiveTables(); startSpotlightObserver(document); startTextInsetObserver(document); + relayoutDecorationsOnResize(); }); } @@ -450,6 +451,21 @@ function startTextInsetObserver(doc: Document): void { 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?.(); + }); + }); +} + if (document.readyState !== 'loading') { window.setTimeout(Setup); } else { From dca01a48097e623469b99bb1d3dd7b55f48b1e02 Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Mon, 23 Nov 2026 15:30:05 +0100 Subject: [PATCH 20/21] feat: add makeSpaceForMarginDecoration EPUB preference At large font sizes, or with small page margins, a margin marker overlaps the text, because the page margin is a fixed gutter that does not grow with the font. The opt-in EPUBPreferences.makeSpaceForMarginDecoration widens the side padding to the largest of the Readium gutter x pageMargins and the room a marker needs with either anchor: 2 x max(4px, 1.5vw) + 1.3em for the page anchor, 4px + 0.5em + 1.3em for the text anchor. It never narrows the margin. The helper stylesheet holds the rule; native switches it on with a root CSS variable, web with a data attribute because ts-toolkit strips root style properties it did not set. Fixed-layout publications ignore it on all platforms. The example app gets a "Room for margin markers" switch. Co-Authored-By: Claude Opus 5.5 --- docs/api-reference/preferences.md | 1 + docs/guides/margin-markers.md | 17 +++++++++++-- .../flutterreadium/FlutterEpubPreferences.kt | 6 +++++ .../nota/flutterreadium/ReadiumExtensions.kt | 10 ++++---- .../FlutterEpubPreferencesTest.kt | 10 ++++++++ .../src/FlutterReadiumTools.scss | 19 +++++++++++++++ .../+margin-decoration-space.added.md | 3 +++ .../example/lib/state/text_settings_bloc.dart | 15 ++++++++++++ .../lib/widgets/text_settings.widget.dart | 11 +++++++++ .../preferences/FlutterEPUBPreferences.swift | 9 +++++++ .../reader/EPUBReaderView+Preferences.swift | 10 ++++---- flutter_readium/web/src/ReadiumReader.ts | 24 +++++++++++++++++-- .../web/src/__tests__/iframeInjection.test.ts | 21 +++++++++++++++- .../web/src/__tests__/preferences.test.ts | 13 +++++++++- .../src/preferences/FlutterEpubPreferences.ts | 4 ++++ .../web/src/utils/iframeInjection.ts | 14 +++++++++++ .../+margin-decoration-space.added.md | 3 +++ .../src/reader/reader_epub_preferences.dart | 17 ++++++++++++- .../test/models_test.dart | 14 +++++++++++ 19 files changed, 205 insertions(+), 16 deletions(-) create mode 100644 flutter_readium/changelog.d/+margin-decoration-space.added.md create mode 100644 flutter_readium_platform_interface/changelog.d/+margin-decoration-space.added.md diff --git a/docs/api-reference/preferences.md b/docs/api-reference/preferences.md index cd115d9a..6c81003e 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/margin-markers.md b/docs/guides/margin-markers.md index 56489970..d8131ca7 100644 --- a/docs/guides/margin-markers.md +++ b/docs/guides/margin-markers.md @@ -24,7 +24,7 @@ The fields are described in the [API reference](../api-reference/decorations.md# - `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. It lines up with the body's text column, so paragraphs that the publisher indents further keep their extra indent. +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. @@ -101,9 +101,22 @@ onDecorationInteraction: (event) { 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 -- **Margin width.** Markers sit in the page margin, whatever their anchor. Icons need a little more room than page numbers, and with small `pageMargins` a marker can overlap the text. The plugin does not compensate for this. - **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. 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 f4ce1a1a..414da9b8 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/ReadiumExtensions.kt b/flutter_readium/android/src/main/kotlin/dk/nota/flutterreadium/ReadiumExtensions.kt index ed1234f4..eb35a735 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 @@ -877,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/test/kotlin/dk/nota/flutterreadium/FlutterEpubPreferencesTest.kt b/flutter_readium/android/src/test/kotlin/dk/nota/flutterreadium/FlutterEpubPreferencesTest.kt index 884ec910..107b511b 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 90fbfd7b..1dde649c 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/changelog.d/+margin-decoration-space.added.md b/flutter_readium/changelog.d/+margin-decoration-space.added.md new file mode 100644 index 00000000..e9ac3f5b --- /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/example/lib/state/text_settings_bloc.dart b/flutter_readium/example/lib/state/text_settings_bloc.dart index a839b35b..259c3e35 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 c2b9217b..06f1f54e 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/model/preferences/FlutterEPUBPreferences.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/model/preferences/FlutterEPUBPreferences.swift index 6403c94f..b8b9b671 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+Preferences.swift b/flutter_readium/ios/flutter_readium/Sources/flutter_readium/reader/EPUBReaderView+Preferences.swift index c1d8f07f..83584752 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/web/src/ReadiumReader.ts b/flutter_readium/web/src/ReadiumReader.ts index c40d7176..6044a6f5 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"; @@ -51,7 +51,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"; @@ -175,6 +175,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. */ @@ -529,6 +531,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, @@ -542,6 +545,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. @@ -653,6 +657,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. } @@ -1109,6 +1118,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__/iframeInjection.test.ts b/flutter_readium/web/src/__tests__/iframeInjection.test.ts index 8fdb1754..0d6089ec 100644 --- a/flutter_readium/web/src/__tests__/iframeInjection.test.ts +++ b/flutter_readium/web/src/__tests__/iframeInjection.test.ts @@ -1,5 +1,9 @@ /** @jest-environment jsdom */ -import { injectFlutterReadiumHelperScripts, setHelperAssetUrls } from "../utils/iframeInjection"; +import { + injectFlutterReadiumHelperScripts, + setHelperAssetUrls, + setMarginDecorationSpaceInWindow, +} from "../utils/iframeInjection"; describe("injectFlutterReadiumHelperScripts", () => { it("fetches the helper URLs set from Dart, so content-hashed names resolve", async () => { @@ -15,3 +19,18 @@ describe("injectFlutterReadiumHelperScripts", () => { expect(frameDocument.head.textContent).toContain("/* assets/tools.4567cdef.css */"); }); }); + +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); + }); +}); diff --git a/flutter_readium/web/src/__tests__/preferences.test.ts b/flutter_readium/web/src/__tests__/preferences.test.ts index f53211e5..b8ddab2a 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/preferences/FlutterEpubPreferences.ts b/flutter_readium/web/src/preferences/FlutterEpubPreferences.ts index f1df8312..dc3086c1 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 7734fdc0..e9964e66 100644 --- a/flutter_readium/web/src/utils/iframeInjection.ts +++ b/flutter_readium/web/src/utils/iframeInjection.ts @@ -56,6 +56,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; + } +} + /** * Injects the Flutter Readium helper bundle (JS + CSS) and a bootstrap script * into a freshly-loaded EPUB iframe, mirroring what native iOS / Android do via 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 00000000..e9ac3f5b --- /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/lib/src/reader/reader_epub_preferences.dart b/flutter_readium_platform_interface/lib/src/reader/reader_epub_preferences.dart index 9163451f..91dcd5e2 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 d038b496..cbfb9359 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', () { From 571809b93cd3f937ccbec32eb3ca99930e5557cf Mon Sep 17 00:00:00 2001 From: Daniel Freiling Date: Tue, 24 Nov 2026 16:46:22 +0100 Subject: [PATCH 21/21] docs(changelog): fold margin anchor into the margin marker entry Text anchoring ships with margin markers in the same release, so it is part of that feature rather than a change upgraders would notice on its own. Co-Authored-By: Claude Opus 5.5 --- flutter_readium/changelog.d/+margin-marker-anchor.added.md | 3 --- .../changelog.d/+margin-marker-decorations.added.md | 4 ++-- .../changelog.d/+margin-marker-anchor.added.md | 3 --- .../changelog.d/+margin-marker-decorations.added.md | 4 ++-- 4 files changed, 4 insertions(+), 10 deletions(-) delete mode 100644 flutter_readium/changelog.d/+margin-marker-anchor.added.md delete mode 100644 flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md diff --git a/flutter_readium/changelog.d/+margin-marker-anchor.added.md b/flutter_readium/changelog.d/+margin-marker-anchor.added.md deleted file mode 100644 index 8bf819c0..00000000 --- a/flutter_readium/changelog.d/+margin-marker-anchor.added.md +++ /dev/null @@ -1,3 +0,0 @@ -**Margin markers sit next to the text by default.** -A margin marker now keeps a small gap from the text column (`MarginAnchor.text`) instead of sitting at the page edge, which on wide screens can be far from the text. Pass `anchor: MarginAnchor.page` to keep a marker at the page edge, as suits page numbers. -It follows font size, page margins and scroll mode on iOS, Android and web. See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#anchoring). diff --git a/flutter_readium/changelog.d/+margin-marker-decorations.added.md b/flutter_readium/changelog.d/+margin-marker-decorations.added.md index 4cf4434d..911313c4 100644 --- a/flutter_readium/changelog.d/+margin-marker-decorations.added.md +++ b/flutter_readium/changelog.d/+margin-marker-decorations.added.md @@ -1,3 +1,3 @@ **Margin marker decorations.** -`DecorationStyle.marginMarker` shows a text label or a built-in icon (bookmark, note or star) in the page margin, level with the first line of a locator, on iOS, Android and web. -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). +`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/changelog.d/+margin-marker-anchor.added.md b/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md deleted file mode 100644 index 70f5eb67..00000000 --- a/flutter_readium_platform_interface/changelog.d/+margin-marker-anchor.added.md +++ /dev/null @@ -1,3 +0,0 @@ -**`MarginMarker.anchor`.** -`MarginAnchor.text` (the default) places a margin marker a small gap from the text column; `MarginAnchor.page` places it at the page edge. -See the [margin markers guide](https://github.com/Notalib/flutter_readium/blob/main/docs/guides/margin-markers.md#anchoring). 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 index 4cf4434d..911313c4 100644 --- a/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md +++ b/flutter_readium_platform_interface/changelog.d/+margin-marker-decorations.added.md @@ -1,3 +1,3 @@ **Margin marker decorations.** -`DecorationStyle.marginMarker` shows a text label or a built-in icon (bookmark, note or star) in the page margin, level with the first line of a locator, on iOS, Android and web. -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). +`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).