Reorganize docs and update reader search flows

This commit is contained in:
shenlei 2026-06-10 08:22:07 +08:00
parent 0e7c0577e3
commit d15187b730
72 changed files with 517 additions and 5214 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.artifacts/

View File

@ -1,26 +0,0 @@
# Milestones
## v1.0
- **Date:** 2026-05-22
- **Scope:** Phases 1-5, 13 plans
- **Archive:** [v1.0-ROADMAP.md](/Users/shen/Work/Code/ReadViewSDK/.planning/milestones/v1.0-ROADMAP.md)
- **Requirements:** [v1.0-REQUIREMENTS.md](/Users/shen/Work/Code/ReadViewSDK/.planning/milestones/v1.0-REQUIREMENTS.md)
- **Audit:** [v1.0-MILESTONE-AUDIT.md](/Users/shen/Work/Code/ReadViewSDK/.planning/v1.0-MILESTONE-AUDIT.md)
### Delivered
- Directly evolved the native reflowable EPUB path toward a WXRead-style renderer instead of introducing a parallel engine.
- Added chapter-level CSS preprocessing, explicit CSS layering, and chapter-scoped renderer inputs.
- Upgraded pagination to use richer page metadata and layouter/layout-frame semantics while preserving offset compatibility.
- Reconnected reader restore, highlight, search, and repagination behavior without modifying `RDReaderView`.
- Built a 5-book validation matrix across native reflowable, fixed/interactive WebKit, and TXT paths.
### Known Gaps
- `REND-01`, `REND-02`, `REND-03`, `REND-04`
- `COMP-01`, `COMP-03`, `COMP-04`
- `STAB-01`, `STAB-02`
Known gaps were accepted at close as requirement bookkeeping debt; see the milestone audit for details.

View File

@ -1,104 +0,0 @@
# ReadViewSDK
## 这是什么
`ReadViewSDK` 是一个 iOS 阅读 SDK`RDReaderView`),提供 EPUB/TXT 的打开、分页与阅读器 UI并包含一个用于演示集成的 Demo 工程(`ReadViewDemo`)。当前项目面向 **brownfield已有代码**,目标是对现有 reflowable EPUB 阅读内核做一次直接重构在旧引擎基础上演进为参考读书WXRead的原生渲染方案而不是保留并行的第二套原生引擎。
## 核心价值
稳定可用的 EPUB/TXT 阅读体验。
## Current Milestone: v1.1 WXRead 深化对齐
**Goal:** 在 v1.0 已完成的 native reflowable 基础上,继续补齐页面几何能力、自定义分页属性闭环、分页质量/缓存,以及更强的自动化验证。
**Target features:**
- native text `layout frame` 几何查询与命中能力
- WXRead 风格分页属性从 HTML/CSS 到 paginator 的闭环
- 复杂图文章节分页质量与缓存/性能采样
- native reflowable 主路径自动化或稳定半自动化回归
## Current State
- 已完成 `v1.0`:现有 reflowable EPUB native path 已完成一轮 WXRead 风格原生化演进。
- chapter-level CSS 分层、页面元数据、复杂分页、reader restore/search/highlight 回接,以及 demo 样本矩阵都已落地。
- Fixed Layout / interactive EPUB 仍保持 `WKWebView` 路径,`RDReaderView` 仍保持既有分页容器契约。
## 需求
### 已验证(现有能力)
- ✓ 支持通过 `RDURLReaderController` 以 URL 打开 `.epub` / `.txt` 并进入阅读器(现有)
- ✓ 具备 `RDEPUBReaderController` 作为主阅读器控制器,负责加载/分页/状态管理(现有)
- ✓ 具备 `RDReaderView` 作为分页容器视图,支持翻页/滚动等呈现模式(现有)
- ✓ reflowable EPUB 当前主路径已是基于 `DTCoreText` / `NSAttributedString` / CoreText 的原生文本渲染与分页;但其样式分层、资源解析与分页策略仍较基础,本次将增强为更接近 WXRead 的实现(现有实现;本次将改造)
- ✓ 固定版式Fixed Layout与交互式内容存在 `WKWebView` 相关能力与桥接(现有)
- ✓ TXT 通过 `RDPlainTextBookBuilder` / `RDEPUBTextBook` 路径进入同一阅读器 UX现有
- ✓ 默认使用 `UserDefaults` 进行部分阅读器状态/设置持久化(现有)
- ✓ v1.0 已完成 native reflowable 原生化基础CSS 分层、页面级 metadata、分页器强化、reader 回接与样本矩阵验证v1.0
### 进行中(本次范围)
- [ ] v1.1 继续补齐 WXRead 深化对齐layout frame 几何能力、自定义分页属性闭环、分页质量/缓存、以及更强的自动化验证
### 不做(明确排除)
- Fixed Layout EPUB继续使用 `WKWebView`,不切换到 WXRead 渲染方式
- 交互式 EPUB含 JS / 音视频 / 表单 / iframe / 外链 / 脚本桥接等):继续使用 `WKWebView`,不切换到 WXRead 渲染方式
- 当前翻页代码(包括 `RDReaderView` 及其现有翻页模式/翻页交互逻辑):不做修改
- 直接拷贝使用读书私有 JS/CSS/私有实现代码:不做
- 同时保留两套 reflowable 原生引擎:不做
## 背景与上下文
- 仓库形态iOS SDK + Demo AppDemo 通过 CocoaPods 以本地 `:path` 引入 SDK。
- 当前分层:`EPUBCore`(解析/分页/状态)、`EPUBUI`(阅读器 UX、`EPUBTextRendering`TXT/TextBook / reflowable 原生文本渲染)、以及 `LegacyRDReaderController`(历史实现并存)。
- WXRead 参考资料位于 `Doc/WXRead/`,包含对读书 EPUB 阅读器的逆向分析文档与相关符号/源码片段。
- 当前 `.textReflowable` 主路径已基于 `DTCoreText` / `NSAttributedString` / CoreText 分页,但分页能力、页面语义、自定义属性体系与复杂块元素处理仍远弱于 WXRead。
## 约束
- **平台**iOS 15+Podspec 声明 iOS 15.0;工程中常见 15.6)— 现有基线
- **语言与风格**:代码标识符保持英文;文档/计划使用中文(见 `CONTEXT.md`)— 项目约束
- **依赖管理**CocoaPods 为主(`RDReaderView.podspec`、`Podfile`、`ReadViewDemo/Podfile`)— 现状约束
- **引擎策略**:必须基于现有旧引擎直接演进,不新增并行原生引擎 — 本次关键约束
- **范围控制**:仅重构 reflowable EPUB 原生渲染内核Fixed Layout 与交互式内容保持 `WKWebView` — 本次目标边界
- **翻页边界**:不修改当前翻页代码(`RDReaderView` 及现有 page curl / scroll 交互逻辑)— 新内核必须适配现有翻页容器
- **兼容性**:阅读位置映射、高亮/选区、搜索结果定位、字号/行高/主题切换后的重新分页必须继续可用 — 核心功能约束
- **稳定性优先**:任何改造需以“可回归验证、不破坏现有打开/阅读主流程”为前提 — 核心价值驱动
## 关键决策
| 决策 | 原因 | 结果 |
|---|---|---|
| reflowable EPUB 旧引擎直接重构为 WXRead 风格原生渲染 | 需要页面级排版能力,而不是继续在轻量 renderer 外壳上打补丁 | ✓ Good |
| Fixed Layout 与交互式 EPUB 继续使用 `WKWebView` | 降低风险与范围,避免破坏既有能力 | ✓ Good |
| 不保留并行 reflowable 原生引擎 | 避免双引擎长期维护成本,把演进压力集中在现有主路径上 | ✓ Good |
| 不修改当前翻页代码 | 控制改动半径,避免把阅读容器与翻页交互回归风险卷入本次内核重构 | ✓ Good |
## Next Milestone Goals
- 补齐 native text `layout frame` 几何查询能力,减少 reader 交互对 `UITextView` 黑盒的依赖
- 建立 WXRead 风格自定义分页属性从 HTML/CSS 到 paginator 的闭环
- 提升复杂图文章节分页质量,并增加缓存与性能采样
- 把 native reflowable 主路径的验证从 runtime spot-check 提升到自动化或稳定半自动化
## 演进
本文件会在阶段切换与里程碑完成时持续演进。
**每个 Phase 完成后**(通过 `$gsd-transition`
1. 有需求被证伪 → 移到“不做”并说明原因
2. 有需求被验证 → 移到“已验证”并记录来源 Phase
3. 出现新需求 → 加到“进行中”
4. 产生关键决策 → 追加到“关键决策”
5. “这是什么”是否仍准确 → 如有漂移及时更新
**每个 Milestone 完成后**(通过 `$gsd-complete-milestone`
1. 全面复查所有章节
2. 核心价值是否仍是最高优先级
3. “不做”是否需要调整边界与理由
4. 更新背景与上下文到当前真实状态
---
*Last updated: 2026-05-22 after v1.0 milestone completion*

View File

@ -1,110 +0,0 @@
# 需求ReadViewSDK v1.1WXRead 深化对齐)
**定义日期:** 2026-05-22
**核心价值:** 在已完成的 reflowable EPUB 原生化基础上,继续补齐 WXRead 风格的页面级排版能力、阅读交互精度与回归可验证性。
## 背景
v1 已完成以下主目标:
- reflowable EPUB 已具备 WXRead 风格的五层 CSS 组织与章节级 render context
- 分页器已具备 block / attachment 边界感知与页面元数据输出
- reader 主流程、高亮、搜索、位置恢复、主题/字号/行高重分页已接回
- fixed layout / interactive EPUB 继续保持 `WKWebView` 路径
`Doc/WXRead/analysis/` 对照后,当前主要差距已不在“是否走原生管线”,而在以下深化能力:
- 页面级 layout frame 的几何查询与绘制能力不足
- 自定义 CSS / attributed string 属性到分页器的闭环仍不完整
- 分页质量、缓存、复杂块元素规则与自动化验证仍弱于 WXRead
## v1.1 需求(本次范围)
### 页面级布局与几何能力
- [ ] **LAYOUT-01**:为 native text 分页结果补齐页面级 layout frame 几何查询能力,至少包括字符串范围矩形查询、矩形反查文本范围、截断检测、命中定位所需的基础 API
- [ ] **LAYOUT-02**:阅读器侧的高亮、搜索命中、选区、点击定位等行为应优先建立在 layout frame 几何能力之上,而不是继续强依赖 `UITextView` 的黑盒行为
- [ ] **LAYOUT-03**:页面级模型需要继续保留并兼容 `pageStartOffset`、`pageEndOffset`、`fragmentOffsets`、`RDEPUBTextOffsetRangeInfo` 等既有语义
### WXRead 自定义属性闭环
- [ ] **ATTR-01**:补齐一条从章节 HTML / CSS 到 `NSAttributedString` 再到分页器的自定义属性闭环,至少覆盖 `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`、`pageRelate`
- [ ] **ATTR-02**:图片与附件相关排版需要支持类似 `wr-vertical-center-style` 的语义输入,并在分页 / 展示阶段保留可消费的信息
- [ ] **ATTR-03**:复杂块元素至少要能区分代码块、表格、列表、引用块等类别,以支持更精细的分页边界控制与诊断
### 分页质量与性能收敛
- [ ] **QUAL-01**:为 layout frame / 分页结果增加缓存机制,避免同一章节在相同视口与排版配置下重复全量排版
- [ ] **QUAL-02**:复杂图文章节的分页质量要进一步提升,减少不合理断页、孤行/寡行、图片前后留白异常、代码块/表格被粗暴截断等问题
- [ ] **QUAL-03**:图片与附件的尺寸策略、暗色模式适配、页面背景类信息需要具备可验证的处理规则,而不是依赖默认 DTCoreText 行为
- [ ] **QUAL-04**:分页深化后不能显著恶化首屏时间、重分页耗时或交互流畅度;若无法立即建立硬性指标,至少要输出稳定的诊断与采样数据
### 稳定性与自动化验证
- [ ] **AUTO-01**:建立覆盖 native reflowable 主路径的自动化回归能力,至少覆盖打开书籍、分页完成、搜索命中、主题/字号切换、位置恢复
- [ ] **AUTO-02**:样本矩阵需要持续覆盖复杂图文、代码/表格/列表、附件密集、fixed/interactive WebKit、TXT 五类路径
- [ ] **AUTO-03**每项核心能力都应尽量附着到可重复证据日志、断言、诊断摘要、UI 自动化步骤或稳定的人工检查清单
## 成功标准
以下结论必须全部为 TRUE
1. native reflowable 路径拥有可复用的页面几何查询能力reader 交互不再主要依赖 `UITextView` 推断页面几何
2. 至少一组 WXRead 风格自定义分页属性已形成端到端闭环,并对复杂块元素分页产生可见收益
3. 同一批复杂样本在新一轮分页器深化后,分页质量优于当前 v1 完成态,而不是仅增加结构复杂度
4. 自动化或半自动化验证覆盖到 native text 的关键交互,不再主要依赖单次手工 spot check
5. fixed layout、interactive EPUB、TXT 和既有 `RDReaderView` 翻页容器不回归
## 非目标(本次明确不做)
| 功能 | 原因 |
|---|---|
| 重写或替换 `RDReaderView` 翻页容器 | 本次继续只深化 native reflowable 内核与页面几何能力 |
| 复刻 WXRead 的完整业务层能力(翻译/双语、免费试读、网络协议、DRM | 这些属于业务闭环,不是当前 SDK 与 WXRead 的主要技术差距 |
| 将 fixed layout / interactive EPUB 改为原生渲染 | 仍保持 `WKWebView` 路径以控制风险 |
| 直接拷贝读书私有 CSS / JS / 私有实现代码 | 仅参考设计思路,不直接搬运私有实现 |
| 一次性完整重写成自绘 `WRPageView` 等价体系 | 风险过大,优先通过 layout frame 几何层与局部 reader 接线演进 |
## 风险与约束
- `RDReaderView`、现有 page curl / horizontal / vertical 交互逻辑继续视为稳定容器契约
- `RDEPUBReaderController` / `RDURLReaderController` 公开入口必须保持兼容
- 所有分页深化都必须保留 offset-based 兼容语义,避免破坏现有高亮、搜索、恢复位置数据
- 若要引入自绘或替换 `UITextView` 页面展示,需要以“先引入几何能力、再最小替换”的顺序推进
- 若性能采样显示分页深化明显拖慢主流程,应优先做缓存与局部优化,而不是继续扩展特性面
## 建议优先级
1. `LAYOUT-*`:先补 layout frame 几何能力
2. `ATTR-*`:再补自定义属性到分页器闭环
3. `QUAL-*`:随后做分页质量与缓存收敛
4. `AUTO-*`:最后把运行时验证补成自动化或稳定半自动化
## 候选 Phase 映射
| 需求 | 建议 Phase | 说明 |
|---|---:|---|
| LAYOUT-01 | Phase 6 | layout frame 几何 API 与截断检测 |
| LAYOUT-02 | Phase 6 | reader 交互从 `UITextView` 推断迁移到几何层 |
| LAYOUT-03 | Phase 6 | 保持 offset / fragment 兼容契约 |
| ATTR-01 | Phase 7 | 自定义分页属性闭环 |
| ATTR-02 | Phase 7 | 图片 / 附件布局语义 |
| ATTR-03 | Phase 7 | block type 分类与分页规则 |
| QUAL-01 | Phase 8 | layout frame / pagination cache |
| QUAL-02 | Phase 8 | 复杂样本分页质量提升 |
| QUAL-03 | Phase 8 | 图片暗色与页面背景类规则 |
| QUAL-04 | Phase 8 | 诊断与性能采样 |
| AUTO-01 | Phase 9 | native reflowable 自动化回归 |
| AUTO-02 | Phase 9 | 样本矩阵扩展 |
| AUTO-03 | Phase 9 | 证据标准化 |
**覆盖统计:**
- v1.1 需求总数13
- 页面级布局3
- 属性闭环3
- 质量与性能4
- 自动化验证3
---
*Requirements defined: 2026-05-22*
*Last updated: 2026-05-22 after WXRead gap analysis*

View File

@ -1,76 +0,0 @@
# 需求ReadViewSDK v1.1
**定义日期:** 2026-05-22
**核心价值:** 稳定可用的 EPUB/TXT 阅读体验
## v1.1 需求(本次范围)
### 页面级布局与几何能力
- [ ] **LAYOUT-01**:为 native text 分页结果补齐页面级 layout frame 几何查询能力,至少包括字符串范围矩形查询、矩形反查文本范围、截断检测、命中定位所需的基础 API
- [ ] **LAYOUT-02**:阅读器侧的高亮、搜索命中、选区、点击定位等行为应优先建立在 layout frame 几何能力之上,而不是继续强依赖 `UITextView` 的黑盒行为
- [ ] **LAYOUT-03**:页面级模型需要继续保留并兼容 `pageStartOffset`、`pageEndOffset`、`fragmentOffsets`、`RDEPUBTextOffsetRangeInfo` 等既有语义
### WXRead 自定义属性闭环
- [ ] **ATTR-01**:补齐一条从章节 HTML / CSS 到 `NSAttributedString` 再到分页器的自定义属性闭环,至少覆盖 `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`、`pageRelate`
- [ ] **ATTR-02**:图片与附件相关排版需要支持类似 `wr-vertical-center-style` 的语义输入,并在分页 / 展示阶段保留可消费的信息
- [ ] **ATTR-03**:复杂块元素至少要能区分代码块、表格、列表、引用块等类别,以支持更精细的分页边界控制与诊断
### 分页质量与性能收敛
- [ ] **QUAL-01**:为 layout frame / 分页结果增加缓存机制,避免同一章节在相同视口与排版配置下重复全量排版
- [ ] **QUAL-02**:复杂图文章节的分页质量要进一步提升,减少不合理断页、孤行/寡行、图片前后留白异常、代码块/表格被粗暴截断等问题
- [ ] **QUAL-03**:图片与附件的尺寸策略、暗色模式适配、页面背景类信息需要具备可验证的处理规则,而不是依赖默认 DTCoreText 行为
- [ ] **QUAL-04**:分页深化后不能显著恶化首屏时间、重分页耗时或交互流畅度;若无法立即建立硬性指标,至少要输出稳定的诊断与采样数据
### 稳定性与自动化验证
- [ ] **AUTO-01**:建立覆盖 native reflowable 主路径的自动化回归能力,至少覆盖打开书籍、分页完成、搜索命中、主题/字号切换、位置恢复
- [ ] **AUTO-02**:样本矩阵需要持续覆盖复杂图文、代码/表格/列表、附件密集、fixed/interactive WebKit、TXT 五类路径
- [ ] **AUTO-03**每项核心能力都应尽量附着到可重复证据日志、断言、诊断摘要、UI 自动化步骤或稳定的人工检查清单
## Future Requirements
### 后续增强(暂不进入 v1.1 roadmap
- **PERF-01**:建立更严格的性能基线与持续采样门槛(首屏时间、重分页时间、内存峰值)
- **GEOM-01**:如果几何层成熟,进一步评估是否需要逐步替换 `UITextView` 展示层
- **INTL-01**更完整的国际化排版增强RTL、断字、多语种高级回退
## Out of Scope
| 功能 | 原因 |
|------|------|
| 重写或替换 `RDReaderView` 翻页容器 | 本次继续只深化 native reflowable 内核与页面几何能力 |
| 复刻 WXRead 的完整业务层能力(翻译/双语、免费试读、网络协议、DRM | 这些属于业务闭环,不是当前 SDK 与 WXRead 的主要技术差距 |
| 将 fixed layout / interactive EPUB 改为原生渲染 | 仍保持 `WKWebView` 路径以控制风险 |
| 直接拷贝读书私有 CSS / JS / 私有实现代码 | 仅参考设计思路,不直接搬运私有实现 |
| 一次性完整重写成自绘 `WRPageView` 等价体系 | 风险过大,优先通过 layout frame 几何层与局部 reader 接线演进 |
## Traceability
| Requirement | Phase | Status |
|-------------|-------|--------|
| LAYOUT-01 | Phase 6 | Pending |
| LAYOUT-02 | Phase 6 | Pending |
| LAYOUT-03 | Phase 6 | Pending |
| ATTR-01 | Phase 7 | Pending |
| ATTR-02 | Phase 7 | Pending |
| ATTR-03 | Phase 7 | Pending |
| QUAL-01 | Phase 8 | Pending |
| QUAL-02 | Phase 8 | Pending |
| QUAL-03 | Phase 8 | Pending |
| QUAL-04 | Phase 8 | Pending |
| AUTO-01 | Phase 9 | Pending |
| AUTO-02 | Phase 9 | Pending |
| AUTO-03 | Phase 9 | Pending |
**Coverage:**
- v1.1 requirements: 13 total
- Mapped to phases: 13
- Unmapped: 0 ✓
---
*Requirements defined: 2026-05-22*
*Last updated: 2026-05-22 after v1.1 milestone initialization*

View File

@ -1,103 +0,0 @@
# 路线图ReadViewSDK v1.1
## 概述
`v1.1` 聚焦在 v1.0 已完成的 native reflowable EPUB 基础上继续深化 WXRead 对齐,不重新打开更大范围的架构重写。实施顺序固定为:先补页面级 layout frame 几何能力,再建立自定义分页属性闭环,然后收敛分页质量/缓存,最后把 native reflowable 的回归证据提升到自动化或稳定半自动化。`RDReaderView` 继续视为稳定容器fixed layout / interactive EPUB 继续保留 `WKWebView` 路径。
## Phases
- [ ] **Phase 6: 页面几何与交互命中层** - 为 native text 建立可复用的 layout frame 几何能力,并让 reader 交互优先依赖该几何层
- [ ] **Phase 7: WXRead 自定义属性闭环** - 建立章节 HTML/CSS → attributed string → paginator 的自定义分页属性闭环
- [ ] **Phase 8: 分页质量、缓存与性能采样** - 改善复杂图文分页质量并加入缓存、暗色/附件规则和性能诊断
- [ ] **Phase 9: 自动化回归与证据标准化** - 把 native reflowable 主路径回归能力提升到自动化或稳定半自动化,并扩展样本矩阵
## Phase Details
### Phase 6: 页面几何与交互命中层
**Goal**: 为 native text 分页结果建立页面级 layout frame 几何查询能力,并把 reader 交互逐步迁移到显式几何层,而不是继续主要依赖 `UITextView` 的黑盒行为。
**Depends on**: Phase 5
**Requirements**: LAYOUT-01, LAYOUT-02, LAYOUT-03
**Success Criteria** (必须为 TRUE):
1. native text 页面可查询字符串范围矩形、矩形反查文本范围、截断与命中信息
2. 至少一条 reader 交互链路(如搜索命中、高亮或点击定位)优先消费 layout frame 几何结果
3. `pageStartOffset`、`pageEndOffset`、`fragmentOffsets`、`RDEPUBTextOffsetRangeInfo` 兼容语义保持稳定
**Plans**: 3 plans
Plans:
- [ ] 06-01`RDEPUBTextLayoutFrame` / page model 补齐几何查询 API 与截断诊断
- [ ] 06-02让 reader 的命中/定位链路优先消费 layout frame 几何层
- [ ] 06-03验证 offset / fragment 兼容契约在新几何层下不回归
Cross-cutting constraints:
- 不替换 `RDReaderView`
- 不引入新的公开 reader 入口
- 优先增量接线,不一次性重写展示层
### Phase 7: WXRead 自定义属性闭环
**Goal**: 把章节 HTML/CSS 中的分页相关语义稳定地传导到 attributed string 与 paginator让复杂块元素、图片和附件拥有更精细的分页控制。
**Depends on**: Phase 6
**Requirements**: ATTR-01, ATTR-02, ATTR-03
**Success Criteria** (必须为 TRUE):
1. 至少 `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`、`pageRelate` 形成端到端闭环
2. 图片/附件垂直居中等语义在分页或展示阶段仍可被消费
3. 代码块、表格、列表、引用块等类别在分页诊断中可区分,并影响分页边界控制
**Plans**: 3 plans
Plans:
- [ ] 07-01定义并接线分页相关自定义属性从 HTML/CSS 到 attributed string 的映射
- [ ] 07-02补齐图片/附件语义与页面消费规则
- [ ] 07-03为复杂块元素分类与分页规则建立诊断和验证路径
Cross-cutting constraints:
- 继续沿用现有 chapter preprocessing 与 renderer contract
- 不直接搬运读书私有实现
- 新属性必须可诊断、可回归,不是隐式魔法行为
### Phase 8: 分页质量、缓存与性能采样
**Goal**: 在新几何层与属性闭环之上提升复杂图文章节分页质量,并控制重复排版开销与主题/附件规则的一致性。
**Depends on**: Phase 7
**Requirements**: QUAL-01, QUAL-02, QUAL-03, QUAL-04
**Success Criteria** (必须为 TRUE):
1. 相同视口与排版配置下,同一章节不会重复全量排版
2. 复杂图文章节分页质量可见改善,减少粗暴截断、不合理留白、孤行/寡行
3. 图片尺寸策略、暗色模式适配、页面背景类信息有明确处理规则和诊断证据
4. 首屏时间、重分页耗时或交互流畅度不会出现明显退化,且有稳定采样数据
**Plans**: 3 plans
Plans:
- [ ] 08-01为 layout frame / pagination 增加缓存键与失效策略
- [ ] 08-02针对复杂样本收敛分页质量与图片/附件/背景规则
- [ ] 08-03补充性能采样与质量诊断输出
Cross-cutting constraints:
- 先做缓存和局部优化,再考虑进一步扩展特性面
- 质量提升必须基于真实样本,而不是仅靠 synthetic case
- 保持与现有 offset-based consumer 的兼容
### Phase 9: 自动化回归与证据标准化
**Goal**: 建立覆盖 native reflowable 主路径的自动化或稳定半自动化回归能力,并把样本矩阵和运行时证据标准化。
**Depends on**: Phase 8
**Requirements**: AUTO-01, AUTO-02, AUTO-03
**Success Criteria** (必须为 TRUE):
1. native reflowable 至少覆盖打开书籍、分页完成、搜索命中、主题/字号切换、位置恢复
2. 样本矩阵持续覆盖复杂图文、代码/表格/列表、附件密集、fixed/interactive WebKit、TXT 五类路径
3. 每项核心能力都具备可重复证据日志、断言、诊断摘要、UI 自动化步骤或稳定人工检查清单
**Plans**: 2 plans
Plans:
- [ ] 09-01建立 native reflowable 关键交互自动化或稳定半自动化验证
- [ ] 09-02扩展样本矩阵并统一证据标准、日志摘要与 rerun 清单
Cross-cutting constraints:
- 不为验证再造第二套 demo shell
- 优先复用 `ReadViewDemo`、现有日志和诊断输出
- WebKit / TXT 路径仍必须留在矩阵内,不能只测 native reflowable
## Progress
| Phase | Plans Complete | Status | Completed |
|---|---:|---|---|
| 6. 页面几何与交互命中层 | 0/3 | Not started | - |
| 7. WXRead 自定义属性闭环 | 0/3 | Not started | - |
| 8. 分页质量、缓存与性能采样 | 0/3 | Not started | - |
| 9. 自动化回归与证据标准化 | 0/2 | Not started | - |

View File

@ -1,66 +0,0 @@
---
gsd_state_version: 1.0
milestone: v1.1
milestone_name: WXRead 深化对齐
status: executing
last_updated: "2026-05-23T10:43:34.404Z"
last_activity: 2026-05-23 -- Phase 8 planning complete
progress:
total_phases: 4
completed_phases: 2
total_plans: 9
completed_plans: 6
percent: 50
---
# STATE
**状态日期:** 2026-05-22
**项目:** ReadViewSDKbrownfield
## Project Reference
参见:`.planning/PROJECT.md`(更新于 2026-05-22
**核心价值:** 稳定可用的 EPUB/TXT 阅读体验
**当前关注:** `v1.1` 已完成 Phase 6-7 执行闭环,下一步进入 Phase 8 规划或执行
## 当前结论(摘要)
- `v1.1` 已基于现有候选需求正式生成 active `REQUIREMENTS.md``ROADMAP.md`
- 当前活跃 roadmap 包含 Phase 6-9页面几何、属性闭环、分页质量/缓存、自动化回归。
- Phase 7 已完成执行与验证HTML/CSS → attributed string → paginator 的属性闭环已落到 renderer → layouter → page metadata 这条链路。
- `v1.0` 归档与 audit 仍保留在 `.planning/milestones/``.planning/v1.0-MILESTONE-AUDIT.md` 供后续追溯。
## 当前风险焦点
- native text 分页质量/缓存与自动化验证仍是 `v1.1` 的主要技术风险
- `v1.0` 遗留的 requirement bookkeeping gap 已归档,不应阻塞 `v1.1` 执行,但后续引用历史证据时需注意
- simulator 仍会输出既有 `.SFUI-Semibold` CoreText 替代提示,但未造成功能性失败
## 现有代码库地图
- 代码库地图:`.planning/codebase/`
- 关键文档:
- `.planning/codebase/ARCHITECTURE.md`
- `.planning/codebase/STACK.md`
- `.planning/codebase/STRUCTURE.md`
- `.planning/codebase/CONCERNS.md`
- 方案文档:
- `Doc/FeatureSolution/ReflowableEPUB_WXReadRenderer_Design.md`
## 下一步
- 建议下一步:`$gsd-plan-phase 8` 或在确认顺序后继续 `$gsd-execute-phase 8`
- 已完成的产物目录:
- `.planning/milestones/`
- `.planning/phases/06-page-geometry-and-interaction-hit-layer/`
- `.planning/phases/07-wxread/`
- `.planning/REQUIREMENTS-v1.1-WXRead-next.md`
## Current Position
Phase: 8
Plan: pending
Status: Ready to execute
Last activity: 2026-05-23 -- Phase 8 planning complete

View File

@ -1,154 +0,0 @@
<!-- refreshed: 2026-05-21 -->
# 架构概览
**分析日期:** 2026-05-21
## 系统概述
本仓库包含一个 iOS **阅读 SDK**`RDReaderView`)以及一个用于演示集成的 **Demo App**`ReadViewDemo`。Demo 通过 CocoaPods 以本地 `:path` 方式引入 SDK。
```text
┌─────────────────────────────────────────────────────────────────────────┐
│ Demo App │
`ReadViewDemo/ReadViewDemo`
│ - 列表展示内置 .epub/.txt → push `RDURLReaderController`
└───────────────────────────────┬─────────────────────────────────────────┘
│ uses
┌─────────────────────────────────────────────────────────────────────────┐
│ Public SDK │
`Sources/RDReaderView`
│ 入口控制器: │
│ - `RDURLReaderController`(基于 URLepub/txt
│ - `RDEPUBReaderController`EPUB + 外部 TextBook
│ 核心视图: │
│ - `RDReaderView`(仿真翻页 / 横向 / 纵向模式) │
└───────────────┬───────────────────────────┬─────────────────────────────┘
│ │
▼ ▼
┌───────────────────────────┐ ┌─────────────────────────────────────────┐
│ EPUBCore │ │ EPUBTextRendering │
`Sources/RDReaderView/ │ │ `Sources/RDReaderView/EPUBTextRendering`│
│ EPUBCore` │ │ - 从 .txt 构建 `RDEPUBTextBook`
│ - 解析/解压 EPUB │ │ - 文本章节渲染/搜索 │
│ - spine/TOC/location 模型 │ └─────────────────────────────────────────┘
│ - 基于 WKWebView 分页 │
│ - 资源解析/寻址 │
└───────────────┬───────────┘
┌─────────────────────────────────────────────────────────────────────────┐
│ EPUBUI │
`Sources/RDReaderView/EPUBUI`
│ - 阅读器 UX工具栏/主题/设置 │
│ - 默认持久化UserDefaults
│ - 协调 parser + paginator + RDReaderView │
└─────────────────────────────────────────────────────────────────────────┘
```
## 组件职责
| 组件 | 职责 | 文件 |
|---|---|---|
| `RDURLReaderController` | 面向“URL 打开”的顶层入口;根据后缀路由 epub vs txt当分页失败时回退为纯文本展示 | `Sources/RDReaderView/RDURLReaderController.swift` |
| `RDEPUBReaderController` | 主阅读器控制器;协调解析/分页,连接 `RDReaderView`;管理阅读状态、选择/高亮/书签、工具视图等 | `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift` |
| `RDReaderView` | 分页容器视图,支持仿真翻页与滚动模式;通过 data source 获取页面视图并回调当前页变化 | `Sources/RDReaderView/RDReaderView.swift` |
| `RDEPUBParser` | 负责解析 `.epub`container.xml + OPF构建 manifest/spine/TOC产出 `RDEPUBPublication` | `Sources/RDReaderView/EPUBCore/RDEPUBParser.swift` |
| `RDEPUBPublication` | 对解析后的 publication 做只读封装metadata/spine/TOC/资源解析、fixed-layout 判定等) | `Sources/RDReaderView/EPUBCore/RDEPUBPublication.swift` |
| `RDEPUBPaginator` | 以 `WKWebView` 测量并生成分页信息章节页范围、CFI 映射等) | `Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift` |
| `RDEPUBReadingSession` | 阅读会话状态(当前章节/页、分页缓存、交互状态等),为 UI 层提供数据 | `Sources/RDReaderView/EPUBCore/RDEPUBReadingSession.swift` |
| `RDEPUBReaderPersistence` | 阅读器持久化协议(位置/设置/书签/高亮等),默认实现使用 UserDefaults | `Sources/RDReaderView/EPUBUI/RDEPUBReaderPersistence.swift` |
> 备注:实际类型与职责以代码为准;上表按文件职责做抽象总结。
## 分层结构
**Demo App 层:**
- 目的:展示集成方式与最小化书籍选择 UX。
- 位置:`ReadViewDemo/ReadViewDemo`
- 依赖:本地 path 的 `RDReaderView` pod、UIKit。
**SDK UI 层Reader UX**
- 目的:阅读器控制器 UX + 设置持久化 + 工具视图。
- 位置:`Sources/RDReaderView/EPUBUI`
- 依赖:`EPUBCore`、`EPUBTextRendering`、`RDReaderView`。
**SDK View 层(分页容器):**
- 目的:页面呈现模式(翻页/滚动)与手势/工具栏显示控制。
- 位置:`Sources/RDReaderView/RDReaderView.swift`、`Sources/RDReaderView/RDReaderFlowLayout.swift`
- 依赖UIKit。
**SDK Core 层EPUB 解析/分页/状态):**
- 目的:解析 EPUB 结构、资源寻址、分页计算、导航状态。
- 位置:`Sources/RDReaderView/EPUBCore`
- 依赖Foundation、WebKit分页/导航、ZIPFoundation解压通过 Podspec 依赖)。
**SDK 文本渲染层:**
- 目的:为纯文本输入构建分页结构并提供渲染/搜索能力。
- 位置:`Sources/RDReaderView/EPUBTextRendering`
- 依赖UIKit/Foundation以及通过 Podspec 依赖的 DTCoreText 相关能力)。
## 数据流
### 主路径(通过 URL 打开书籍)
1. Demo 选择文件并 push reader`ReadViewDemo/ReadViewDemo/ViewController.swift`)。
2. `RDURLReaderController` 根据扩展名分发(`Sources/RDReaderView/RDURLReaderController.swift`)。
3. 对 EPUB`RDEPUBReaderController` 开始加载,解析 publication并为当前视口执行分页`Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`)。
4. 分页由 `RDEPUBPaginator``WKWebView` 测量)生成 `EPUBPage` / `EPUBChapterInfo` 等快照,供 `RDReaderView` 渲染(`Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift`、`Sources/RDReaderView/EPUBCore/RDEPUBReadingSession.swift`)。
5. `RDReaderView` 展示页面并输出页切换回调(`Sources/RDReaderView/RDReaderView.swift`)。
### 次路径(打开纯文本文件)
1. `RDURLReaderController` 使用 `RDPlainTextBookBuilder` 构建 `RDEPUBTextBook`,分页尺寸/样式来自 `RDEPUBReaderConfiguration``Sources/RDReaderView/RDURLReaderController.swift`、`Sources/RDReaderView/EPUBTextRendering/RDPlainTextBookBuilder.swift`)。
2. `RDEPUBReaderController` 以 “external TextBook” 模式运行,复用相同的阅读器 UX 与持久化链路(`Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`)。
**状态管理:**
- 内存态主要由 `RDEPUBReadingSession``RDEPUBReaderController` 维护。
- 默认持久化为 UserDefaults`RDEPUBUserDefaultsPersistence`,见 `Sources/RDReaderView/EPUBUI/RDEPUBReaderPersistence.swift`)。
## 入口点
**SDK**
- `RDURLReaderController`URL 入口,封装 epub/txt 分支(`Sources/RDReaderView/RDURLReaderController.swift`)。
- `RDEPUBReaderController`:可直接打开 epub URL或读取已构建的 `RDEPUBTextBook``Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`)。
- `RDReaderView`:可复用的分页视图(`Sources/RDReaderView/RDReaderView.swift`)。
**Demo**
- UIKit 生命周期(`ReadViewDemo/ReadViewDemo/AppDelegate.swift`、`ReadViewDemo/ReadViewDemo/SceneDelegate.swift`)。
## 架构约束
- **平台:** iOS 15+`RDReaderView.podspec` 中 `s.platform = :ios, "15.0"`)。
- **视口耦合:** 分页与视口大小/insets 强耦合,视口变化会触发重新分页(`Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`)。
- **WebKit 依赖:** 可重排 EPUB 的分页使用离屏、非持久化的 `WKWebView``Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift`)。
## 错误处理
**策略:** URL 入口采用“尽量可用”的 fail-soft 体验Reader Controller 提供可见的 loading/error UI。
**模式:**
- URL 入口在文本分页失败时回退为 `UITextView``Sources/RDReaderView/RDURLReaderController.swift`)。
- Parser 通过 `RDEPUBParserError` 抛出类型化错误(`Sources/RDReaderView/EPUBCore/RDEPUBModels.swift`)。
## Evidence关键证据
检查过的关键文件:
- `RDReaderView.podspec`
- `Podfile`
- `ReadViewDemo/ReadViewDemo.xcworkspace/contents.xcworkspacedata`
- `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
- `ReadViewDemo/ReadViewDemo/AppDelegate.swift`
- `ReadViewDemo/ReadViewDemo/SceneDelegate.swift`
- `ReadViewDemo/ReadViewDemo/ViewController.swift`
- `Sources/RDReaderView/RDURLReaderController.swift`
- `Sources/RDReaderView/RDReaderView.swift`
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBParser.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBPublication.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingSession.swift`
---
*架构分析2026-05-21*

View File

@ -1,90 +0,0 @@
# 外部集成
**分析日期:** 2026-05-21
## API 与外部服务
**网络 / Web 服务:**
- 在 SDK 源码(`Sources/RDReaderView/**`)中未检测到:未发现 `URLSession` 使用,也未发现常见第三方网络 SDK。
**托管服务 SDK统计/崩溃/广告/支付):**
- 在仓库源码中未检测到:未发现 Firebase、Sentry、Mixpanel/Segment/Amplitude、AppCenter 等。
## 数据存储
**数据库:**
- 未检测到(`Sources/RDReaderView/**` 中未发现 Core Data / SQLite / Realm / GRDB 使用)。
**文件存储(本地文件系统):**
- EPUB 解压使用 `FileManager`,将解压内容存放在 app caches 或临时目录下,并使用“确定性签名”目录名 — `Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift`
**偏好 / 轻量持久化:**
- 使用 `UserDefaults` 保存设置/状态(例如 debug 开关、阅读器状态快照)— `Sources/RDReaderView/EPUBCore/RDEPUBWebViewDebug.swift`、`Sources/RDReaderView/EPUBUI/RDEPUBReaderPersistence.swift`、`Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`。
## 认证与身份
- 不适用(未检测到认证提供方或身份流程)。
## 监控与可观测性
**错误追踪 / 崩溃上报:**
- 未检测到(无 Crashlytics/Sentry 等)。
**日志:**
- 存在用于 EPUB WebView 调试的本地 debug 日志工具 — `Sources/RDReaderView/EPUBCore/RDEPUBWebViewDebug.swift`
## 构建期集成
**CocoaPods**
- SDK 作为 CocoaPod 发布并声明外部依赖 — `RDReaderView.podspec`
- 示例 App 通过本地 `:path => '..'` 引用该 Pod — `ReadViewDemo/Podfile`
- 仓库根 `Podfile` 也声明了 `RDReaderView` 的本地 path 依赖,并设置共享构建参数覆盖 — `Podfile`
**构建设置覆盖:**
- 在 `post_install` 中统一设置 `ENABLE_USER_SCRIPT_SANDBOXING = NO`、`IPHONEOS_DEPLOYMENT_TARGET = 15.6` — `Podfile`、`ReadViewDemo/Podfile`。
## 渲染 / 内嵌 Web 内容
**WKWebView 集成:**
- 使用 `WKWebViewConfiguration` 并设置 `websiteDataStore = .nonPersistent()`;注册自定义 URL scheme handler 以服务 EPUB 资源 — `Sources/RDReaderView/EPUBCore/RDEPUBWebView+Configuration.swift`
- 注入 user script并注册 script message handler 实现 JavaScript bridge — `Sources/RDReaderView/EPUBCore/RDEPUBWebView+Configuration.swift`、`Sources/RDReaderView/EPUBCore/RDEPUBJavaScriptBridge.swift`。
## CI/CD 与部署
**CI 流水线:**
- 未检测到(未发现 `.github/` 或常见 CI 配置文件)。
**部署:**
- 未检测到 App 部署流水线;仓库形态为 iOS SDK + Demo App`RDReaderView.podspec`、`ReadViewDemo/`)。
## 环境配置
**必须的环境变量:**
- 未检测到(未发现 `.env*` 使用,也未发现 `Sources/RDReaderView/**` 中读取环境变量的代码)。
**密钥存放:**
- 基于当前仓库内容检查结果:不适用。
## Webhooks 与回调
**入站:**
- 未检测到。
**出站:**
- 未检测到。
## Evidence关键证据
检查过的关键文件:
- `RDReaderView.podspec`
- `ReadViewDemo/Podfile`
- `ReadViewDemo/Podfile.lock`
- `Podfile`
- `Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBWebView+Configuration.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBJavaScriptBridge.swift`
- `Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`
---
*外部集成审计2026-05-21*

View File

@ -1,82 +0,0 @@
# 技术栈
**分析日期:** 2026-05-21
## 语言
**主要语言:**
- SwiftPodspec 声明 Swift 5.10)— SDK 实现在 `Sources/RDReaderView/**/*.swift`,示例 App 在 `ReadViewDemo/ReadViewDemo/*.swift`
**次要语言:**
- Objective-C — 主要来自示例工程 vendored 的 CocoaPods 依赖源码 `ReadViewDemo/Pods/**`(例如 DTFoundation/DTCoreText
## 运行环境
**平台:**
- iOS — 最低 iOS 15.xSDK 声明 iOS 15.0Demo/Podfile 常见为 15.6)。
**使用到的 Apple Framework不完全列举**
- UIKit — `Sources/RDReaderView/**` 内的 UI 与控制器实现。
- WebKit — EPUB Web 渲染相关配置见 `Sources/RDReaderView/EPUBCore/RDEPUBWebView+Configuration.swift`
- CoreText — 文本分页/渲染支持(`Sources/RDReaderView/EPUBTextRendering/**`)。
- Foundation — 文件系统/持久化等基础能力(`Sources/RDReaderView/**`)。
## 依赖管理
**CocoaPods**
- SDK 以 Podspec 形式发布:`RDReaderView.podspec`。
- 示例工程通过 CocoaPods 集成:`ReadViewDemo/Podfile`、`ReadViewDemo/Podfile.lock`。
- Lockfile 记录的 CocoaPods 版本1.16.2`ReadViewDemo/Podfile.lock`)。
**未检测到:**
- Swift Package Manager未发现 `Package.swift`
- Carthage未发现 `Cartfile`
## 框架与第三方库
**核心库(本仓库):**
- `RDReaderView`(阅读器 UI + EPUB/TXT 阅读能力)— `Sources/RDReaderView/**`
**Pod 声明的第三方依赖:**
- `ZIPFoundation (~> 0.9)` — EPUB 压缩包读取/解压与解析。
- `DTCoreText` — HTML → NSAttributedString 渲染(在 `#if canImport(DTCoreText)` 条件下使用)。
- `SnapKit` — Auto Layout 约束封装。
- `SSAlertSwift` — 弹窗/提示 UI 工具。
## 构建与开发工具
**Xcode 工程(示例 App**
- Workspace/Project`ReadViewDemo/ReadViewDemo.xcworkspace`、`ReadViewDemo/ReadViewDemo.xcodeproj`。
**CocoaPods post_install 构建设置(仓库内配置):**
- 在 Pods 与用户工程上统一设置 `IPHONEOS_DEPLOYMENT_TARGET = 15.6``ENABLE_USER_SCRIPT_SANDBOXING = NO` — 见 `Podfile`、`ReadViewDemo/Podfile`。
## 资源与素材
**资源 bundle**
- Podspec 声明了 `RDReaderViewAssets` 资源 bundle来源为 `Sources/RDReaderView/Resources/**``RDReaderView.podspec`)。
## 平台要求
**开发:**
- 需要 macOS + XcodeiOS SDK构建 Demo workspace/project`ReadViewDemo/ReadViewDemo.xcworkspace`)。
- 需要 CocoaPods 安装 Demo 依赖(`ReadViewDemo/Podfile.lock` 体现了 CocoaPods 使用)。
**发布/分发:**
- 以 CocoaPod 形式分发(`RDReaderView.podspec`)。
## Evidence关键证据
检查过的关键文件:
- `RDReaderView.podspec`
- `Podfile`
- `ReadViewDemo/Podfile`
- `ReadViewDemo/Podfile.lock`
- `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
- `Sources/RDReaderView/EPUBCore/RDEPUBWebView+Configuration.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift`
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBDTCoreTextRenderer.swift`
---
*技术栈分析2026-05-21*

View File

@ -1,149 +0,0 @@
# 代码库结构
**分析日期:** 2026-05-21
## 目录布局
```text
ReadViewSDK/
├── Sources/
│ └── RDReaderView/ # SDK 实现Swift
│ ├── EPUBCore/ # EPUB 解压/解析/模型/分页/状态Foundation/WebKit
│ ├── EPUBTextRendering/ # TXT/TextBook 构建 + 文本渲染/搜索
│ ├── EPUBUI/ # 阅读器控制器 UX、设置、持久化、工具视图
│ ├── LegacyRDReaderController/# 旧版阅读器控制器 + 工具视图
│ ├── Resources/ # 资源pod resource bundle
│ ├── RDReaderView.swift # 核心分页视图 + DS/delegate 协议
│ ├── RDReaderFlowLayout.swift # 滚动模式的 CollectionView 分页布局
│ └── RDURLReaderController.swift # 基于 URL 的入口控制器
├── ReadViewDemo/
│ ├── ReadViewDemo/ # Demo App 源码/资源UIKit
│ ├── ReadViewDemo.xcodeproj/ # Demo target 的 Xcode project
│ ├── ReadViewDemo.xcworkspace/ # 集成 Pods 工程的 workspace
│ ├── Podfile # Demo 的 Pods 集成(本地 path
│ └── Podfile.lock # Demo 的锁定依赖版本
├── Pods/ # 仓库根目录的 CocoaPods 产物(本地开发)
├── Podfile # 仓库级 Pods 集成脚本(见说明)
├── RDReaderView.podspec # SDK 的 Podspec分发与依赖声明
├── Doc/ # 参考资料/分析产物
└── .planning/codebase/ # 生成的代码库地图(本目录)
```
## 目录职责
**`Sources/RDReaderView/EPUBCore`**
- 目的EPUB 解压 + 解析 + 核心模型 + 分页 + 导航状态。
- 关键文件:
- `Sources/RDReaderView/EPUBCore/RDEPUBParser.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBPublication.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingSession.swift`
**`Sources/RDReaderView/EPUBUI`**
- 目的:阅读器 UX 协调与对外 reader controller API。
- 关键文件:
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderConfiguration.swift`
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderPersistence.swift`
**`Sources/RDReaderView/EPUBTextRendering`**
- 目的:从 `.txt` 构建 `RDEPUBTextBook`,并提供渲染/搜索等能力。
- 关键文件:
- `Sources/RDReaderView/EPUBTextRendering/RDPlainTextBookBuilder.swift`
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift`
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift`
**`Sources/RDReaderView`(顶层文件):**
- 目的SDK 的对外入口与核心分页视图/布局基础设施。
- 关键文件:
- `Sources/RDReaderView/RDURLReaderController.swift`
- `Sources/RDReaderView/RDReaderView.swift`
- `Sources/RDReaderView/RDReaderFlowLayout.swift`
**`ReadViewDemo/ReadViewDemo`**
- 目的Demo App用于发现内置书籍并打开 SDK。
- 关键文件:
- `ReadViewDemo/ReadViewDemo/ViewController.swift`
- `ReadViewDemo/ReadViewDemo/AppDelegate.swift`
- `ReadViewDemo/ReadViewDemo/SceneDelegate.swift`
## 关键文件位置
**SDK 入口点:**
- `Sources/RDReaderView/RDURLReaderController.swift`URL 入口epub/txt 路由)。
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`主阅读器控制器EPUB + external TextBook
- `Sources/RDReaderView/RDReaderView.swift`:分页视图与 data source/delegate 协议。
**Demo 入口点:**
- `ReadViewDemo/ReadViewDemo/AppDelegate.swift`App 生命周期入口(`@main`)。
- `ReadViewDemo/ReadViewDemo/SceneDelegate.swift`Window 与 root navigation controller 配置。
- `ReadViewDemo/ReadViewDemo/ViewController.swift`:书籍列表 → 打开 reader。
**配置/打包:**
- `RDReaderView.podspec`SDK 打包(源码 + 资源 + 依赖)。
- `ReadViewDemo/Podfile`Demo 的 Pods 集成(`pod 'RDReaderView', :path => '..'`)。
- `ReadViewDemo/ReadViewDemo.xcworkspace/contents.xcworkspacedata`workspace 结构。
## 命名约定
**模块(目录)划分:**
- `EPUBCore`、`EPUBUI`、`EPUBTextRendering`:按职责分层拆分于 `Sources/RDReaderView/` 下。
**类型前缀:**
- `RD*`:阅读器容器视图与 legacy controller/tooling例如 `RDReaderView`、`RDURLReaderController`)。
- `RDEPUB*`EPUB 解析/分页/阅读器 UI 域(例如 `RDEPUBParser`、`RDEPUBPaginator`、`RDEPUBReaderController` 及相关模型)。
## 组件关系(从入口到渲染)
- `RDURLReaderController` 根据文件类型选择实现:
- `.epub``RDEPUBReaderController(epubURL:configuration:persistence:)`
- `.txt``RDPlainTextBookBuilder``RDEPUBReaderController(textBook:...)`
- 回退路径:分页失败时使用 `UITextView` 展示原始文本
- 入口文件:`Sources/RDReaderView/RDURLReaderController.swift`
- `RDEPUBReaderController` 负责阅读器生命周期:
- parse`RDEPUBParser`)→ publication`RDEPUBPublication`)→ paginate`RDEPUBPaginator`)→ display`RDReaderView`
- 通过 `RDEPUBReaderPersistence` 持久化设置/位置/书签/高亮等
- 入口文件:`Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`
## 新代码应放在哪里
**新增面向读者的 UI 功能(工具视图/菜单/手势):**
- 主要:`Sources/RDReaderView/EPUBUI/`
- 若影响分页呈现:`Sources/RDReaderView/RDReaderView.swift` 或 `Sources/RDReaderView/RDReaderFlowLayout.swift`
**新增 EPUB 解析/模型支持:**
- 主要:`Sources/RDReaderView/EPUBCore/`parser/models/resolver
**新增纯文本导入/渲染行为:**
- 主要:`Sources/RDReaderView/EPUBTextRendering/`
**更新 Demo / 复现步骤:**
- 主要:`ReadViewDemo/ReadViewDemo/`
## 特殊目录说明
**`Pods/` 与 `ReadViewDemo/Pods/`**
- 用途CocoaPods 生成产物,服务本地开发/示例工程。
- 是否生成:是。
- 是否提交:当前工作区中存在(通常按生成目录对待)。
**`Doc/`**
- 用途:文档/分析资料(不属于 SDK 运行时的一部分)。
## Evidence关键证据
检查过的关键文件:
- `RDReaderView.podspec`
- `Podfile`
- `ReadViewDemo/Podfile`
- `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
- `ReadViewDemo/ReadViewDemo.xcworkspace/contents.xcworkspacedata`
- `ReadViewDemo/ReadViewDemo/ViewController.swift`
- `Sources/RDReaderView/RDURLReaderController.swift`
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBParser.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift`
---
*结构分析2026-05-21*

View File

@ -1,71 +0,0 @@
# 测试说明
**分析日期:** 2026-05-21
## 测试框架与现状
**Runner**
- XCTestiOS/Xcode 默认测试框架)
- **当前仓库状态**:未检测到任何 XCTest 测试文件或测试 Target未发现 `import XCTest`/`XCTestCase`,且示例工程 `ReadViewDemo``project.pbxproj` 仅声明应用 Target
**断言库:**
- XCTest 内建断言(当前仓库未见使用案例)
## 测试文件组织
**位置:**
- 未检测到 `*Tests*` 目录或 `*.test.*` / `*.spec.*` 文件(排除 `ReadViewDemo/Pods/**` 第三方依赖源码)。
**命名:**
- 未检测到(无测试用例)
## 如何运行(在当前仓库结构下)
### CocoaPods 依赖准备
> 仓库包含示例工程 `ReadViewDemo`,并已提交 `Pods/``Podfile.lock`。如本地环境未同步,可在仓库根或示例工程目录运行:
```bash
pod install
```
(依赖入口:`Podfile`、`ReadViewDemo/Podfile`
### 运行/构建示例工程
- Xcode 打开:`ReadViewDemo/ReadViewDemo.xcworkspace`
- Scheme/Target 名称从工程文件可见为 `ReadViewDemo`(见 `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
### 运行测试
**当前无测试可运行。** 若未来添加 `ReadViewDemoTests`(或为 SDK 增加独立测试工程/SwiftPM 包),可用 Xcode 或 `xcodebuild test` 运行。
示例(需要存在测试 Scheme/Target 后才有效):
```bash
xcodebuild test \
-workspace ReadViewDemo/ReadViewDemo.xcworkspace \
-scheme ReadViewDemo \
-destination 'platform=iOS Simulator,name=iPhone 15'
```
> 注:本环境中执行 `xcodebuild -list` 发生过 CoreSimulator/日志权限相关错误,属于运行环境限制;测试命令以项目结构为依据给出,实际执行以本机 Xcode/Simulator 可用性为准。
## 覆盖率Coverage
- 未检测到覆盖率配置或现有覆盖率报告产物(例如 `.xcresult` 固化路径或 CI 输出)。
- 若新增 XCTest Target可在 Xcode Scheme 的 Test 设置中启用 Coverage或通过 `xcodebuild test` 生成 `.xcresult` 后用 Xcode 查看。
## Mocking / Fixtures
- 未检测到统一 mocking 框架或 fixtures 目录(无测试用例)。
## Evidence关键证据文件
- `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
- `Podfile`
- `ReadViewDemo/Podfile`
- `ReadViewDemo/Podfile.lock`
- `RDReaderView.podspec`
- `ReadViewDemo/ReadViewDemo/ViewController.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBParser.swift`

View File

@ -1,69 +0,0 @@
{
"model_profile": "balanced",
"commit_docs": true,
"parallelization": true,
"search_gitignored": false,
"brave_search": false,
"firecrawl": false,
"exa_search": false,
"git": {
"branching_strategy": "none",
"phase_branch_template": "gsd/phase-{phase}-{slug}",
"milestone_branch_template": "gsd/{milestone}-{slug}",
"quick_branch_template": null
},
"workflow": {
"research": true,
"plan_check": true,
"verifier": true,
"nyquist_validation": true,
"auto_advance": true,
"node_repair": true,
"node_repair_budget": 2,
"ui_phase": true,
"ui_safety_gate": true,
"text_mode": false,
"research_before_questions": false,
"discuss_mode": "discuss",
"skip_discuss": false,
"code_review": true,
"code_review_depth": "standard"
},
"ship": {
"pr_body_sections": [
{
"heading": "User Stories & Acceptance Criteria",
"enabled": true,
"source": "REQUIREMENTS.md ## User Stories || REQUIREMENTS.md ## Acceptance Criteria",
"fallback": "- 验收标准以关联的 REQUIREMENTS 与验证证据为准。"
},
{
"heading": "Risks & Dependencies",
"enabled": true,
"source": "PLAN.md ## Risks || PLAN.md ## Dependencies",
"fallback": "- 当前无已知高风险依赖。"
},
{
"heading": "Success Metrics & Release Criteria",
"enabled": true,
"source": "REQUIREMENTS.md ## Definition of Done || VERIFICATION.md ## Release Criteria",
"fallback": "- 当自动化验证与必要的手工检查通过后发布。"
},
{
"heading": "Stakeholder Review & Approval",
"enabled": false,
"template": "- 需要 {phase_name} 的产品/负责人审批。"
}
]
},
"hooks": {
"context_warnings": true
},
"project_code": null,
"phase_naming": "sequential",
"agent_skills": {},
"features": {},
"resolve_model_ids": "omit",
"mode": "yolo",
"granularity": "coarse"
}

View File

@ -1,83 +0,0 @@
# 需求归档ReadViewSDK v1.0
**归档日期:** 2026-05-22
**核心价值:** 稳定可用的 EPUB/TXT 阅读体验
## 结果说明
本归档按 milestone close 生成。v1.0 的实现与运行时证据整体达成,但由于 close-out 前未完全回写 requirement bookkeeping以下需求状态分为
- `Validated`实现、phase verification、summary metadata 三者一致
- `Delivered with accepted gaps`:实现和运行时证据存在,但 requirement bookkeeping 未完全对齐,作为已接受的归档缺口保留
## v1 Requirements
### 渲染内核重构Reflowable EPUB
- [x] **REND-01**:直接重构当前 `.textReflowable` 路径,使 reflowable EPUB 不再依赖当前“简单 `DTCoreText` renderer + `pageRanges` 切页”模式,而是具备 WXRead 风格的页面级原生排版能力
- [x] **REND-02**:在旧引擎基础上引入 WXRead 风格的 CSS 分层策略(`default / replace / dark / epub / user`),并让样式作用于章节级 HTML → `NSAttributedString` 转换过程
- [x] **REND-03**:在旧引擎基础上引入自定义 DTCoreText 属性体系与页面级 `NSAttributedString` 元数据,能够承载分页、块元素、图片、页面语义等布局信息
- [x] **REND-04**:将当前简单的 CoreText 切页逻辑升级为具备页面语义的复杂分页器,具备与 `WRCoreTextLayouter / WRCoreTextLayoutFrame` 核心能力等价的分页与页面布局控制能力
### 兼容性与主流程
- [x] **COMP-01**`RDURLReaderController` / `RDEPUBReaderController` 作为公开入口继续可用,`.epub` / `.txt` 打开主流程不回归
- [x] **COMP-02**Fixed Layout EPUB 与交互式 EPUB 继续使用 `WKWebView`,行为不因本次改造产生回归
- [x] **COMP-03**reflowable EPUB 的阅读位置映射、高亮/选区、搜索结果定位、字号/行高/主题切换后的重新分页在新内核下继续可用
- [x] **COMP-04**:当前翻页代码(`RDReaderView` 及现有 page curl / horizontal scroll / vertical scroll 交互逻辑)不做修改,新内核必须适配既有翻页容器
### 稳定性与验证
- [x] **STAB-01**:至少 3 类样本书验证通过:纯文本/小说类、含图片与复杂段落样式的章节、含外链与多个 CSS 文件引用的章节
- [x] **STAB-02**:以上样本在新内核下不出现崩溃、白屏、无限加载、严重错页或关键交互链路失效
## Requirement Outcomes
| Requirement | Archived Outcome | Notes |
|-------------|------------------|-------|
| REND-01 | Delivered with accepted gaps | Phase 2 established renderer/context path; audit still flagged bookkeeping incompleteness. |
| REND-02 | Delivered with accepted gaps | Phase 2 verification marked it satisfied; archive accepts missing checkbox sync. |
| REND-03 | Delivered with accepted gaps | Phase 3 implemented page metadata; requirement-level verification mapping was missing. |
| REND-04 | Delivered with accepted gaps | Phase 3 delivered stronger pagination semantics; requirement bookkeeping remained orphaned. |
| COMP-01 | Delivered with accepted gaps | Phase 4 restored reader main flow, but requirement mapping was not backfilled. |
| COMP-02 | Validated | Phase 1 fully documented and verified the `WKWebView` retention boundary. |
| COMP-03 | Delivered with accepted gaps | Phase 4 runtime evidence supports compatibility, though close-out evidence chain was incomplete. |
| COMP-04 | Delivered with accepted gaps | `RDReaderView` remained untouched across the milestone, but requirement metadata was not reconciled. |
| STAB-01 | Delivered with accepted gaps | Phase 5 5-book matrix covers required categories. |
| STAB-02 | Delivered with accepted gaps | Phase 5 runtime/UI evidence shows no sampled crash/blank-page regression. |
## Out of Scope
| 功能 | 原因 |
|---|---|
| Fixed Layout EPUB 改为原生渲染 | 本次明确保留 `WKWebView` 路径以控制风险 |
| 交互式 EPUB 改为原生渲染 | 交互能力JS/音视频/表单/iframe/外链/bridge更适配 `WKWebView`,本次不改 |
| 修改当前翻页代码(`RDReaderView` / 现有翻页模式与交互逻辑) | 本次只重构 reflowable 渲染内核,不把翻页容器一起纳入改造 |
| 直接拷贝使用读书私有 JS/CSS/私有实现代码 | 只能参考设计与行为,不直接搬运私有实现 |
| 同时保留两套 reflowable 原生引擎 | 本次要求直接演进旧引擎,不维护双轨 |
## Traceability
| Requirement | Phase | Final Status |
|-------------|-------|--------------|
| REND-01 | Phase 2 | Delivered with accepted gaps |
| REND-02 | Phase 2 | Delivered with accepted gaps |
| REND-03 | Phase 3 | Delivered with accepted gaps |
| REND-04 | Phase 3 | Delivered with accepted gaps |
| COMP-01 | Phase 4 | Delivered with accepted gaps |
| COMP-02 | Phase 1 | Validated |
| COMP-03 | Phase 4 | Delivered with accepted gaps |
| COMP-04 | Phase 4 | Delivered with accepted gaps |
| STAB-01 | Phase 5 | Delivered with accepted gaps |
| STAB-02 | Phase 5 | Delivered with accepted gaps |
**Coverage:**
- v1 requirements: 10 total
- Archived as shipped: 10
- Strict audit passed without gaps: 1
- Archived with accepted evidence gaps: 9
---
*Requirements defined: 2026-05-21*
*Archived: 2026-05-22 after milestone close with accepted audit gaps*

View File

@ -1,139 +0,0 @@
# Milestone v1.0: WXRead Native Reflowable Foundation
**Status:** ✅ SHIPPED 2026-05-22
**Phases:** 1-5
**Total Plans:** 13
## Overview
v1.0 completed the direct evolution of the existing reflowable EPUB native path instead of introducing a parallel engine. The milestone established chapter-level CSS preprocessing, richer page metadata, a stronger paginator, reader-shell reintegration, and sample-corpus regression evidence across native reflowable, fixed/interactive WebKit, and TXT flows.
The milestone was archived with accepted audit gaps: the runtime and source evidence indicate the implementation is broadly complete, but requirement bookkeeping in `REQUIREMENTS.md`, `VERIFICATION.md`, and `SUMMARY.md` was not fully reconciled before close-out.
## Phases
### Phase 1: 对齐现状、边界与重构切入点
**Goal**: 把“当前旧引擎是什么、哪些能力必须保留、哪些路径绝对不能动”说清楚,形成直接重构旧引擎的实施基线。
**Depends on**: Nothing (first phase)
**Plans**: 2 plans
Plans:
- [x] 01-01审计当前 `.textReflowable` 路径(`RDEPUBDTCoreTextRenderer` / `RDEPUBTextBookBuilder` / `RDEPUBTextPaginationSupport` / `RDEPUBTextContentView`
- [x] 01-02结合 `Doc/WXRead/analysis/*` 提炼旧引擎可直接演进的切入点与必须保留的兼容链路
**Details:**
- 固定了 native `.textReflowable` 的真实调用链和 `WKWebView` 分流边界。
- 把 `RDReaderView` 明确记录为稳定容器,不纳入这轮重构。
- 产出了后续 Phase 2-4 的实施顺序和硬边界。
### Phase 2: 重构 typesetter 与 CSS 分层
**Goal**: 在现有旧引擎基础上引入 WXRead 风格的 CSS 分层与章节级 HTML → attributed string 增强,让 renderer 输入具备更完整的排版语义。
**Depends on**: Phase 1
**Plans**: 3 plans
Plans:
- [x] 02-01设计并实现旧引擎中的 WXRead 风格 stylesheet builder / HTML 预处理增强
- [x] 02-02改造 `RDEPUBDTCoreTextRenderer` 与相邻渲染链路,使其承接新的样式分层与章节上下文
- [x] 02-03验证章节级图片/CSS/基础资源在新渲染输入下可正常解析
**Details:**
- 建立了 `default / replace / dark / epub / user` 五层 CSS 顺序。
- 把 chapter preprocessing、baseURL、linked CSS 内联、资源标准化接入 native renderer。
- 用 demo 样本书验证了 reflowable 章节资源解析。
### Phase 3: 重构属性体系与复杂分页器
**Goal**: 在旧引擎路径中引入页面级 attributed string 元数据与更复杂的分页/页面布局能力,替代当前简单 `pageRanges` 切页模式。
**Depends on**: Phase 2
**Plans**: 3 plans
Plans:
- [x] 03-01定义并实现页面级 attributed string 元数据与自定义属性键
- [x] 03-02在旧引擎基础上重构分页器使其具备接近 `WRCoreTextLayouter / WRCoreTextLayoutFrame` 的核心能力
- [x] 03-03验证复杂块元素、图片与分页边界控制在新分页器下可工作
**Details:**
- 引入了页面元数据、attachment/block break reasons、layout frame 语义。
- 保持 `pageStartOffset`、`pageEndOffset`、`fragmentOffsets`、`RDEPUBTextOffsetRangeInfo` 兼容不变。
- 在真实 EPUB 上输出分页诊断,证明新分页语义已生效。
### Phase 4: 接回现有 reader 能力链路
**Goal**: 让新内核在不新增并行原生引擎、且不修改当前翻页代码的前提下,继续服务现有 reader UI、阅读位置、高亮、搜索与主题切换能力。
**Depends on**: Phase 3
**Plans**: 3 plans
Plans:
- [x] 04-01将新内核接回 `RDEPUBTextBookBuilder` / `RDEPUBTextContentView` / `RDEPUBReaderController`,不修改 `RDReaderView`
- [x] 04-02修复并验证阅读位置映射、高亮、搜索等兼容能力
- [x] 04-03验证字体、行高、主题切换后的重新分页与状态恢复
**Details:**
- native text backend 被接回现有 reader shell`RDReaderView` 保持不变。
- 位置恢复、高亮、搜索、TOC、重分页行为围绕 absolute offset 契约继续工作。
- demo 输出恢复诊断,证明 semantic location 在主题/字号变化后仍可恢复。
### Phase 5: 回归验证与稳定性收敛
**Goal**: 围绕样本书和主流程做回归,收敛分页正确性、位置映射稳定性与关键阅读交互问题。
**Depends on**: Phase 4
**Plans**: 2 plans
Plans:
- [x] 05-01构建样本书验证矩阵与诊断手段日志/断言/复现清单)
- [x] 05-02收敛分页、位置映射、图片/块元素分页与主题切换后的稳定性问题
**Details:**
- demo 启动摘要扩展为 5 本样本书的矩阵验证。
- 覆盖 native reflowable、fixed/interactive WebKit、TXT 三条主路径。
- 运行时证据确认 `样本验证5/5 通过`,并保留分页/恢复诊断。
---
## Milestone Summary
**Decimal Phases:**
- None
**Key Decisions:**
- 选择直接演进现有 `.textReflowable` 原生引擎,而不是引入并行原生引擎。
- Fixed Layout 与交互式 EPUB 继续保留 `WKWebView` 路径。
- `RDReaderView` 作为稳定分页容器不纳入本轮改造范围。
- 兼容链路继续围绕 offset-based location/highlight/search/restore 语义维持。
**Issues Resolved:**
- chapter-level CSS 分层、preprocessing 和资源标准化接入 native renderer。
- 分页器从纯 visible-range slicing 升级为带 block/attachment-aware 语义的 layouter path。
- native reader shell 与位置恢复、高亮、搜索、主题/字号切换重新打通。
- demo 建立了覆盖 reflowable / WebKit / TXT 的统一样本矩阵。
**Issues Deferred:**
- requirement bookkeeping 未在 milestone close 前完全回写,详见 `v1.0-MILESTONE-AUDIT.md`
- 尚无完整 UI 自动化覆盖所有样本和关键交互。
- Nyquist validation 文档仍存在 draft / partial 状态。
**Technical Debt Incurred:**
- `REQUIREMENTS.md`、`VERIFICATION.md`、`SUMMARY.md` 的 requirement evidence chain 需要后续补齐。
- simulator 运行仍会出现既有 `.SFUI-Semibold` CoreText substitution note。
---
_For current project status, see `.planning/ROADMAP.md`_

View File

@ -1,76 +0,0 @@
---
phase: 6
plan: 06-01
type: execute
wave: 1
depends_on: []
files_modified:
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
autonomous: true
requirements:
- LAYOUT-01
- LAYOUT-03
---
# Phase 6-01: Page Geometry Model
<objective>
Add a reusable page geometry layer on top of native text pagination so callers can query page-relative rectangles and map rectangles back to text ranges without breaking offset continuity.
</objective>
<must_haves>
- `RDEPUBTextLayoutFrame` can expose page geometry derived from CoreText, not guessed from offsets.
- `pageStartOffset`, `pageEndOffset`, `fragmentOffsets`, and `RDEPUBTextOffsetRangeInfo` semantics remain stable.
- The geometry API is reusable by selection, search, highlight, and tap-locate work in later plans.
</must_haves>
<tasks>
<task id="06-01-01">
<type>execute</type>
<action>Extend `RDEPUBTextLayoutFrame` and the page model with explicit geometry value types, including a page-level geometry container and line or fragment geometry records. Populate them from `RDEPUBTextLayouter` using CoreText line data so the page can answer range-to-rect and rect-to-range queries without changing pagination break rules.</action>
<read_first>
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
</read_first>
<acceptance_criteria>
- `RDEPUBTextLayoutFrame` or its companion geometry type exposes a query path for at least string-range rectangles and reverse lookup from rects to `NSRange`.
- Existing metadata fields (`contentRange`, `breakReason`, `blockRange`, `attachmentRanges`, `attachmentKinds`, `trailingFragmentID`, `diagnostics`) remain present and unchanged in meaning.
- `RDEPUBTextLayouter` still emits the same page boundaries for the sample books after the geometry data is added.
</acceptance_criteria>
</task>
<task id="06-01-02">
<type>execute</type>
<action>Thread the new geometry data through `RDEPUBTextBookBuilder` and `RDEPUBTextBook` so each page retains its geometry alongside `pageStartOffset`, `pageEndOffset`, and `fragmentOffsets`. Keep `pageNumber(for:)` and `location(forPageNumber:)` compatible with the existing absolute-offset contract.</action>
<read_first>
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
- Sources/RDReaderView/LegacyRDReaderController/RDEPUBTextPaging.swift
</read_first>
<acceptance_criteria>
- `RDEPUBTextBook` pages still map absolute offsets to pages through `pageStartOffset` / `pageEndOffset`.
- `RDEPUBTextBook.location(forPageNumber:)` still returns a stable `RDEPUBLocation` for native text pages.
- The sample text book builds successfully with the new geometry fields attached to each page.
</acceptance_criteria>
</task>
</tasks>
<verification>
- Build the `ReadViewDemo` workspace with the `ReadViewDemo` scheme.
- Confirm the new page geometry API compiles and the sample book still paginates.
- Confirm no existing offset-based selection or restore code needs to change to keep building.
</verification>
<success_criteria>
- Native text pages expose reusable geometry data.
- The offset-based page contract remains intact.
- Later selection overlay work can consume the geometry layer without re-deriving page boundaries.
</success_criteria>

View File

@ -1,19 +0,0 @@
---
phase: 6
plan: 06-01
status: complete
requirements-completed:
- LAYOUT-01
- LAYOUT-03
updated: 2026-05-22
---
# 06-01 Summary
- Added `RDEPUBTextPageGeometry` value types and threaded page geometry through `RDEPUBTextLayoutFrame`, `RDEPUBTextPage`, and both text book builders.
- Geometry now comes from CoreText line offsets instead of inferred page offsets, while `pageStartOffset`, `pageEndOffset`, `fragmentOffsets`, and `RDEPUBTextOffsetRangeInfo` semantics remain unchanged.
- Added reusable page query helpers for range-to-rect and rect or point back to absolute text ranges.
## Verification
- `build_sim` for `ReadViewDemo` on iOS Simulator succeeded on 2026-05-22.

View File

@ -1,76 +0,0 @@
---
phase: 6
plan: 06-02
type: execute
wave: 2
depends_on:
- 06-01
files_modified:
- Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBSelectionOverlayView.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
autonomous: true
requirements:
- LAYOUT-02
- LAYOUT-03
---
# Phase 6-02: Selection Overlay and Hit Flow
<objective>
Move native text selection presentation onto a custom overlay backed by page geometry while keeping the controller-owned selection state, persistence, and absolute offset payload unchanged.
</objective>
<must_haves>
- Selection rendering is driven by overlay geometry, not by the default `UITextView` selection chrome.
- `RDEPUBReaderController` remains the single owner of current selection, persistence, and menu actions.
- Selections still round-trip through `RDEPUBTextOffsetRangeInfo` and preserve absolute offsets.
</must_haves>
<tasks>
<task id="06-02-01">
<type>execute</type>
<action>Add `RDEPUBSelectionOverlayView` and embed it in `RDEPUBTextContentView` as the visual selection surface. Use the page geometry from 06-01 to draw the selected range and page-local hit regions, while leaving `UITextView` as the text host and input source.</action>
<read_first>
- Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
</read_first>
<acceptance_criteria>
- A dedicated overlay view or layer exists for native selection presentation.
- Overlay updates when a new selection is made, when the page is reconfigured, and when selection is cleared.
- The visible selection treatment no longer depends on `UITextView`'s default selection chrome as the primary presentation path.
</acceptance_criteria>
</task>
<task id="06-02-02">
<type>execute</type>
<action>Update the `RDEPUBTextContentView` delegate flow so selection changes still produce `RDEPUBSelection` objects with absolute offsets, `RDEPUBReaderController` still normalizes and persists them, and copy/highlight/annotate menu actions continue to work through the same controller-owned selection state.</action>
<read_first>
- Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
</read_first>
<acceptance_criteria>
- `currentSelection` still updates when the user changes the selection.
- Selection menu actions still route through the controller and continue to create highlights or annotations.
- Clearing the selection clears both the overlay state and the controller's current selection.
</acceptance_criteria>
</task>
</tasks>
<verification>
- Build and run `ReadViewDemo` on the simulator.
- Select text in a native reflowable sample and confirm the overlay is the visible selection surface.
- Trigger copy/highlight/annotate actions and confirm the controller still receives a valid selection payload.
</verification>
<success_criteria>
- Selection presentation is overlay-backed.
- Selection state still round-trips through absolute offsets.
- Reader interaction behavior remains stable for native text pages.
</success_criteria>

View File

@ -1,19 +0,0 @@
---
phase: 6
plan: 06-02
status: complete
requirements-completed:
- LAYOUT-02
- LAYOUT-03
updated: 2026-05-22
---
# 06-02 Summary
- Added `RDEPUBSelectionOverlayView` and mounted it above the native text host so visible selection rendering is driven by page geometry.
- Preserved the controller-owned selection contract: selections still normalize through `RDEPUBSelection`, absolute offsets still serialize through `RDEPUBTextOffsetRangeInfo`, and menu actions still flow through `RDEPUBReaderController`.
- Clearing or reconfiguring a page now clears both overlay state and controller selection state.
## Verification
- `build_sim` for `ReadViewDemo` on iOS Simulator succeeded on 2026-05-22.

View File

@ -1,78 +0,0 @@
---
phase: 6
plan: 06-03
type: execute
wave: 3
depends_on:
- 06-01
- 06-02
files_modified:
- ReadViewDemo/ReadViewDemo/ViewController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
autonomous: true
requirements:
- LAYOUT-01
- LAYOUT-02
- LAYOUT-03
---
# Phase 6-03: Geometry Verification and Diagnostics
<objective>
Expose concrete demo diagnostics for the new geometry and selection overlay path, then verify that page geometry, restore, search, and selection remain compatible on real sample books.
</objective>
<must_haves>
- The demo can report geometry and selection evidence for a native reflowable page.
- Offset-based restore and page lookup continue to resolve the same content after geometry and overlay changes.
- Any geometry regression is visible in simulator logs or the demo status text.
</must_haves>
<tasks>
<task id="06-03-01">
<type>execute</type>
<action>Add a geometry diagnostic hook to `RDEPUBReaderController` or `RDEPUBTextContentView` that reports the active page index, the selected absolute offset range, and the geometry summary for the current native page. Keep the diagnostic format deterministic so the demo can surface it in startup logs.</action>
<read_first>
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
</read_first>
<acceptance_criteria>
- A runtime call can produce a geometry summary string for the current native page.
- The summary includes the selected absolute range or an explicit no-selection state.
- The summary is deterministic enough to compare across rebuilds on the same sample book.
</acceptance_criteria>
</task>
<task id="06-03-02">
<type>execute</type>
<action>Extend `ReadViewDemo/ViewController.swift` startup validation so the native reflowable sample output includes the new geometry summary alongside the existing pagination and restore diagnostics. Keep the TXT and fixed/interactive matrix paths intact.</action>
<read_first>
- ReadViewDemo/ReadViewDemo/ViewController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
</read_first>
<acceptance_criteria>
- The simulator startup log includes a geometry/selection summary for at least one native reflowable sample.
- The existing sample validation matrix still reports the native, fixed/interactive, and TXT paths.
- Font or theme changes still preserve the same href and absolute-offset semantics in the restore diagnostic output.
</acceptance_criteria>
</task>
</tasks>
<verification>
- Build and launch `ReadViewDemo` in the simulator.
- Open a native reflowable sample, select text, and confirm the geometry summary matches the overlay selection.
- Change font size or theme and confirm restore diagnostics still report stable href and offset behavior.
</verification>
<success_criteria>
- Geometry and overlay behavior are visible in the demo.
- Selection, restore, and sample validation remain compatible after the phase 6 changes.
- The phase produces reusable diagnostics for later phases without requiring a second demo shell.
</success_criteria>

View File

@ -1,21 +0,0 @@
---
phase: 6
plan: 06-03
status: complete
requirements-completed:
- LAYOUT-01
- LAYOUT-02
- LAYOUT-03
updated: 2026-05-22
---
# 06-03 Summary
- Added deterministic native text geometry summaries on `RDEPUBTextPage` and `RDEPUBReaderController`.
- Extended `ReadViewDemo` startup validation to emit pagination, restore, and geometry diagnostics for native reflowable samples while keeping the fixed/interactive and TXT matrix intact.
- Verified simulator logs now surface geometry evidence for a real sample page with explicit `selection none` output.
## Verification
- `build_run_sim` for `ReadViewDemo` on iPhone 17 (iOS 26.5 simulator) succeeded on 2026-05-22.
- Runtime log included `几何诊断:宝山辽墓材料与释读 · page 40 · href Text/Chapter_4_2.xhtml · range {1056, 227} · lines 13 · fragments 227 · selection none`.

View File

@ -1,102 +0,0 @@
# Phase 6: 页面几何与交互命中层 - Context
**Gathered:** 2026-05-22
**Status:** Ready for planning
<domain>
## Phase Boundary
为 native text 分页结果建立可复用的页面级 layout frame 几何能力,并把 reader 的命中、选区和定位行为逐步迁移到显式几何层,而不是继续主要依赖 `UITextView` 的黑盒行为。此阶段不替换 `RDReaderView`fixed / interactive EPUB 继续走 `WKWebView`,并且必须保持 `pageStartOffset`、`pageEndOffset`、`fragmentOffsets`、`RDEPUBTextOffsetRangeInfo` 的既有语义稳定。
</domain>
<decisions>
## Implementation Decisions
### Geometry Coverage
- **D-01:** 几何 API 以 `selection` 为第一优先级,但实现不能停留在单点能力上;页面几何层应至少覆盖字符串范围矩形查询、矩形反查文本范围、截断检测、命中定位所需的基础 API。
- **D-02:** 用户明确希望前两项讨论点都“全做”,因此 Phase 6 的几何层不能只做 selection 的局部补丁,而要把 selection 相关的几何查询做成可复用、可持续扩展的基础层。
### Interaction Migration
- **D-03:** 第一条迁移链路选择 `selection`。Phase 6 优先把选区范围获取、选区命中、选区展示和 offset 归一化迁移到 layout frame 几何层。
- **D-04:** 搜索命中、高亮和点击定位保持兼容,但不作为本阶段的主迁移链路;它们应当复用同一套几何接口,而不是各自再造一层逻辑。
### Display Strategy
- **D-05:** 展示策略选择 `custom overlay`。`UITextView` 继续承担基础文本布局/输入能力,但选区和命中展示不应继续绑定在它的黑盒 selection 表现上。
- **D-06:** overlay 方案必须与现有 offset-based 语义对齐,不能引入只可视不可追踪的新状态。
### Geometry Precision
- **D-07:** 精度优先级选择 `glyph 级精度`。在兼容性不被破坏的前提下,优先追求更精确的 glyph/fragment 级几何,而不是只做到粗粒度 block 级命中。
- **D-08:** 兼容性要求仍然保留,但仅作为精度实现的约束条件,不作为本阶段的目标上限。
### the agent's Discretion
- `search`、`highlight`、`tap locate` 在 Phase 6 中保持可接入状态;如果实现 selection 几何时顺手能抽出共享接口,可以一并收口,但不允许为了覆盖面而重写 reader 展示层。
</decisions>
<canonical_refs>
## Canonical References
**Downstream agents MUST read these before planning or implementing.**
### Milestone framing
- `.planning/ROADMAP.md` — Phase 6 的目标、依赖、成功标准与 cross-cutting constraints
- `.planning/REQUIREMENTS.md` — LAYOUT-01 / LAYOUT-02 / LAYOUT-03 的具体要求与 out-of-scope 约束
- `.planning/STATE.md` — 当前里程碑、当前 phase 和规划状态
### Native pagination and geometry pipeline
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` — 当前分页 frame 的生成、断页原因、attachment/block 诊断逻辑
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift` — 现有 page frame 结构与元数据承载点
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift` — 现有分页支持入口和 page range 适配
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` — page / offset continuity 的构建逻辑
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift``pageStartOffset`、`pageEndOffset`、`fragmentOffsets`、`RDEPUBTextOffsetRangeInfo` 等核心语义
### Reader integration
- `Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift` — 当前 `UITextView` selection、highlight 与 offset overlap 逻辑
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift` — reader 状态编排、位置恢复、搜索和高亮接线点
No external specs — requirements are fully captured in decisions above
</canonical_refs>
<code_context>
## Existing Code Insights
### Reusable Assets
- `RDEPUBTextLayoutFrame` already carries content range, break reason, block range, attachment ranges, attachment kinds and diagnostics; it is the natural home for extra geometry fields.
- `RDEPUBTextLayouter` already has a stable frame-generation pipeline and can be extended without changing the upstream chapter preprocessing contract.
- `RDEPUBTextBookBuilder` already preserves absolute offsets and fragment continuity, which keeps selection and restore compatible with later geometry work.
- `RDEPUBReaderController` already centralizes reader state and interaction orchestration, so selection migration should route through it instead of creating a parallel controller.
### Established Patterns
- Offset-based consumers already rely on `pageStartOffset` / `pageEndOffset` / `fragmentOffsets` rather than page-local ad hoc state.
- Existing highlight and search rendering are driven by offset overlap, which is a useful bridge for moving selection to a geometry-backed overlay.
- Native reflowable EPUB remains the primary target for deeper internals; fixed / interactive EPUB stays on `WKWebView`.
### Integration Points
- Geometry APIs should live next to the page frame and pagination support code, not inside the reader view shell.
- Selection overlay work must integrate with `RDEPUBTextContentView` and the controller flow that already owns selection restore and highlight updates.
- Any new geometry result type should be consumable by future search/highlight/tap-locate work without duplicating page traversal or offset math.
</code_context>
<specifics>
## Specific Ideas
- The user wants Phase 6 to be selection-first and to complete that path fully, not as a partial shim.
- The user prefers a custom overlay for selection presentation rather than continuing to lean on `UITextView` selection visuals.
- The geometry target is glyph-level precision, with compatibility kept as a constraint rather than the primary target.
</specifics>
<deferred>
## Deferred Ideas
None — the discussion stayed within Phase 6 scope. `search` / `highlight` / `tap locate` remain compatible consumers of the same geometry layer, but they are not the primary migrated chain in this phase.
</deferred>
---
*Phase: 6-页面几何与交互命中层*
*Context gathered: 2026-05-22*

View File

@ -1,71 +0,0 @@
# Phase 6: 页面几何与交互命中层 - Discussion Log
> **Audit trail only.** Do not use as input to planning, research, or execution agents.
> Decisions are captured in CONTEXT.md — this log preserves the alternatives considered.
**Date:** 2026-05-22
**Phase:** 6-页面几何与交互命中层
**Areas discussed:** Geometry Coverage, Interaction Migration, Display Strategy, Geometry Precision
---
## Geometry Coverage
| Option | Description | Selected |
|--------|-------------|----------|
| `selection` | Prioritize selection geometry first | ✓ |
| `search / highlight / tap locate` | Prioritize other interaction geometry first | |
| `all` | Spread coverage across all consumers immediately | |
**User's choice:** `selection`
**Notes:** User additionally said the first two discussion areas should be fully done, so this is not a thin one-off patch.
---
## Interaction Migration
| Option | Description | Selected |
|--------|-------------|----------|
| `selection` | Migrate selection range / hit / display flow first | ✓ |
| `search hit` | Migrate search hit resolution first | |
| `highlight paint` | Migrate highlight painting first | |
| `tap locate` | Migrate tap / point locate first | |
**User's choice:** `selection`
**Notes:** The selection chain is the first reader interaction to move onto the geometry layer.
---
## Display Strategy
| Option | Description | Selected |
|--------|-------------|----------|
| `custom overlay` | Add a dedicated overlay for selection/highlight rendering | ✓ |
| `UITextView only` | Keep all display logic inside `UITextView` selection behavior | |
| `hybrid` | Use `UITextView` plus overlay only for a subset | |
**User's choice:** `custom overlay`
**Notes:** Overlay is preferred for selection presentation; `UITextView` should not remain the main black-box selection renderer.
---
## Geometry Precision
| Option | Description | Selected |
|--------|-------------|----------|
| `glyph 级精度` | Prefer precise glyph-level geometry and reverse mapping | ✓ |
| `block 级兼容` | Prefer coarse block-level compatibility first | |
| `balanced` | Stop at whatever precision is easiest to ship | |
**User's choice:** `glyph 级精度`
**Notes:** Compatibility remains a constraint, but precision is the target.
---
## the agent's Discretion
- Keep `search` / `highlight` / `tap locate` compatible with the same geometry layer, but do not make them the primary migration target for this phase.
## Deferred Ideas
- Broader interaction migration beyond selection can reuse the same geometry layer in later work.

View File

@ -1,39 +0,0 @@
# Phase 6: 页面几何与交互命中层 - Patterns
## Reusable Patterns
### Offset continuity is already the compatibility contract
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` and `Sources/RDReaderView/LegacyRDReaderController/RDEPUBTextPaging.swift` both preserve `pageStartOffset`, `pageEndOffset`, and `fragmentOffsets`.
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift` keeps `RDEPUBTextOffsetRangeInfo` as the absolute-offset payload used by selection and highlight consumers.
- Phase 6 should keep that contract intact even after a geometry overlay is introduced.
### The layouter already knows more than the view layer
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` already determines `blockRange`, `attachmentRanges`, `attachmentKinds`, `breakReason`, and `trailingFragmentID`.
- That makes the layouter the right place to enrich `RDEPUBTextLayoutFrame` with queryable page geometry instead of re-deriving page rules inside `RDEPUBTextContentView`.
### Reader coordination already belongs to the controller
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift` already owns selection persistence, current-location updates, highlight creation, search state, and repagination.
- Any new geometry-backed selection flow should plug into the controller rather than creating a second reader state owner.
### Content view should become a thin host
- `Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift` currently mixes display, selection, highlight painting, and offset conversion.
- For this phase, the safest direction is to let the view host text plus an overlay and keep the selection model conversion in one place.
## Closest Existing Analogs
- `RDEPUBTextLayoutFrame` is the natural home for page geometry metadata.
- `RDEPUBTextBookBuilder` is the natural place to lift geometry results into page-level book state.
- `RDEPUBReaderController` is the natural adapter layer for user interactions and persistence.
- `RDEPUBTextContentView` is the natural host for an overlay layer because it already owns the page view composition.
## Design Guardrails
- Do not move fixed/interactive EPUB off `WKWebView`.
- Do not change `RDReaderView`.
- Do not break the existing offset-based consumers while introducing geometry queries.
- Do not let search/highlight/tap-locate become separate geometry implementations; they should reuse the same page geometry API later.

View File

@ -1,45 +0,0 @@
# Phase 6: 页面几何与交互命中层 - Research
**Date:** 2026-05-22
**Phase:** 6
## Research Question
What do we need to know to plan page geometry and interaction hit handling well for the native text path?
## Current State
- `Sources/RDReaderView/EPUBUI/RDEPUBTextContentView.swift` still renders native text through `UITextView` and derives selection from `selectedRange`.
- `RDEPUBTextContentView` currently converts the selected range into `RDEPUBSelection` by using page-relative offsets plus `RDEPUBTextOffsetRangeInfo` absolute offsets.
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift` normalizes selections, persists them, and remains the central coordination point for reader interactions.
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` already computes page boundaries, break reasons, block ranges, attachment ranges, and trailing fragment IDs from CoreText frames.
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift` is currently only a metadata wrapper around `contentRange` plus pagination diagnostics.
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` preserves absolute offsets, page continuity, and fragment offsets when assembling `RDEPUBTextBook`.
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift` already keeps the offset-based reader contract alive through `pageStartOffset`, `pageEndOffset`, `fragmentOffsets`, and `RDEPUBTextOffsetRangeInfo`.
## What This Means
1. The missing abstraction is a page-level geometry layer, not a new pagination pipeline.
2. The right insertion point is beside the layout frame / pagination code, because that layer already knows page boundaries and fragment continuity.
3. Selection should move first because the current user decision explicitly made selection the primary migrated interaction chain.
4. `custom overlay` is the right display model for Phase 6 because `UITextView` selection visuals are still the black-box dependency we are trying to reduce.
5. Precision target should be glyph-level or fragment-level geometry, with the existing offset contract kept as the compatibility anchor.
## Recommended Planning Shape
- **Plan 06-01:** add page geometry query APIs to the page frame / book layer.
- **Plan 06-02:** move selection presentation and hit handling onto a custom overlay while keeping offset-based selection data intact.
- **Plan 06-03:** verify selection geometry, offset continuity, and restore/search/highlight compatibility across the existing sample books.
## Technical Risks
- `UITextView` can provide selection behavior, but it is not a reliable source for a stable custom overlay pipeline if the overlay needs richer glyph-level rects.
- If geometry is bolted into the reader controller, the phase will become a UI-layer patch instead of a reusable page geometry layer.
- Any new geometry result must remain consumable by future `search`, `highlight`, and `tap locate` work without re-deriving offsets or page boundaries.
## Validation Implications
- There is no dedicated test target in the repo, so plan verification will need to rely on simulator build/run plus observable runtime behavior.
- The phase should define concrete UI and log checks for selection overlay behavior, offset preservation, and current-location compatibility.
- The verification strategy should keep one manual check for glyph-level selection/overlay behavior because that is the user-visible risk area for this phase.

View File

@ -1,80 +0,0 @@
---
phase: 6
slug: page-geometry-and-interaction-hit-layer
status: draft
nyquist_compliant: true
wave_0_complete: false
created: 2026-05-22
---
# Phase 6 — Validation Strategy
> Per-phase validation contract for page geometry and selection overlay work.
---
## Test Infrastructure
| Property | Value |
|----------|-------|
| **Framework** | none — simulator build/run and manual UAT |
| **Config file** | none |
| **Quick run command** | `xcodebuild -workspace ReadViewDemo/ReadViewDemo.xcworkspace -scheme ReadViewDemo -configuration Debug -destination 'platform=iOS Simulator,name=iPhone 17' build` |
| **Full suite command** | `xcodebuild -workspace ReadViewDemo/ReadViewDemo.xcworkspace -scheme ReadViewDemo -configuration Debug -destination 'platform=iOS Simulator,name=iPhone 17' build && build_run_sim` |
| **Estimated runtime** | ~180 seconds |
---
## Sampling Rate
- After every task commit: run the quick build command.
- After every plan wave: run the full simulator build/run path and confirm reader startup.
- Before execution handoff: confirm the selection overlay and offset preservation checks below.
- Max feedback latency: 180 seconds.
---
## Per-Task Verification Map
| Task ID | Plan | Wave | Requirement | Threat Ref | Secure Behavior | Test Type | Automated Command | File Exists | Status |
|---------|------|------|-------------|------------|-----------------|-----------|-------------------|-------------|--------|
| 06-01-01 | 06-01 | 1 | LAYOUT-01 | — | N/A | build | `xcodebuild ... build` | ✅ | ⬜ pending |
| 06-01-02 | 06-01 | 1 | LAYOUT-03 | — | N/A | build | `xcodebuild ... build` | ✅ | ⬜ pending |
| 06-02-01 | 06-02 | 2 | LAYOUT-02 | — | N/A | simulator | `build_run_sim` | ✅ | ⬜ pending |
| 06-02-02 | 06-02 | 2 | LAYOUT-03 | — | N/A | simulator | `build_run_sim` | ✅ | ⬜ pending |
| 06-03-01 | 06-03 | 3 | LAYOUT-01 | — | N/A | manual | simulator inspection | ✅ | ⬜ pending |
| 06-03-02 | 06-03 | 3 | LAYOUT-02 | — | N/A | manual | simulator inspection | ✅ | ⬜ pending |
| 06-03-03 | 06-03 | 3 | LAYOUT-03 | — | N/A | manual | simulator inspection | ✅ | ⬜ pending |
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
---
## Wave 0 Requirements
- Existing build path covers the phase requirements; no new test target is required.
- Manual checks must be available in the demo app using the native text sample books.
---
## Manual-Only Verifications
| Behavior | Requirement | Why Manual | Test Instructions |
|----------|-------------|------------|-------------------|
| Selection overlay appears and tracks the selected text range | LAYOUT-02 | Overlay geometry is visible behavior, not a source-only assertion | Open a native text sample, select text, verify overlay bounds follow the selected text and not the default `UITextView` selection chrome |
| Selection still serializes through `RDEPUBTextOffsetRangeInfo` | LAYOUT-03 | Offset continuity is best verified through persisted selection state and runtime logs | Create a selection, refresh the page, and confirm restored selection points to the same absolute offsets |
| Geometry queries do not break page navigation / current location | LAYOUT-01 | Page geometry must be validated through runtime behavior and current-location flow | Move between pages, search, and restore location after repagination; confirm page mapping stays stable |
---
## Validation Sign-Off
- [ ] All tasks have `<acceptance_criteria>` or manual checks
- [ ] Sampling continuity: no 3 consecutive tasks without a build or simulator check
- [ ] Wave 0 covers missing infrastructure
- [ ] No watch-mode flags
- [ ] Feedback latency < 180s
- [ ] `nyquist_compliant: true` set in frontmatter
**Approval:** pending

View File

@ -1,75 +0,0 @@
---
phase: 7
plan: 07-01
type: execute
wave: 1
depends_on: []
files_modified:
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBDTCoreTextRenderer.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
autonomous: true
requirements:
- ATTR-01
- ATTR-03
---
# Phase 7-01: 自定义分页语义映射
<objective>
定义一套显式的 WXRead 分页语义模型,并把章节 HTML/CSS 中的分页相关语义稳定映射到 attributed string作为后续分页器消费的唯一事实来源。
</objective>
<must_haves>
- `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`、`pageRelate` 至少在 attributed string 层形成统一属性键闭环。
- 块元素分类需要在 attributed string 或配套语义模型中可读,而不是只存在于 HTML 标签解析时的瞬时判断。
- 现有 `fragmentOffsets`、`pageStartOffset`、`pageEndOffset` 兼容语义不被破坏。
</must_haves>
<tasks>
<task id="07-01-01">
<type>execute</type>
<action>`RDEPUBTextRenderer.swift``RDEPUBReadingModels.swift` 中定义 Phase 7 需要的原生分页语义类型和属性键,例如块类型、分页 hint、附件垂直居中值、页面关联标记等。保持命名收敛避免把语义散落成多个匿名字符串常量。</action>
<read_first>
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- .planning/phases/07-wxread/07-RESEARCH.md
- Doc/WXRead/analysis/DTCoreText自定义修改分析.md
</read_first>
<acceptance_criteria>
- 新语义有明确的 Swift 类型或受控 raw-value 定义,不依赖匿名 magic string。
- 至少覆盖 `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`、`pageRelate`、块类型、附件垂直居中语义。
- 现有 `rdPageBlockRange`、`rdPageBlockIndex`、`rdPageAttachmentKind` 语义保持兼容,不被重命名或删除。
</acceptance_criteria>
</task>
<task id="07-01-02">
<type>execute</type>
<action>扩展 `RDEPUBTextRendererSupport``RDEPUBDTCoreTextRenderer` 的 preprocessing / post-processing 流程,从章节 HTML/CSS 中提取上述语义并写入 attributed string。优先复用现有 chapter preprocessing 与 attribute normalization 流程,必要时通过可诊断的桥接标记或受控 HTML 注入把 DTCoreText 默认不会保留的语义带过来。</action>
<read_first>
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBDTCoreTextRenderer.swift
- ReadViewDemo/Pods/DTCoreText/Core/Source/DTHTMLElement.h
- ReadViewDemo/Pods/DTCoreText/Core/Source/DTHTMLAttributedStringBuilder.m
</read_first>
<acceptance_criteria>
- 渲染后的 attributed string 至少能在对应 range 上读到分页 hint、页面关联标记与块类型中的一部分或全部。
- 无法直接保真的语义必须有明确桥接策略和诊断回退,而不是默默丢失。
- 现有章节渲染流程仍可构建 native text 样本,不引入 fixed/interactive 分支依赖。
</acceptance_criteria>
</task>
</tasks>
<verification>
- Build the `ReadViewDemo` workspace with the `ReadViewDemo` scheme.
- 对一个包含图片和复杂块元素的 native text 样本打印 attributed string 语义摘要,确认关键属性可见。
- 确认 fragment marker 提取和现有章节分页入口仍然工作。
</verification>
<success_criteria>
- Phase 7 的核心语义在 attributed string 层稳定存在。
- 语义提取路径集中在 renderer support而不是散落在 UI 层。
- 后续分页器与诊断路径可以消费统一的语义模型。
</success_criteria>

View File

@ -1,20 +0,0 @@
---
phase: 7
plan: 07-01
status: complete
requirements-completed:
- ATTR-01
- ATTR-03
updated: 2026-05-22
---
# 07-01 Summary
- Added explicit native-text semantic types and attributed-string keys for block kinds, pagination hints, and attachment placement.
- Extended chapter preprocessing to inject semantic markers for WXRead-style hints such as `avoidPageBreakInside`, `pageBreakBefore`, `pageBreakAfter`, `pageRelate`, and image/body block semantics.
- Renderer post-processing now strips those markers and applies real attributes before fragment-offset extraction, so semantic metadata is preserved without breaking the existing offset contract.
## Verification
- `build_sim` for `ReadViewDemo` on iOS Simulator succeeded on 2026-05-22.

View File

@ -1,77 +0,0 @@
---
phase: 7
plan: 07-02
type: execute
wave: 2
depends_on:
- 07-01
files_modified:
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
autonomous: true
requirements:
- ATTR-01
- ATTR-02
- ATTR-03
---
# Phase 7-02: 分页器消费与页级元数据接线
<objective>
让 native text 分页器与页级元数据真正消费 Phase 7 的自定义语义,使块分类、附件语义和分页 hint 能影响分页边界决策并保留到 page metadata。
</objective>
<must_haves>
- `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter` 不只是“记录下来”,而是能进入分页边界决策或分页诊断。
- 图片/附件的垂直居中等语义必须被保留到 page metadata 或可消费结构中。
- 块类型需要进入 page/frame 级诊断,使 `table / code / list / blockquote` 能被区分。
</must_haves>
<tasks>
<task id="07-02-01">
<type>execute</type>
<action>扩展 `RDEPUBTextLayouter``RDEPUBTextLayoutFrame`,在现有 attachment boundary / block boundary 逻辑上接入分页 hint处理强制分页前后断点、avoid-break 优先回退,以及附件语义对边界选择的影响。需要同时把命中的规则写进 diagnostics避免变成不可解释的隐式行为。</action>
<read_first>
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
- .planning/phases/07-wxread/07-RESEARCH.md
</read_first>
<acceptance_criteria>
- 命中的 `pageBreakBefore` / `pageBreakAfter` / `avoidPageBreakInside` 规则会改变 break 决策或至少改变诊断结果,不能完全无效。
- 分页 diagnostics 能说明当前页面为何提前断页、避免断页或跟随附件边界调整。
- 现有 page offset 兼容语义不回归native text 仍能完成章节分页。
</acceptance_criteria>
</task>
<task id="07-02-02">
<type>execute</type>
<action>`RDEPUBTextBookBuilder``RDEPUBReadingModels.swift` 中提升并暴露新的页级语义元数据,包括块类型摘要、附件垂直居中/附件分页语义、强制分页命中信息与复杂块分页诊断。保证 chapter/page 级诊断输出对 Demo 和后续回归可复用。</action>
<read_first>
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
</read_first>
<acceptance_criteria>
- `RDEPUBTextPageMetadata` 或其配套结构能表达块类型、附件语义和分页 hint 命中摘要。
- `RDEPUBTextChapterPaginationDiagnostic` 能输出至少一组与 Phase 7 语义直接相关的诊断信息。
- 图片/附件语义不会在 attributed string → layouter → page metadata 这条链路中丢失。
</acceptance_criteria>
</task>
</tasks>
<verification>
- Build and run `ReadViewDemo` on the simulator.
- 打开包含图片和复杂块元素的 native reflowable 样本,确认分页完成且 diagnostics 中能看见新语义。
- 对比分页前后 page count、offset 映射与现有 restore/search 路径,确认没有基础回归。
</verification>
<success_criteria>
- 自定义分页语义被分页器实际消费。
- 页级元数据可以解释复杂块和附件的分页行为。
- Phase 8 可以在不重复定义语义的前提下继续优化分页质量与附件规则。
</success_criteria>

View File

@ -1,21 +0,0 @@
---
phase: 7
plan: 07-02
status: complete
requirements-completed:
- ATTR-01
- ATTR-02
- ATTR-03
updated: 2026-05-22
---
# 07-02 Summary
- Taught `RDEPUBTextLayouter` to consume semantic hints and emit `semanticBoundary` breaks when explicit page-break or avoid-break rules should influence pagination.
- Expanded page metadata and layout frames to retain block kinds, semantic hints, and attachment placements alongside the existing attachment and break diagnostics.
- Propagated the richer pagination diagnostics through `RDEPUBTextBookBuilder` and `RDPlainTextBookBuilder`, so chapter summaries can now explain attachment-heavy and block-sensitive pagination behavior.
## Verification
- `build_sim` for `ReadViewDemo` on iOS Simulator succeeded on 2026-05-22.

View File

@ -1,78 +0,0 @@
---
phase: 7
plan: 07-03
type: execute
wave: 3
depends_on:
- 07-01
- 07-02
files_modified:
- ReadViewDemo/ReadViewDemo/ViewController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
autonomous: true
requirements:
- ATTR-01
- ATTR-02
- ATTR-03
---
# Phase 7-03: 诊断与回归证据标准化
<objective>
把 Phase 7 的自定义属性闭环变成可观测、可复现的 demo 证据,让复杂块、附件语义与分页命中规则能稳定出现在运行时诊断和回归日志中。
</objective>
<must_haves>
- Demo 或运行时日志能报告当前 native text 页面命中的分页语义与块类型摘要。
- 图片/附件语义和复杂块分类在真实样本上可见,不依赖阅读源码才能判断是否生效。
- 回归证据格式应尽量稳定,便于后续 Phase 8 / Phase 9 复用。
</must_haves>
<tasks>
<task id="07-03-01">
<type>execute</type>
<action>`RDEPUBReaderController``RDEPUBTextBookBuilder` 增加统一的 Phase 7 语义诊断摘要接口,输出当前页面或章节的块类型、附件语义、分页 hint 命中与 break reason。要求格式确定性强便于比较不同构建结果。</action>
<read_first>
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
- .planning/phases/07-wxread/07-PATTERNS.md
</read_first>
<acceptance_criteria>
- 存在一个可从 native text 路径调用的语义诊断摘要接口或方法。
- 摘要至少包含块类型、附件语义或强制分页命中中的两类以上信息。
- 同一章节在同一构建下重复运行时,摘要格式稳定且可比较。
</acceptance_criteria>
</task>
<task id="07-03-02">
<type>execute</type>
<action>扩展 `ReadViewDemo/ReadViewDemo/ViewController.swift` 的样本验证输出,至少对一个图片/附件章节和一个复杂块章节打印 Phase 7 语义摘要,并保留现有 native/fixed/interactive/TXT 矩阵。必要时补充最小的控制器接线,确保 demo 能暴露这些证据。</action>
<read_first>
- ReadViewDemo/ReadViewDemo/ViewController.swift
- Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
- Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
</read_first>
<acceptance_criteria>
- Demo 启动日志或显式诊断输出包含 Phase 7 语义摘要。
- 复杂块与附件样本至少各有一条可读证据,能证明语义没有在链路中丢失。
- 原有 fixed / interactive EPUB 与 TXT 路径仍保留在样本矩阵中,没有被新的 native text 诊断覆盖掉。
</acceptance_criteria>
</task>
</tasks>
<verification>
- Build and launch `ReadViewDemo` in the simulator.
- 记录复杂块样本与图片/附件样本的语义诊断摘要,确认块类型、附件语义、分页 hint 命中可见。
- 重新分页、切换主题或字号后再次记录摘要,确认格式仍稳定且基础导航语义未回归。
</verification>
<success_criteria>
- Phase 7 产出稳定的运行时证据,而不是只留下源码层推断。
- 复杂块、附件语义与分页规则在 demo 中可见。
- 后续阶段可以直接复用这些诊断输出做质量收敛和自动化回归。
</success_criteria>

View File

@ -1,23 +0,0 @@
---
phase: 7
plan: 07-03
status: complete
requirements-completed:
- ATTR-01
- ATTR-02
- ATTR-03
updated: 2026-05-22
---
# 07-03 Summary
- Added reusable semantic diagnostic summaries on `RDEPUBTextBookBuilder` and `RDEPUBReaderController` for the native text path.
- Updated `ReadViewDemo` startup validation to prioritize a Phase 7 semantic-closure line and a pagination line from native reflowable samples.
- Verified the simulator runtime log now surfaces explicit semantic evidence for a real sample book, rather than only generic sample-matrix output.
## Verification
- `build_run_sim` for `ReadViewDemo` on iPhone 17 (iOS 26.5 simulator) succeeded on 2026-05-22.
- Runtime log included `属性闭环诊断:宝山辽墓材料与释读 · 章节 10 · block kinds [attachment,paragraph] · placements [inline,centered] · block kinds: attachment`.
- Runtime log included `分页诊断:宝山辽墓材料与释读 · 章节 10 · attachment 页 54 · semantic break 页 57 · block kinds [attachment,paragraph] · placements [inline,centered] · reasons [attachmentBoundary:31, blockBoundary:26, frameLimit:17, chapterEnd:4] · page break: blockBoundary`.

View File

@ -1,36 +0,0 @@
# Phase 7: WXRead 自定义属性闭环 - Patterns
## Reusable Patterns
### Renderer support 已经是语义收口点
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift` 已负责 HTML 预处理、CSS layer 注入、fragment marker 注入和属性归一化。
- 新的 WXRead 语义应优先在这里被提取、标准化并写成统一属性键,而不是散落到 controller 或 view 层。
### Page metadata 已经是分页结果的公开契约
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift``RDEPUBTextPageMetadata` 已经对外承载 `breakReason`、`blockRange`、`attachmentKinds` 和 `diagnostics`
- 新增块类型、附件垂直居中、强制分页、avoid-break 命中等信息时,应继续沿用这个页级元数据汇总口。
### Layouter 已经掌握分页边界决策
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` 当前决定 attachment boundary、block boundary 和 frame limit。
- 所有“是否提前断页 / 是否避免截断 / 是否记录强制分页原因”的规则都应该在这里收敛,而不是后置到 UI 层补判断。
### BookBuilder 已经是诊断出口
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` 会把 frame 元数据提升为 chapter/page并产出 chapter 级诊断摘要。
- Phase 7 的复杂块分类与附件语义诊断最适合从这里向 demo 和后续回归路径暴露。
## Closest Existing Analogs
- `rdPageAttachmentKind` 是附件语义的最近现有 analog但只区分 `image/generic`,不够承载 WXRead 风格值。
- `rdPageBlockRange` / `rdPageBlockIndex` 是块级语义的最近现有 analog可以在此基础上继续引入 block kind 与分页 hint。
- `RDEPUBTextChapterPaginationDiagnostic.sampleNotes` 是最接近“可比对证据”的现有出口,适合扩展为 Phase 7 的语义诊断摘要。
## Design Guardrails
- 不直接搬运读书私有 DTCoreText 魔改实现;只复用公开文档中可验证的语义与行为目标。
- 继续沿用现有 chapter preprocessing、DTCoreText renderer contract 和 page offset 兼容语义。
- 新属性必须可观测:要么进入 attributed string 属性键,要么进入 page metadata / diagnostics不能只存在于瞬时局部变量。
- 不把 Phase 7 扩展成分页质量全面重写;复杂质量收敛和缓存仍属于 Phase 8。

View File

@ -1,46 +0,0 @@
# Phase 7: WXRead 自定义属性闭环 - Research
**Date:** 2026-05-22
**Phase:** 7
## Research Question
What do we need to know to plan the WXRead custom pagination-attribute closure well for the native text pipeline?
## Current State
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift` 已经负责章节 HTML 预处理、CSS 分层注入、fragment marker 注入,以及 `normalizeReadingAttributes` 的统一属性收口。
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBDTCoreTextRenderer.swift` 当前只把 DTCoreText 产出的 attributed string 交给通用后处理,没有显式保留 WXRead 风格的分页语义。
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` 目前只定义了 `rdPageBlockRange`、`rdPageBlockIndex`、`rdPageFragmentID`、`rdPageAttachmentKind` 四个原生属性键,缺少分页控制语义模型。
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` 已经会消费 block/attachment 元数据,并在分页时输出 `breakReason`、`blockRange`、`attachmentKinds`、`diagnostics`,但还不会消费 `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`、`pageRelate` 这类显式语义。
- `Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift``RDEPUBTextPageMetadata` 已经是页级元数据汇总点,适合继续承载块类型、附件语义、强制分页、分页诊断摘要。
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` 会把分页结果提升为 chapter/page 模型,并生成诊断摘要,是把新语义暴露给 Demo、回归、后续 Phase 8 的最佳出口。
- `Doc/WXRead/analysis/EPUB渲染管线详解.md``Doc/WXRead/analysis/DTCoreText自定义修改分析.md` 明确给出了目标语义集合:`wr-vertical-center-style`、`weread-page-relate`、`avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter`,以及 `table / code / list / blockquote` 这类块分类。
- `ReadViewDemo/Pods/DTCoreText/Core/Source/DTHTMLElement.*``DTHTMLAttributedStringBuilder.*` 是当前可复用的底层行为边界:现阶段更现实的是在现有 chapter preprocessing 和 attributed-string 后处理层增量接线,而不是直接重写 DTCoreText 私有实现。
## What This Means
1. Phase 7 的缺口不是“再造一个 renderer”而是给现有 renderer 增加一套显式、可诊断、可分页消费的语义模型。
2. 最稳妥的切入点是 `RDEPUBTextRendererSupport`,因为它已经同时掌握 HTML、CSS、attributed string、fragment marker 和统一后处理。
3. 块分类和分页语义必须先在 attributed string 上变成稳定属性键,后面的 layouter / page metadata / demo 诊断才能复用同一份事实。
4. 附件语义不能只保留“是不是图片”,还需要保留像 `wr-vertical-center-style` 这样的消费值,否则 Phase 8 无法继续细化图片/附件规则。
5. `avoidPageBreakInside`、`pageBreakBefore`、`pageBreakAfter` 不能停留在“记录下来”,它们至少要影响分页边界选择或诊断结果,否则闭环是不完整的。
## Recommended Planning Shape
- **Plan 07-01:** 定义语义模型与属性键,把 HTML/CSS 中的分页相关语义稳定映射到 attributed string。
- **Plan 07-02:** 让分页器和页级元数据真正消费这些语义,尤其是块分类、强制分页、附件垂直居中与 avoid-break 规则。
- **Plan 07-03:** 把语义闭环暴露到 demo / 诊断 / 回归路径,确保复杂样本上可观察、可比对、可复现。
## Technical Risks
- 如果语义提取分散在 renderer、layouter、UI 多处Phase 8 会继续面对“同一规则多处解释”的漂移问题。
- DTCoreText 默认产物对自定义 CSS 属性并不天然保真Phase 7 需要在 preprocessing 或 post-processing 层建立明确桥接策略。
- `avoidPageBreakInside` 与强制分页一旦直接改写分页边界,最容易引入 page offset 回归,因此必须把兼容契约和诊断一起规划进去。
- 块分类如果只靠标签名静态猜测,遇到 EPUB 自带 class/style 变体时可能不稳定;计划里需要明确保守策略和可诊断回退。
## Validation Implications
- 现有仓库没有独立测试靶Phase 7 仍需依赖 simulator build/run 与 demo 日志证据。
- 验证重点必须覆盖三类证据:属性是否进入 attributed string、分页器是否消费、demo 是否能看见块类型/附件语义/分页原因。
- 复杂样本至少要覆盖代码块/表格/列表/引用块以及含图片附件章节,否则 ATTR-02 / ATTR-03 的闭环无法证明。

View File

@ -1,79 +0,0 @@
---
phase: 7
slug: wxread
status: draft
nyquist_compliant: true
wave_0_complete: false
created: 2026-05-22
---
# Phase 7 — Validation Strategy
> Per-phase validation contract for WXRead custom pagination-attribute closure.
---
## Test Infrastructure
| Property | Value |
|----------|-------|
| **Framework** | none — simulator build/run and manual UAT |
| **Config file** | none |
| **Quick run command** | `xcodebuild -workspace ReadViewDemo/ReadViewDemo.xcworkspace -scheme ReadViewDemo -configuration Debug -destination 'platform=iOS Simulator,name=iPhone 17' build` |
| **Full suite command** | `xcodebuild -workspace ReadViewDemo/ReadViewDemo.xcworkspace -scheme ReadViewDemo -configuration Debug -destination 'platform=iOS Simulator,name=iPhone 17' build && build_run_sim` |
| **Estimated runtime** | ~180 seconds |
---
## Sampling Rate
- After every task commit: run the quick build command.
- After every plan wave: run the full simulator build/run path and confirm the native text sample books still open.
- Before execution handoff: confirm the semantic-attribute and pagination-diagnostic checks below.
- Max feedback latency: 180 seconds.
---
## Per-Task Verification Map
| Task ID | Plan | Wave | Requirement | Threat Ref | Secure Behavior | Test Type | Automated Command | File Exists | Status |
|---------|------|------|-------------|------------|-----------------|-----------|-------------------|-------------|--------|
| 07-01-01 | 07-01 | 1 | ATTR-01 | — | N/A | build | `xcodebuild ... build` | ✅ | ⬜ pending |
| 07-01-02 | 07-01 | 1 | ATTR-01 / ATTR-03 | — | N/A | build | `xcodebuild ... build` | ✅ | ⬜ pending |
| 07-02-01 | 07-02 | 2 | ATTR-01 / ATTR-02 | — | N/A | simulator | `build_run_sim` | ✅ | ⬜ pending |
| 07-02-02 | 07-02 | 2 | ATTR-03 | — | N/A | simulator | `build_run_sim` | ✅ | ⬜ pending |
| 07-03-01 | 07-03 | 3 | ATTR-02 / ATTR-03 | — | N/A | manual | simulator inspection | ✅ | ⬜ pending |
| 07-03-02 | 07-03 | 3 | ATTR-01 / ATTR-03 | — | N/A | manual | simulator inspection | ✅ | ⬜ pending |
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
---
## Wave 0 Requirements
- Existing build path covers the phase requirements; no new test target is required.
- Demo validation must include at least one native text sample with images/attachments and one sample containing code/list/table/blockquote-like structure.
---
## Manual-Only Verifications
| Behavior | Requirement | Why Manual | Test Instructions |
|----------|-------------|------------|-------------------|
| `avoidPageBreakInside` / `pageBreakBefore` / `pageBreakAfter` 规则能在分页日志或诊断中看见 | ATTR-01 | 需要结合真实章节分页结果,而不是只看源码 | 打开 native text 样本,记录分页摘要,确认强制分页或 avoid-break 命中会出现在诊断输出 |
| 图片/附件垂直居中等语义在 page metadata 或展示侧可见 | ATTR-02 | 需要运行时确认附件语义没有在 attributed string 到分页器之间丢失 | 打开包含图片的章节,检查 demo 日志或调试输出是否显示 attachment semantic / vertical-center 信息 |
| 代码块、表格、列表、引用块分类可区分并进入分页诊断 | ATTR-03 | 这是复杂样本行为,必须在真实内容上确认 | 打开复杂图文章节,确认诊断摘要能区分 block kind并能解释分页边界为何调整 |
---
## Validation Sign-Off
- [ ] All tasks have `<acceptance_criteria>` or manual checks
- [ ] Sampling continuity: no 3 consecutive tasks without a build or simulator check
- [ ] Wave 0 covers missing infrastructure
- [ ] No watch-mode flags
- [ ] Feedback latency < 180s
- [ ] `nyquist_compliant: true` set in frontmatter
**Approval:** pending

View File

@ -1,35 +0,0 @@
---
phase: 7
status: passed
requirements-verified:
- ATTR-01
- ATTR-02
- ATTR-03
updated: 2026-05-22
---
# Phase 7 Verification
## Result
Passed.
## What Was Verified
- HTML/CSS pagination semantics now survive the native text pipeline as explicit attributed-string metadata.
- Paginator and page metadata consume those semantics and expose them in break reasons and diagnostics.
- Demo startup validation surfaces semantic-closure evidence for a native reflowable sample book.
## Evidence
- `build_sim` for `ReadViewDemo` succeeded after the semantic extraction and layouter-consumption changes.
- `build_run_sim` for `ReadViewDemo` succeeded on iPhone 17 (iOS 26.5 simulator).
- Runtime log surfaced:
- `属性闭环诊断:宝山辽墓材料与释读 · 章节 10 · block kinds [attachment,paragraph] · placements [inline,centered] · block kinds: attachment`
- `分页诊断:宝山辽墓材料与释读 · 章节 10 · attachment 页 54 · semantic break 页 57 · block kinds [attachment,paragraph] · placements [inline,centered] · reasons [attachmentBoundary:31, blockBoundary:26, frameLimit:17, chapterEnd:4] · page break: blockBoundary`
## Residual Risk
- Current semantic extraction is intentionally conservative and heuristic-driven; future EPUB variants may require additional tag/class/style mappings in Phase 8.
- The sample evidence currently proves attachment and paragraph semantics clearly; richer code/list/table/blockquote samples should continue to be exercised as later phases tighten quality and automation.

View File

@ -1,237 +0,0 @@
---
phase: 08-pagination-quality-cache-performance
plan: 01
type: execute
wave: 1
depends_on: []
files_modified:
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift
autonomous: true
requirements:
- QUAL-01
must_haves:
truths:
- "Same bookID + fontSize + lineHeightMultiple + contentInsets produces same cache key"
- "Cache hit returns stored RDEPUBTextBook without calling build()"
- "Cache miss falls through to build and stores result"
- "Schema version bump invalidates all cached entries"
- "Changing any layout parameter produces a different cache key"
artifacts:
- path: "Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift"
provides: "Disk-persistent RDEPUBTextBook cache with SHA256 key generation"
contains: "class RDEPUBTextBookCache"
min_lines: 100
key_links:
- from: "RDEPUBTextBookCache.swift"
to: "Library/Caches/RDEPUBTextBookCache/"
via: "FileManager.default.urls(for: .cachesDirectory)"
pattern: "cachesDirectory"
---
<objective>
Create a disk-persistent cache for RDEPUBTextBook objects keyed by layout parameters (bookID + fontSize + lineHeightMultiple + contentInsets + pageSize), using NSKeyedArchiver for serialization and SHA256 for cache key hashing. This eliminates redundant full pagination of the same book under identical layout configuration.
Purpose: QUAL-01 requires that the same viewport and typography configuration does not trigger redundant full pagination. The cache stores complete RDEPUBTextBook objects to disk so repeated opens with the same parameters skip the entire build pipeline.
Output: A new `RDEPUBTextBookCache.swift` file providing load/save/invalidate operations.
</objective>
<execution_context>
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
@$HOME/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/phases/08-pagination-quality-cache-performance/08-CONTEXT.md
@.planning/phases/08-pagination-quality-cache-performance/08-RESEARCH.md
@.planning/phases/08-pagination-quality-cache-performance/08-PATTERNS.md
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
@Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
@Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift
<interfaces>
<!-- Key types the executor must serialize. From RDEPUBTextBookBuilder.swift lines 16-94 -->
From RDEPUBTextBookBuilder.swift:
```swift
public struct RDEPUBTextBook: Equatable {
public var chapters: [RDEPUBTextChapter]
public var pages: [RDEPUBTextPage]
public init(chapters: [RDEPUBTextChapter], pages: [RDEPUBTextPage])
}
public struct RDEPUBTextChapter: Equatable {
public var chapterIndex: Int
public var spineIndex: Int
public var href: String
public var title: String
public var attributedContent: NSAttributedString
public var fragmentOffsets: [String: Int]
public var pageBreakReasons: [RDEPUBTextPageBreakReason]
public var pages: [RDEPUBTextPage]
}
public struct RDEPUBTextPage: Equatable {
public var absolutePageIndex: Int
public var chapterIndex: Int
public var spineIndex: Int
public var href: String
public var chapterTitle: String
public var pageIndexInChapter: Int
public var totalPagesInChapter: Int
public var content: NSAttributedString
public var contentRange: NSRange
public var pageStartOffset: Int
public var pageEndOffset: Int
public var metadata: RDEPUBTextPageMetadata
}
```
From RDEPUBReadingModels.swift lines 183-215:
```swift
public struct RDEPUBTextPageMetadata: Codable, Equatable {
public var breakReason: RDEPUBTextPageBreakReason
public var blockRange: NSRange?
public var attachmentRanges: [NSRange]
public var attachmentKinds: [RDEPUBTextAttachmentKind]
public var blockKinds: [RDEPUBTextBlockKind]
public var semanticHints: [RDEPUBTextSemanticHint]
public var attachmentPlacements: [RDEPUBTextAttachmentPlacement]
public var trailingFragmentID: String?
public var diagnostics: [String]
}
```
<!-- File I/O pattern to follow. From RDEPUBParser+Archive.swift lines 55-66 -->
```swift
// Cache directory pattern:
let baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
.appendingPathComponent("RDEPUBTextBookCache", isDirectory: true)
?? FileManager.default.temporaryDirectory.appendingPathComponent("RDEPUBTextBookCache", isDirectory: true)
try FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
```
<!-- NSKeyedArchiver pattern for NSAttributedString serialization -->
```swift
// NSAttributedString supports NSCoding — serialize via NSKeyedArchiver
let data = try NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: false)
let object = try NSKeyedUnarchiver.unarchivedObject(ofClass: SomeClass.self, from: data)
```
</interfaces>
</context>
<tasks>
<task type="auto">
<name>Task 1: Create RDEPUBTextBookCache class with cache key generation and disk I/O</name>
<files>Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift</files>
<read_first>
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift
</read_first>
<action>
Create a new file `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift` implementing the complete cache system.
**RDEPUBTextBookCache class** (per D-01):
1. **Cache key generation** using CryptoKit SHA256:
- Key inputs: `bookID: String`, `fontSize: CGFloat`, `lineHeightMultiple: CGFloat`, `contentInsets: UIEdgeInsets`, `pageSize: CGSize`, `schemaVersion: Int`
- Format: `SHA256("\(bookID)_\(fontSize)_\(lineHeightMultiple)_\(contentInsets.top)_\(contentInsets.left)_\(contentInsets.bottom)_\(contentInsets.right)_\(pageSize.width)_\(pageSize.height)_v\(schemaVersion)")`
- Output: hex-encoded string + ".cache" extension for use as filename
- Reference WXRead pattern: `WRChapterPageCount.currentCacheKeyWithBookId:` encodes bookId + fontSize + lineSpacing + pageWidth + pageHeight
2. **Thread safety** using a serial DispatchQueue:
- `private let queue = DispatchQueue(label: "com.rdreader.textbookcache", qos: .utility)`
- All read/write operations wrapped in `queue.sync { }`
3. **Storage directory**: `Library/Caches/RDEPUBTextBookCache/` using `FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)`, with fallback to `temporaryDirectory`. Create directory with `createDirectory(at:withIntermediateDirectories:)` on init.
4. **Serialization strategy** using NSKeyedArchiver:
- Since RDEPUBTextBook is NOT NSCoding-conformant, create NSCoding wrapper classes for serialization:
- `RDEPUBTextBookArchive: NSObject, NSCoding` — stores array of chapter archives
- `RDEPUBTextChapterArchive: NSObject, NSCoding` — stores attributedContent (via NSKeyedArchiver), page data arrays
- `RDEPUBTextPageArchive: NSObject, NSCoding` — stores all RDEPUBTextPage fields
- `RDEPUBTextPageMetadataArchive: NSObject, NSCoding` — stores RDEPUBTextPageMetadata fields
- For NSRange fields: encode as `{location: Int, length: Int}` pairs
- For enums: encode as rawValue strings
- Wrap all NSCoding classes as `private` or `internal` (not public API)
5. **Public API**:
- `public init(subdirectory: String = "RDEPUBTextBookCache")` — sets up cache directory
- `public func cacheKey(bookID: String, fontSize: CGFloat, lineHeightMultiple: CGFloat, contentInsets: UIEdgeInsets, pageSize: CGSize) -> String` — returns SHA256 hash filename
- `public func load(key: String) -> RDEPUBTextBook?` — deserializes from disk, returns nil on miss or error
- `public func save(_ book: RDEPUBTextBook, key: String)` — serializes to disk
- `public func invalidateAll()` — deletes all files in cache directory
- `public var schemaVersion: Int` — default 1, bump when pagination logic changes to force invalidation
6. **Error handling**: All file I/O wrapped in do/catch. Failures logged via `print("[Cache] ...")` pattern and return nil/false (no throws in public API to avoid breaking callers).
7. **Console logging pattern** (follows existing `[EPUB]` style):
- `[Cache] save key=... chapters=N pages=N` on save
- `[Cache] load HIT key=...` on hit
- `[Cache] load MISS key=...` on miss
- `[Cache] invalidateAll` on clear
</action>
<verify>
<automated>xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' 2>&1 | tail -5</automated>
</verify>
<acceptance_criteria>
- File `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift` exists and contains `public final class RDEPUBTextBookCache`
- Cache key method produces deterministic SHA256 hex string from layout parameters
- Same inputs always produce identical key (deterministic)
- Different fontSize values produce different keys
- `schemaVersion` is a public property defaulting to 1
- `load(key:)` returns `RDEPUBTextBook?` (not throwing)
- `save(_:key:)` accepts `RDEPUBTextBook` (not throwing)
- `invalidateAll()` method exists
- Serial dispatch queue used for thread safety (`queue.sync`)
- Cache directory is under `Library/Caches/RDEPUBTextBookCache/`
- NSCoding wrapper classes exist for RDEPUBTextBook/Chapter/Page/Metadata serialization
- NSRange fields encoded as location+length integer pairs
- Build succeeds without compiler errors
</acceptance_criteria>
<done>
RDEPUBTextBookCache.swift is a complete, compilable file implementing SHA256 cache key generation, NSKeyedArchiver serialization with NSCoding wrappers, serial-queue thread safety, and load/save/invalidateAll API. Build succeeds.
</done>
</task>
</tasks>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| disk-cache → memory | Cached RDEPUBTextBook loaded from disk into memory; tampered cache files could inject malicious attributed strings |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation |
|-----------|----------|-----------|-------------|------------|
| T-08-01 | Tampering | RDEPUBTextBookCache disk files | accept | Cache stored in app sandbox Library/Caches; no external access; low-value target |
| T-08-02 | Information Disclosure | RDEPUBTextBookCache disk files | accept | No PII in cache; book content already accessible via app bundle |
| T-08-SC | Tampering | npm/pip/cargo installs | mitigate | No external packages installed in this phase |
</threat_model>
<verification>
- `xcodebuild build -scheme ReadViewDemo` succeeds
- `RDEPUBTextBookCache.swift` contains public class with cacheKey/load/save/invalidateAll
- SHA256 key generation uses CryptoKit
- NSCoding wrapper classes handle NSAttributedString and NSRange serialization
- Cache directory created under Library/Caches
</verification>
<success_criteria>
- New file `RDEPUBTextBookCache.swift` exists with complete implementation
- Cache key is deterministic: same inputs -> same key
- NSKeyedArchiver serialization produces valid .cache files
- Build succeeds with no warnings related to new code
</success_criteria>
<output>
Create `.planning/phases/08-pagination-quality-cache-performance/08-01-SUMMARY.md` when done
</output>

View File

@ -1,53 +0,0 @@
# Phase 08, Plan 01 — Summary
**Status**: Implementation complete. Build verification blocked by permission system.
## What Was Done
### New File Created
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift` (379 lines)
### Implementation Details
**RDEPUBTextBookCache class** — public final class with:
- `cacheKey(bookID:fontSize:lineHeightMultiple:contentInsets:pageSize:)` — CryptoKit SHA256 hex + `.cache` extension
- `load(key:) -> RDEPUBTextBook?` — NSKeyedUnarchiver deserialization, returns nil on miss/error
- `save(_:key:)` — NSKeyedArchiver serialization with atomic write
- `invalidateAll()` — deletes all files in cache directory
- `schemaVersion: Int` — defaults to 1, bump to invalidate all cached entries
- Serial `DispatchQueue` (`com.rdreader.textbookcache`) for thread safety via `queue.sync`
- Cache directory: `Library/Caches/RDEPUBTextBookCache/` with fallback to `temporaryDirectory`
**NSCoding wrapper classes** (private/internal):
- `RDEPUBTextBookArchive` — wraps chapters array
- `RDEPUBTextChapterArchive` — wraps chapter fields + attributedContent via NSKeyedArchiver
- `RDEPUBTextPageArchive` — wraps page fields + content NSAttributedString
- `RDEPUBTextPageMetadataArchive` — wraps metadata fields, NSRange as location+length pairs
- Enums serialized as rawValue strings
**Console logging**: `[Cache] save/load HIT/load MISS/invalidateAll` pattern
### Pre-existing Files Restored
- `RDEPUBTextLayouter.swift` — restored to committed state (had broken changes with missing method resolution)
- `RDEPUBTextPaginationSupport.swift` — restored to match (had config parameter mismatch)
These files had working-tree modifications that introduced compiler errors unrelated to this phase.
## Acceptance Criteria Met
- [x] File exists with `public final class RDEPUBTextBookCache`
- [x] SHA256 cache key generation (CryptoKit)
- [x] Deterministic key output (same inputs = same key)
- [x] Different fontSize produces different key
- [x] `schemaVersion` public property, defaults to 1
- [x] `load(key:)` returns `RDEPUBTextBook?` (non-throwing)
- [x] `save(_:key:)` accepts `RDEPUBTextBook` (non-throwing)
- [x] `invalidateAll()` exists
- [x] Serial dispatch queue (`queue.sync`)
- [x] Cache directory under `Library/Caches/RDEPUBTextBookCache/`
- [x] NSCoding wrapper classes for Book/Chapter/Page/Metadata
- [x] NSRange as location+length pairs
- [x] Enums as rawValue strings
- [?] Build succeeds — **UNVERIFIED** (permission system blocks xcodebuild/swift commands)
## Risks
- Build verification could not be performed due to permission restrictions on all build-related bash commands (xcodebuild, xcodebuildmcp, swift). The code was manually reviewed against all acceptance criteria and API signatures.

View File

@ -1,413 +0,0 @@
---
phase: 08-pagination-quality-cache-performance
plan: 02
type: execute
wave: 1
depends_on: []
files_modified:
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift
autonomous: true
requirements:
- QUAL-02
- QUAL-03
must_haves:
truths:
- "avoidPageBreakInside blocks are not split across page boundaries"
- "Orphan lines (last line of paragraph alone at page top) are prevented"
- "Widow lines (first line of paragraph alone at page bottom) are prevented"
- "Oversized images are scaled to fit within a single page height"
- "Image attachment blocks have vertical centering applied"
- "Image sizing and placement details appear in diagnostics"
- "Dark mode preserves original image colors (no color inversion applied)"
- "Page background information is surfaced in diagnostics for attachment blocks"
artifacts:
- path: "Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift"
provides: "RDEPUBTextLayoutConfig struct definition"
contains: "struct RDEPUBTextLayoutConfig"
- path: "Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift"
provides: "avoidPageBreakInside enforcement, orphan/widow control"
contains: "orphanWidowAdjustedRange"
- path: "Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift"
provides: "General image fit-to-page sizing and centering"
contains: "imageMaxHeight"
key_links:
- from: "RDEPUBTextLayouter.swift"
to: "RDEPUBTextRenderer.swift"
via: "RDEPUBTextLayoutConfig parameter in init"
pattern: "config: RDEPUBTextLayoutConfig"
- from: "RDEPUBTextRendererSupport.swift"
to: "RDEPUBTextLayoutConfig"
via: "imageMaxHeightRatio used in prepareHTMLElementForReaderRendering"
pattern: "imageMaxHeightRatio"
---
<objective>
Improve pagination quality for complex image-heavy chapters by enforcing avoidPageBreakInside (currently only a marker with no behavior), adding orphan/widow line control, and formalizing image sizing rules so oversized images fit within a single page.
Purpose: QUAL-02 requires reducing bad page breaks, orphan/widow lines, and image whitespace issues. QUAL-03 requires verifiable image sizing rules. The layouter currently has semantic boundary detection but does not enforce avoidPageBreakInside, and images have no general fit-to-page logic (only cover/footnote special cases).
Output: Modified layouter with orphan/widow control and avoidPageBreakInside enforcement; new RDEPUBTextLayoutConfig struct; enhanced image sizing in renderer support.
</objective>
<execution_context>
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
@$HOME/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/phases/08-pagination-quality-cache-performance/08-CONTEXT.md
@.planning/phases/08-pagination-quality-cache-performance/08-RESEARCH.md
@.planning/phases/08-pagination-quality-cache-performance/08-PATTERNS.md
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift
<interfaces>
<!-- Current layouter init signature. From RDEPUBTextLayouter.swift line 10 -->
```swift
init(attributedString: NSAttributedString, pageSize: CGSize)
```
<!-- Current adjustedRange return type. From RDEPUBTextLayouter.swift lines 64-77 -->
```swift
private func adjustedRange(
from proposedRange: NSRange,
totalLength: Int
) -> (
range: NSRange,
breakReason: RDEPUBTextPageBreakReason,
blockRange: NSRange?,
attachmentRanges: [NSRange],
attachmentKinds: [RDEPUBTextAttachmentKind],
blockKinds: [RDEPUBTextBlockKind],
semanticHints: [RDEPUBTextSemanticHint],
attachmentPlacements: [RDEPUBTextAttachmentPlacement],
diagnostics: [String]
)
```
<!-- Existing preferredSemanticBoundary with avoidPageBreakInside hint. From RDEPUBTextLayouter.swift lines 243-250 -->
```swift
if hints.contains(.avoidPageBreakInside),
attributeRange.location > range.location,
attributeRange.location < range.location + range.length,
attributeRange.location >= minimumEnd,
attributeEnd > range.location + range.length {
boundary = (attributeRange.location, RDEPUBTextSemanticHint.avoidPageBreakInside.rawValue)
stop.pointee = true
}
```
<!-- Existing paragraph range helper. From RDEPUBTextLayouter.swift lines 294-298 -->
```swift
private func paragraphRange(containing location: Int) -> NSRange {
let source = attributedString.string as NSString
guard source.length > 0 else { return NSRange(location: 0, length: 0) }
let safeLocation = min(max(location, 0), max(source.length - 1, 0))
return source.paragraphRange(for: NSRange(location: safeLocation, length: 0))
}
```
<!-- Existing image sizing pattern (cover only). From RDEPUBTextRendererSupport.swift lines 243-261 -->
```swift
if lowercasedClasses.contains("rd-front-cover-image") || lowercasedPath == "cover.jpg" {
let maxSize = UIScreen.main.bounds.insetBy(dx: 20, dy: 28).size
let originalSize = attachment.originalSize
if originalSize.width > 0, originalSize.height > 0 {
let scale = min(maxSize.width / originalSize.width, maxSize.height / originalSize.height)
attachment.displaySize = CGSize(
width: round(originalSize.width * scale),
height: round(originalSize.height * scale)
)
}
attachment.verticalAlignment = .baseline
element.displayStyle = .block
}
```
<!-- Existing RDEPUBTextRenderStyle struct pattern. From RDEPUBTextRenderer.swift lines 36-48 -->
```swift
public struct RDEPUBTextRenderStyle {
public var font: UIFont
public var lineSpacing: CGFloat
public var textColor: UIColor?
public var backgroundColor: UIColor?
public init(font: UIFont, lineSpacing: CGFloat, textColor: UIColor? = nil, backgroundColor: UIColor? = nil) {
self.font = font
self.lineSpacing = lineSpacing
self.textColor = textColor
self.backgroundColor = backgroundColor
}
}
```
<!-- WXRead reference: WRCoreTextLayoutFrame.avoidPageBreakInsideByRemovingLastLinesIfNeeded
When the proposed page end falls inside an avoidPageBreakInside block:
1. Find the block's start location
2. If block start >= minimumEnd, break at block start (push entire block to next page)
3. If block start < minimumEnd (block too large), fall through to frameLimit -->
<!-- rd_paginatedFrames extension (entry point). From RDEPUBTextPaginationSupport.swift lines 4-11 -->
```swift
extension NSAttributedString {
func rd_paginatedFrames(
size: CGSize,
fragmentOffsets: [String: Int] = [:]
) -> [RDEPUBTextLayoutFrame] {
RDEPUBTextLayouter(attributedString: self, pageSize: size)
.layoutFrames(fragmentOffsets: fragmentOffsets)
}
}
```
</interfaces>
</context>
<tasks>
<task type="auto">
<name>Task 1: Add RDEPUBTextLayoutConfig and wire into layouter + pagination support</name>
<files>Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift, Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift, Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift</files>
<read_first>
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
</read_first>
<action>
**Step 1: Define RDEPUBTextLayoutConfig in RDEPUBTextRenderer.swift** (per D-02, D-03)
Insert `RDEPUBTextLayoutConfig` struct after `RDEPUBTextRenderStyle` (after line 48), following the same struct pattern:
```swift
public struct RDEPUBTextLayoutConfig: Equatable {
public var avoidOrphans: Bool
public var avoidWidows: Bool
public var avoidPageBreakInsideEnabled: Bool
public var imageMaxHeightRatio: CGFloat
public init(
avoidOrphans: Bool = true,
avoidWidows: Bool = true,
avoidPageBreakInsideEnabled: Bool = true,
imageMaxHeightRatio: CGFloat = 0.85
) {
self.avoidOrphans = avoidOrphans
self.avoidWidows = avoidWidows
self.avoidPageBreakInsideEnabled = avoidPageBreakInsideEnabled
self.imageMaxHeightRatio = imageMaxHeightRatio
}
public static let `default` = RDEPUBTextLayoutConfig()
}
```
This follows the exact same pattern as `RDEPUBTextRenderStyle` at lines 36-48: public struct, public stored properties, public init with defaults, static default instance.
**Step 2: Add config parameter to RDEPUBTextLayouter**
In `RDEPUBTextLayouter.swift`:
- Add stored property: `private let config: RDEPUBTextLayoutConfig`
- Update init signature: `init(attributedString: NSAttributedString, pageSize: CGSize, config: RDEPUBTextLayoutConfig = .default)`
- Store config: `self.config = config`
**Step 3: Update rd_paginatedFrames extension**
In `RDEPUBTextPaginationSupport.swift`, update the `rd_paginatedFrames` method to pass through config:
```swift
func rd_paginatedFrames(
size: CGSize,
fragmentOffsets: [String: Int] = [:],
config: RDEPUBTextLayoutConfig = .default
) -> [RDEPUBTextLayoutFrame] {
RDEPUBTextLayouter(attributedString: self, pageSize: size, config: config)
.layoutFrames(fragmentOffsets: fragmentOffsets)
}
```
The `config` parameter has a default value so all existing call sites continue to work without changes.
</action>
<verify>
<automated>xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' 2>&1 | tail -5</automated>
</verify>
<acceptance_criteria>
- `RDEPUBTextLayoutConfig` struct exists in RDEPUBTextRenderer.swift with properties: `avoidOrphans`, `avoidWidows`, `avoidPageBreakInsideEnabled`, `imageMaxHeightRatio`
- `RDEPUBTextLayoutConfig` has `public static let default` instance
- `RDEPUBTextLayouter` init accepts `config: RDEPUBTextLayoutConfig` parameter with `.default` default value
- `rd_paginatedFrames` extension accepts `config: RDEPUBTextLayoutConfig` parameter with `.default` default value
- Build succeeds with no errors at existing call sites (default parameter maintains backward compatibility)
</acceptance_criteria>
<done>
RDEPUBTextLayoutConfig struct defined in RDEPUBTextRenderer.swift; layouter and rd_paginatedFrames accept optional config parameter with backward-compatible defaults. Build succeeds.
</done>
</task>
<task type="auto">
<name>Task 2: Implement avoidPageBreakInside enforcement and orphan/widow control in layouter</name>
<files>Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift</files>
<read_first>
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift
</read_first>
<action>
Modify `RDEPUBTextLayouter.swift` to add two pagination quality improvements. Both use the `config` property added in Task 1.
**A. avoidPageBreakInside enforcement** (per D-02, QUAL-02, WXRead reference: `avoidPageBreakInsideByRemovingLastLinesIfNeeded`)
The current `preferredSemanticBoundary` at lines 243-250 only triggers avoidPageBreakInside when the block START is the boundary point (i.e., the block starts after minimumEnd and extends past page end). This misses the case where the page end falls IN THE MIDDLE of an avoidPageBreakInside block.
Add a new private method `avoidPageBreakInsideBoundary(in:proposedRange:minimumEnd:)` that, after the existing `preferredSemanticBoundary` check and before `preferredAttachmentBoundary` in `adjustedRange()`:
1. Enumerate `.rdPageSemanticHints` in the proposed range
2. For each range containing `.avoidPageBreakInside`:
- If the attribute range overlaps with the last portion of the page (i.e., the attribute range contains characters near `pageEnd`)
- And the attribute's start location is >= `minimumEnd` (so pushing to block start is reasonable)
- Then return the attribute range's start location as the break point
3. If `config.avoidPageBreakInsideEnabled` is false, skip this check entirely
Insert this check in `adjustedRange()` between the `preferredSemanticBoundary` block (line 114-139) and the `preferredAttachmentBoundary` block (line 141). When triggered, use `breakReason: .semanticBoundary` and add `"avoidPageBreakInside enforcement"` to diagnostics.
**B. Orphan/widow control** (per QUAL-02)
Add a new private method `orphanWidowAdjustedRange(from:totalLength:)` that:
1. **Orphan check** (config.avoidOrphans): If the page starts at the beginning of a new paragraph, check if only 1-2 lines of that paragraph fit on the page. If so, and if pulling back 1-2 lines from the previous page would not cause that page to lose too much content, adjust the break point backward to include those lines. Use `paragraphRange(containing:)` to find paragraph boundaries.
- Implementation: Check if the first paragraph on the page has fewer than 2 lines worth of characters (heuristic: `paragraphRange.length < averageLineHeight * 2.5`). If so, move the break point to include more of this paragraph from the previous page, respecting minimumEnd.
2. **Widow check** (config.avoidWidows): If the page ends with just 1-2 lines of a paragraph, and the next page would start with the continuation of that same paragraph, check if pushing 1-2 lines forward would help. Use `paragraphRange(containing:)` to detect this.
- Implementation: At the proposed page end, get the paragraph range. If the remaining portion of the paragraph after pageEnd is small (fewer than 2 lines), pull the break point back to before this paragraph, forcing the entire paragraph to the next page. Respect minimumEnd.
Insert this check after `avoidPageBreakInsideBoundary` and before `preferredAttachmentBoundary` in `adjustedRange()`. When triggered, use `breakReason: .semanticBoundary` and add `"orphan control"` or `"widow control"` to diagnostics.
**C. Diagnostics enhancement**: When avoidPageBreakInside or orphan/widow triggers, append a descriptive string to the diagnostics array, e.g., `"avoidPageBreakInside: pushed block to next page"`, `"orphan control: included 1 line from previous page"`, `"widow control: pushed paragraph to next page"`.
</action>
<verify>
<automated>xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' 2>&1 | tail -5</automated>
</verify>
<acceptance_criteria>
- `adjustedRange()` in RDEPUBTextLayouter contains a check for `avoidPageBreakInside` after `preferredSemanticBoundary` and before `preferredAttachmentBoundary`
- The avoidPageBreakInside check is gated on `config.avoidPageBreakInsideEnabled`
- Orphan control method exists and is called in `adjustedRange()` flow
- Widow control method exists and is called in `adjustedRange()` flow
- Both orphan and widow checks are gated on `config.avoidOrphans` and `config.avoidWidows` respectively
- Diagnostic strings are appended when avoidPageBreakInside/orphan/widow triggers
- Build succeeds
</acceptance_criteria>
<done>
Layouter enforces avoidPageBreakInside by detecting when page end falls inside an avoidPageBreakInside block and pushing the block to the next page. Orphan/widow control prevents single-line paragraphs at page boundaries. All gated via RDEPUBTextLayoutConfig. Build succeeds.
</done>
</task>
<task type="auto">
<name>Task 3: Add general image fit-to-page sizing and enhanced diagnostics in renderer support</name>
<files>Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift</files>
<read_first>
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
</read_first>
<action>
Modify `prepareHTMLElementForReaderRendering` in `RDEPUBTextRendererSupport.swift` (inside the `#if canImport(DTCoreText)` block, lines 216-262) to add general image sizing for all non-special-case images.
**Current state**: The method handles two special cases:
- Footnote images (qqreader-footnote) at lines 228-241: inline, scaled to font size
- Cover images (rd-front-cover-image) at lines 243-261: block display, scaled to fit screen
**Add general image handling** after the cover image check (after line 261, before the closing brace of the method). This handles ALL other images that are not footnotes or covers:
1. **Fit-to-page height** (per D-03, QUAL-03, WXRead reference: images should not span pages):
- Check if `attachment.originalSize` has valid dimensions (width > 0, height > 0)
- Calculate `maxImageHeight = pageSize.height * imageMaxHeightRatio` — but since `prepareHTMLElementForReaderRendering` does not receive pageSize, use `UIScreen.main.bounds.insetBy(dx: 20, dy: 28).height` as the max height (same pattern used for cover images at line 244)
- If `originalSize.height > maxImageHeight`: scale proportionally so display height = maxImageHeight
- If `originalSize.width > maxWidth` (screen width minus insets): scale proportionally
- Set `attachment.displaySize` to the scaled dimensions
- The scale formula: `let scale = min(maxWidth / originalSize.width, maxImageHeight / originalSize.height)`
2. **Vertical centering for block-level images** (per D-03, WXRead reference: `wr-vertical-center-style`):
- If the element has `displayStyle == .block` (or is a figure/bodyPic), set `attachment.verticalAlignment = .center`
- This aligns with the existing `attachmentPlacements` mechanism that already tracks `.centered` placement
3. **Enhanced diagnostic output** (per QUAL-03):
- After setting displaySize, print a diagnostic line: `print("[EPUB][Attachment] general image path=\(lowercasedPath) original=\(string(from: originalSize)) display=\(string(from: attachment.displaySize)) scaled=\(wasScaled)")`
- Use the existing `string(from:)` helper at line 424 to format CGSize values
- Track `wasScaled` boolean: true if displaySize differs from originalSize
4. **Dark mode image preservation** (per D-03):
- Images in dark mode must preserve original colors (no color inversion). DTCoreText's `NSAttributedString` rendering already preserves image attachment colors by default.
- Add a diagnostic check: if `UITraitCollection.current.userInterfaceStyle == .dark`, emit `print("[EPUB][Attachment] dark mode: image colors preserved for path=\(lowercasedPath)")` to verify the behavior is observable.
- This is a declarative rule — ensure no future code adds `tintColor` overrides or color filters to image attachments in dark mode.
5. **Page background diagnostics** (per D-03):
- For attachment blocks, emit a diagnostic that includes the block's background color if one is set on the attributed string: `print("[EPUB][Attachment] background: path=\(lowercasedPath) hasBackground=\(hasBackground)")` where `hasBackground` checks if `.backgroundColor` attribute exists at the attachment location.
- This provides verifiable evidence of background handling without changing rendering behavior.
6. **Guard condition**: Only apply this general sizing if the image is NOT already handled by the footnote or cover checks above. Structure: the footnote check returns early (already does), the cover check returns early (add `return` at the end of the cover block), then the general image check runs for all remaining images.
**Important**: Add `return` at the end of the cover image block (after line 261) so the general image check does not double-process cover images. The current cover block does NOT have a `return` — it falls through.
</action>
<verify>
<automated>xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' 2>&1 | tail -5</automated>
</verify>
<acceptance_criteria>
- `prepareHTMLElementForReaderRendering` contains a general image sizing block after the cover image block
- General image block checks `originalSize.height > maxImageHeight` and scales proportionally
- General image block sets `attachment.verticalAlignment = .center` for block-level images
- Cover image block has `return` to prevent fall-through to general image handling
- Diagnostic `print("[EPUB][Attachment] general image ...")` is emitted with original/display sizes
- Dark mode diagnostic `print("[EPUB][Attachment] dark mode: image colors preserved ...")` is emitted when userInterfaceStyle == .dark
- Background diagnostic `print("[EPUB][Attachment] background: ...")` is emitted for attachment blocks
- Build succeeds
</acceptance_criteria>
<done>
General images (not footnote, not cover) are scaled to fit within page height, vertically centered when block-level, dark mode preserves original image colors, page background info diagnosed, and all decisions logged via console output. Build succeeds.
</done>
</task>
</tasks>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| CoreText layout → page break decisions | Layouter now makes more aggressive break adjustments; incorrect logic could produce empty or overlapping pages |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation |
|-----------|----------|-----------|-------------|------------|
| T-08-03 | Tampering | RDEPUBTextLayoutConfig defaults | accept | Config is a value type with safe defaults; no external input can modify it |
| T-08-SC | Tampering | npm/pip/cargo installs | mitigate | No external packages installed in this phase |
</threat_model>
<verification>
- `xcodebuild build -scheme ReadViewDemo` succeeds
- RDEPUBTextLayoutConfig struct exists in RDEPUBTextRenderer.swift
- Layouter adjustedRange includes avoidPageBreakInside, orphan, and widow checks
- prepareHTMLElementForReaderRendering handles general image sizing
- Runtime log shows `[EPUB][Attachment] general image` for non-special images
- Runtime log shows `[EPUB][Attachment] dark mode: image colors preserved` in dark mode
- Runtime log shows `[EPUB][Attachment] background:` for attachment blocks
</verification>
<success_criteria>
- avoidPageBreakInside blocks are never split across page boundaries when config enabled
- Orphan/widow control reduces single-line paragraphs at page boundaries
- Oversized images scale to fit within page height
- Dark mode preserves original image colors (no inversion)
- Page background information is diagnosed for attachment blocks
- Diagnostic output confirms image sizing decisions
- Build succeeds with no regressions
</success_criteria>
<output>
Create `.planning/phases/08-pagination-quality-cache-performance/08-02-SUMMARY.md` when done
</output>

View File

@ -1,51 +0,0 @@
---
phase: 08-pagination-quality-cache-performance
plan: 02
type: summary
date: 2026-05-23
---
# Phase 08-02 Summary
## Objective
Improve pagination quality by enforcing avoidPageBreakInside, adding orphan/widow line control, and implementing general image fit-to-page sizing.
## Tasks Completed
### Task 1: RDEPUBTextLayoutConfig struct and wiring
- Defined `RDEPUBTextLayoutConfig` in `RDEPUBTextRenderer.swift` with 4 properties: `avoidOrphans`, `avoidWidows`, `avoidPageBreakInsideEnabled`, `imageMaxHeightRatio` (default 0.85)
- Follows the exact `RDEPUBTextRenderStyle` struct pattern: public struct, public stored properties, public init with defaults, static `.default` instance
- Added `config` parameter to `RDEPUBTextLayouter.init` with `.default` default value
- Added `config` parameter to `rd_paginatedFrames` extension with `.default` default value
- All existing call sites continue to work unchanged (backward compatible)
### Task 2: avoidPageBreakInside enforcement + orphan/widow control
- Added `avoidPageBreakInsideBoundary(in:minimumEnd:)` method in `RDEPUBTextLayouter.swift`
- Detects when page end falls INSIDE an avoidPageBreakInside block (complement to existing check that only handles block start as boundary)
- Pushes entire block to next page when block start >= minimumEnd
- Gated on `config.avoidPageBreakInsideEnabled`
- Added `orphanWidowAdjustedRange(from:minimumEnd:)` method
- **Orphan control**: When page starts at a paragraph beginning and only 1-2 lines fit, pulls back to include more content from previous page
- **Widow control**: When page ends with only 1-2 lines of a paragraph remaining, pushes entire paragraph to next page
- Both gated on `config.avoidOrphans` and `config.avoidWidows` respectively
- Inserted both checks in `adjustedRange()` between `preferredSemanticBoundary` and `preferredAttachmentBoundary`
- Diagnostic strings emitted on trigger: "avoidPageBreakInside enforcement", "orphan control: ...", "widow control: ..."
### Task 3: General image fit-to-page sizing and diagnostics
- Added `return` at end of cover image block to prevent fall-through to general handling
- Added general image sizing block for all non-footnote, non-cover images:
- Scales images exceeding `maxImageHeight` (screen height * 0.85) or `maxWidth` proportionally
- Sets `verticalAlignment = .center` for block-level images (bodyPic, qrbodyPic, figure, .block displayStyle)
- Added diagnostic output:
- `[EPUB][Attachment] general image ...` with original/display sizes and scaled flag
- `[EPUB][Attachment] dark mode: image colors preserved ...` when in dark mode
- `[EPUB][Attachment] background: ...` with hasBackground check for attachment blocks
## Files Modified
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` — added `RDEPUBTextLayoutConfig` struct
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` — added config property, avoidPageBreakInside enforcement, orphan/widow control
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift` — added config parameter to `rd_paginatedFrames`
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift` — added general image sizing, cover return, diagnostic output
## Build Status
All three tasks verified with `xcodebuild build -workspace ReadViewDemo/ReadViewDemo.xcworkspace -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17 Pro'` — BUILD SUCCEEDED for each.

View File

@ -1,396 +0,0 @@
---
phase: 08-pagination-quality-cache-performance
plan: 03
type: execute
wave: 2
depends_on:
- 08-01
- 08-02
files_modified:
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift
- Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
autonomous: true
requirements:
- QUAL-01
- QUAL-04
must_haves:
truths:
- "Builder records per-chapter render time and paginate time"
- "Builder records total build time"
- "Builder records cache hit/miss per chapter"
- "Performance samples are accessible via lastBuildPerformanceSamples"
- "Cache integration: builder accepts optional cache parameter and skips build on hit"
- "Cache miss triggers full build and stores result"
- "Console logs show [PERF] summary with timing data"
artifacts:
- path: "Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift"
provides: "RDEPUBTextPerformanceSample struct and RDEPUBTextPerformanceSampler class"
contains: "struct RDEPUBTextPerformanceSample"
- path: "Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift"
provides: "Cache integration and performance instrumentation in build()"
contains: "lastBuildPerformanceSamples"
key_links:
- from: "RDEPUBTextBookBuilder.swift"
to: "RDEPUBTextBookCache.swift"
via: "cache.load(key:) / cache.save(_:key:)"
pattern: "cache\\.load\\|cache\\.save"
- from: "RDEPUBTextBookBuilder.swift"
to: "RDEPUBTextPerformanceSampler.swift"
via: "sampler.record(sample)"
pattern: "sampler\\.record"
---
<objective>
Create performance sampling infrastructure and integrate cache + performance instrumentation into RDEPUBTextBookBuilder.build(). This adds timing measurements for render/paginate/build operations and wires the cache from Plan 01 so that repeated builds with the same parameters skip the full pipeline.
Purpose: QUAL-04 requires stable diagnostic/sampling data to ensure no degradation. QUAL-01 requires cache integration to avoid redundant pagination. This plan brings both into the builder.
Output: New RDEPUBTextPerformanceSampler.swift; modified RDEPUBTextBookBuilder.swift with cache integration and timing instrumentation.
</objective>
<execution_context>
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
@$HOME/.claude/get-shit-done/templates/summary.md
</execution_context>
<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/phases/08-pagination-quality-cache-performance/08-CONTEXT.md
@.planning/phases/08-pagination-quality-cache-performance/08-RESEARCH.md
@.planning/phases/08-pagination-quality-cache-performance/08-PATTERNS.md
@.planning/phases/08-pagination-quality-cache-performance/08-01-SUMMARY.md
@.planning/phases/08-pagination-quality-cache-performance/08-02-SUMMARY.md
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift
@Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
<interfaces>
<!-- Builder init pattern. From RDEPUBTextBookBuilder.swift lines 101-107 -->
```swift
public init(renderer: RDEPUBTextRenderer) {
self.renderer = renderer
}
public convenience init() {
self.init(renderer: RDEPUBDTCoreTextRenderer())
}
```
<!-- Existing diagnostics properties. From RDEPUBTextBookBuilder.swift lines 98-99 -->
```swift
public private(set) var lastBuildResourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic] = []
public private(set) var lastBuildPaginationDiagnostics: [RDEPUBTextChapterPaginationDiagnostic] = []
```
<!-- Build method signature. From RDEPUBTextBookBuilder.swift lines 132-137 -->
```swift
public func build(
parser: RDEPUBParser,
publication: RDEPUBPublication,
pageSize: CGSize,
style: RDEPUBTextRenderStyle
) throws -> RDEPUBTextBook
```
<!-- Cache public API (from Plan 01) -->
```swift
public final class RDEPUBTextBookCache {
public init(subdirectory: String = "RDEPUBTextBookCache")
public func cacheKey(bookID: String, fontSize: CGFloat, lineHeightMultiple: CGFloat, contentInsets: UIEdgeInsets, pageSize: CGSize) -> String
public func load(key: String) -> RDEPUBTextBook?
public func save(_ book: RDEPUBTextBook, key: String)
public func invalidateAll()
public var schemaVersion: Int
}
```
<!-- Performance measurement pattern (standard iOS) -->
```swift
let start = CFAbsoluteTimeGetCurrent()
// ... operation ...
let duration = CFAbsoluteTimeGetCurrent() - start
```
<!-- Existing struct pattern for diagnostics. From RDEPUBTextRenderer.swift lines 90-113 -->
```swift
public struct RDEPUBTextResourceReferenceDiagnostic: Equatable {
public var kind: RDEPUBTextResourceReferenceKind
public var chapterHref: String
// ...
public init(kind: ..., chapterHref: ..., ...) { ... }
}
```
<!-- PaginationSupport extension (from Plan 02, Task 1 — updated to pass config) -->
```swift
extension NSAttributedString {
func rd_paginatedFrames(
size: CGSize,
fragmentOffsets: [String: Int] = [:],
config: RDEPUBTextLayoutConfig = .default
) -> [RDEPUBTextLayoutFrame]
}
```
</interfaces>
</context>
<tasks>
<task type="auto">
<name>Task 1: Create RDEPUBTextPerformanceSampler with timing sample struct and recording API</name>
<files>Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift</files>
<read_first>
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
</read_first>
<action>
Create a new file `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift`.
**RDEPUBTextPerformanceSample struct** (per QUAL-04, D-04):
```swift
public struct RDEPUBTextPerformanceSample: Equatable {
public var chapterHref: String
public var renderDuration: TimeInterval // DTCoreText render time
public var paginateDuration: TimeInterval // CoreText pagination time
public var pageCount: Int
public var attributedStringLength: Int
public var cacheHit: Bool
public init(
chapterHref: String,
renderDuration: TimeInterval,
paginateDuration: TimeInterval,
pageCount: Int,
attributedStringLength: Int,
cacheHit: Bool
) { ... }
}
```
Follow the exact pattern from `RDEPUBTextResourceReferenceDiagnostic` at RDEPUBTextRenderer.swift lines 90-113: public struct, Equatable, explicit public init with all properties.
**RDEPUBTextPerformanceSampler class**:
```swift
public final class RDEPUBTextPerformanceSampler {
public private(set) var samples: [RDEPUBTextPerformanceSample] = []
public private(set) var totalBuildDuration: TimeInterval = 0
public init() {}
public func record(_ sample: RDEPUBTextPerformanceSample) {
samples.append(sample)
print("[PERF] \(sample.chapterHref): render=\(formatMS(sample.renderDuration)) paginate=\(formatMS(sample.paginateDuration)) pages=\(sample.pageCount) cache=\(sample.cacheHit ? "HIT" : "MISS")")
}
public func summary() -> String {
let totalRender = samples.reduce(0) { $0 + $1.renderDuration }
let totalPaginate = samples.reduce(0) { $0 + $1.paginateDuration }
let hitCount = samples.filter(\.cacheHit).count
return "[PERF] chapters=\(samples.count) render=\(formatMS(totalRender)) paginate=\(formatMS(totalPaginate)) total=\(formatMS(totalBuildDuration)) cacheHits=\(hitCount)/\(samples.count)"
}
public func reset() {
samples.removeAll()
totalBuildDuration = 0
}
private func formatMS(_ duration: TimeInterval) -> String {
String(format: "%.0fms", duration * 1000)
}
}
```
**Console output pattern** (follows existing `[EPUB]` style in the codebase):
- Each `record()` call prints a per-chapter `[PERF]` line
- `summary()` returns a formatted string (caller prints it)
- Use milliseconds (multiply TimeInterval by 1000) for human-readable output
</action>
<verify>
<automated>xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' 2>&1 | tail -5</automated>
</verify>
<acceptance_criteria>
- File `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift` exists
- `RDEPUBTextPerformanceSample` is a public struct with Equatable conformance
- Properties: `chapterHref`, `renderDuration`, `paginateDuration`, `pageCount`, `attributedStringLength`, `cacheHit`
- `RDEPUBTextPerformanceSampler` is a public final class
- `record(_:)` method appends sample and prints `[PERF]` line
- `summary()` returns formatted string with totals and cache hit rate
- `reset()` clears samples and totalBuildDuration
- `totalBuildDuration` is a public property
- Build succeeds
</acceptance_criteria>
<done>
RDEPUBTextPerformanceSampler.swift contains performance sample struct and sampler class with record/summary/reset API and [PERF] console logging. Build succeeds.
</done>
</task>
<task type="auto">
<name>Task 2: Integrate cache and performance sampling into RDEPUBTextBookBuilder.build()</name>
<files>Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift</files>
<read_first>
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift
Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift
Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift
</read_first>
<action>
Modify `RDEPUBTextBookBuilder.swift` to integrate the cache (from Plan 01) and performance sampling (Task 1).
**Step 1: Add new stored properties** (per D-01, D-04)
After the existing `lastBuildPaginationDiagnostics` property (line 99), add:
```swift
public private(set) var lastBuildPerformanceSamples: [RDEPUBTextPerformanceSample] = []
public private(set) var lastBuildCacheStats: (hits: Int, misses: Int) = (0, 0)
```
**Step 2: Add cache and sampler to init** (per D-01)
Update the initializer to accept optional cache:
```swift
private let cache: RDEPUBTextBookCache?
private let sampler: RDEPUBTextPerformanceSampler
public init(renderer: RDEPUBTextRenderer, cache: RDEPUBTextBookCache? = nil) {
self.renderer = renderer
self.cache = cache
self.sampler = RDEPUBTextPerformanceSampler()
}
public convenience init() {
self.init(renderer: RDEPUBDTCoreTextRenderer())
}
```
The `cache` parameter defaults to nil for backward compatibility. The sampler is always created (lightweight, no cost until samples recorded).
**Step 3: Add cache key helper**
Add a private helper method to generate the cache key from build parameters:
```swift
private func makeCacheKey(
bookID: String,
pageSize: CGSize,
style: RDEPUBTextRenderStyle
) -> String? {
guard let cache else { return nil }
return cache.cacheKey(
bookID: bookID,
fontSize: style.font.pointSize,
lineHeightMultiple: style.lineSpacing,
contentInsets: .zero, // or derive from pageSize insets if available
pageSize: pageSize
)
}
```
Note: The `bookID` needs to come from the publication. Use `publication.metadata.identifier ?? publication.metadata.title ?? "unknown"` as the bookID. If no identifier is available, return nil to skip caching.
**Step 4: Instrument the build() method** (per QUAL-04, QUAL-01)
At the start of `build()`, after the existing `lastBuildResourceDiagnostics = []` / `lastBuildPaginationDiagnostics = []` lines:
1. **Reset sampler**: `sampler.reset()`, `lastBuildCacheStats = (0, 0)`
2. **Start build timer**: `let buildStart = CFAbsoluteTimeGetCurrent()`
3. **Cache lookup**: If cache is available, generate key and try `cache.load(key:)`. If hit, set `lastBuildCacheStats.hits += 1`, print `[Cache] HIT`, and return the cached book immediately.
4. **Cache miss**: If cache miss, proceed with existing build loop.
Inside the for loop, around each chapter's render + paginate:
1. **Render timing**: Wrap `renderer.renderChapter(request:)` (line 158) with `CFAbsoluteTimeGetCurrent()` before and after
2. **Paginate timing**: Wrap `content.rd_paginatedFrames(size:)` (line 196) with `CFAbsoluteTimeGetCurrent()` before and after
3. **Record sample**: After getting layoutFrames, record:
```swift
sampler.record(RDEPUBTextPerformanceSample(
chapterHref: item.href,
renderDuration: renderDuration,
paginateDuration: paginateDuration,
pageCount: effectiveFrames.count,
attributedStringLength: content.length,
cacheHit: false
))
```
4. **Miss counter**: `lastBuildCacheStats.misses += 1`
After the loop, before returning:
1. **Set total build duration**: `sampler.totalBuildDuration = CFAbsoluteTimeGetCurrent() - buildStart`
2. **Save to cache**: If cache available and key was generated, `cache.save(book, key: cacheKey)`
3. **Print summary**: `print(sampler.summary())`
4. **Store samples**: `lastBuildPerformanceSamples = sampler.samples`
**Step 5: Update build() method signature** — keep the existing signature unchanged. The cache is accessed via the stored property, not a method parameter.
**Important implementation notes**:
- All timing uses `CFAbsoluteTimeGetCurrent()` (no external deps, per D-04)
- Timing happens on the same queue as the build (DispatchQueue.global(qos: .userInitiated)), not dispatched to main
- The `publication.metadata.identifier` or equivalent needs to be accessible — check the `RDEPUBPublication` type for an identifier field
- If publication has no identifier, skip cache (return nil from makeCacheKey)
</action>
<verify>
<automated>xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' 2>&1 | tail -5</automated>
</verify>
<acceptance_criteria>
- `RDEPUBTextBookBuilder` has `lastBuildPerformanceSamples: [RDEPUBTextPerformanceSample]` property
- `RDEPUBTextBookBuilder` has `lastBuildCacheStats: (hits: Int, misses: Int)` property
- `RDEPUBTextBookBuilder` init accepts optional `cache: RDEPUBTextBookCache?` parameter (defaults to nil)
- `build()` method contains `CFAbsoluteTimeGetCurrent()` timing calls for render and paginate
- `build()` method calls `cache.load(key:)` before the build loop when cache is available
- `build()` method calls `cache.save(_:key:)` after the build loop when cache is available
- `build()` method calls `sampler.record()` for each chapter with timing data
- `build()` method prints `sampler.summary()` at the end
- Existing `convenience init()` still works (cache defaults to nil)
- Build succeeds with no regressions
</acceptance_criteria>
<done>
RDEPUBTextBookBuilder.build() is instrumented with per-chapter render/paginate timing, cache hit/miss logging, and performance sample recording. Cache integration skips build on hit and stores result on miss. Build succeeds.
</done>
</task>
</tasks>
<threat_model>
## Trust Boundaries
| Boundary | Description |
|----------|-------------|
| builder → cache | Builder writes to cache after successful build; corrupted cache could return invalid RDEPUBTextBook on next load |
## STRIDE Threat Register
| Threat ID | Category | Component | Disposition | Mitigation |
|-----------|----------|-----------|-------------|------------|
| T-08-04 | Tampering | Cache integration in builder | accept | Cache is optional (nil default); NSKeyedArchiver deserialization fails safely returning nil |
| T-08-SC | Tampering | npm/pip/cargo installs | mitigate | No external packages installed in this phase |
</threat_model>
<verification>
- `xcodebuild build -scheme ReadViewDemo` succeeds
- Builder init accepts optional cache parameter
- build() method has CFAbsoluteTimeGetCurrent timing instrumentation
- Cache load/save calls are present in build() flow
- Performance samples accessible via lastBuildPerformanceSamples
- Console shows [PERF] summary and [Cache] HIT/MISS logs
</verification>
<success_criteria>
- Per-chapter render and paginate durations are recorded
- Total build time is captured
- Cache hit skips the entire build loop
- Cache miss runs full build and stores result
- Performance summary printed to console after each build
- No functional regression: book opens, paginates, and displays correctly
</success_criteria>
<output>
Create `.planning/phases/08-pagination-quality-cache-performance/08-03-SUMMARY.md` when done
</output>

View File

@ -1,45 +0,0 @@
# Plan 08-03 Summary: Performance Sampling + Cache Integration
## Status: COMPLETE
## What Was Done
### Task 1: Created RDEPUBTextPerformanceSampler.swift
- **File**: `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift` (new)
- `RDEPUBTextPerformanceSample` struct with `chapterHref`, `renderDuration`, `paginateDuration`, `pageCount`, `attributedStringLength`, `cacheHit`
- `RDEPUBTextPerformanceSampler` class with `record(_:)`, `summary()`, `reset()`, `totalBuildDuration`, `samples`
- Per-chapter `[PERF]` console logging with millisecond formatting
### Task 2: Instrumented RDEPUBTextBookBuilder with cache + performance
- **File**: `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` (modified)
- Added `cache: RDEPUBTextBookCache?` (optional, defaults to nil for backward compat)
- Added `sampler: RDEPUBTextPerformanceSampler` (always created)
- Added `lastBuildPerformanceSamples: [RDEPUBTextPerformanceSample]`
- Added `lastBuildCacheStats: (hits: Int, misses: Int)`
- `build()` method now:
- Checks cache before building (cache HIT returns immediately)
- Wraps `renderer.renderChapter()` with `CFAbsoluteTimeGetCurrent()` timing
- Wraps `content.rd_paginatedFrames()` with timing
- Records per-chapter `RDEPUBTextPerformanceSample`
- Saves to cache on miss after successful build
- Prints `[PERF]` summary at end
- Added `makeCacheKey()` helper using `publication.metadata.identifier ?? publication.metadata.title`
### Pre-existing fixes (not in plan scope but required for clean build)
- **RDEPUBTextBookCache.swift**: Changed 4 `private final class` to `final class` to fix NSCoding "unstable name" errors (Swift compiler change in newer SDK)
- **RDEPUBSelectionOverlayView.swift**: Fixed empty array literal type annotation and commented-out code
## Files Modified
| File | Action |
|------|--------|
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift` | CREATED |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` | MODIFIED |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift` | MODIFIED (pre-existing NSCoding fix) |
| `Sources/RDReaderView/EPUBUI/RDEPUBSelectionOverlayView.swift` | MODIFIED (pre-existing error fix) |
## Build Verification
- `xcodebuild build -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17 Pro'` -- **BUILD SUCCEEDED**
## Key Links Established
- `RDEPUBTextBookBuilder` -> `RDEPUBTextBookCache` via `cache.load(key:)` / `cache.save(_:key:)`
- `RDEPUBTextBookBuilder` -> `RDEPUBTextPerformanceSampler` via `sampler.record(sample)`

View File

@ -1,160 +0,0 @@
# Phase 8: 分页质量、缓存与性能采样 - Context
**Gathered:** 2026-05-23
**Updated:** 2026-05-23 (research corrected: D-01/D-02/D-04/D-05 already implemented)
**Status:** Ready for planning
**Source:** ARCHITECTURE-CONTEXT.md + REQUIREMENTS.md (QUAL-01 ~ QUAL-04) + 08-RESEARCH.md
---
<domain>
## Phase Boundary
Phase 8 在 Phase 6页面几何和 Phase 7自定义属性闭环之上解决三个问题
1. **缓存**:相同视口 + 排版配置下,同一章节不重复全量排版 (QUAL-01)
2. **分页质量**:复杂图文章节减少粗暴截断、孤行/寡行、图片留白异常 (QUAL-02, QUAL-03)
3. **性能诊断**:输出稳定的采样数据,确保不出现明显退化 (QUAL-04)
本阶段**不**涉及 CoreText 直接绘制迁移v1.2+**不**涉及字体系统。
实现时可直接参考读书 (WXRead) 的对应实现模式。
### 已完成的能力(研究发现)
以下能力在之前的 Phase 中已经实现Phase 8 不需要重新实现:
- **D-01 分页引擎集成**: `RDEPUBTextBookBuilder.build()` 已调用 `content.rd_paginatedFrames(size:)`(非旧的 `ss_pageRanges`
- **D-02 分页元数据暴露**: `RDEPUBTextPageMetadata` 已定义并包含 breakReason/blockKinds/semanticHints
- **D-04 CSS `<link>` 内联**: 已在渲染前处理 `<link>` 标签
- **D-05 5 层 CSS 级联**: `RDEPUBTextStyleSheetPackage`/`RDEPUBTextStyleSheetLayer` 已在使用
</domain>
<decisions>
## Implementation Decisions
### D-01: 分页缓存 — RDEPUBTextBook 序列化 [P0, QUAL-01]
`bookID + fontSize + lineHeightMultiple + contentInsets` 生成缓存 key将完整 `RDEPUBTextBook` 序列化到磁盘。
- **WXRead 参考:** `WRChapterPageCount.currentCacheKeyWithBookId:` 按排版设置缓存
- **关键文件:** `RDEPUBTextBookBuilder.swift`,新增 `RDEPUBTextBookCache.swift`
- **技术决策:**
- 缓存 key: `SHA256("\(bookID)_\(fontSize)_\(lineHeightMultiple)_\(contentInsets)")` + schema version
- 存储格式: `NSKeyedArchiver``NSAttributedString` 支持 `NSCoding``NSRange` 同理)
- 需运行时验证 DTCoreText 自定义属性在 `NSKeyedArchiver` 下的持久性
- 失效策略: 参数变化自动失效 + schema version bump 强制失效
- 存储位置: `Library/Caches` 子目录
### D-02: 分页质量增强 — 避让规则执行 [P0, QUAL-02]
`RDEPUBTextLayouter``avoidPageBreakInside` 的语义标记需要实际执行避让(当前仅有标记无行为),并增加孤行/寡行控制。
- **WXRead 参考:** `WRCoreTextLayoutFrame.avoidPageBreakInsideByRemovingLastLinesIfNeeded` — CSS `avoid-page-break-inside` 实现
- **关键文件:** `RDEPUBTextLayouter.swift`、`RDEPUBTextLayoutFrame.swift`
- **技术决策:**
- `avoidPageBreakInside`: 检测 block 最后 1-2 行被切到下一页时,将整个 block 移到下一页
- 孤行控制: 页首不允许出现段落最后一行orphan页尾不允许出现段落第一行widow
- 增加 `RDEPUBTextLayoutConfig` 结构体封装分页配置(孤行/寡行阈值等),或先硬编码合理默认值
### D-03: 图片/附件处理规则 [P1, QUAL-03]
图片尺寸策略、暗色模式适配、页面背景类信息有明确处理规则和诊断证据。
- **WXRead 参考:** `wr-vertical-center-style`(图片垂直居中)、`DTPageBreakInsideAvoid`(断页避让)
- **关键文件:** `RDEPUBTextLayoutFrame.swift`、`RDEPUBTextRendererSupport.swift`、`RDEPUBDTCoreTextRenderer.swift`
- **技术决策:**
- 图片 fit: 超过页面高度的图片按比例缩放到页面内,不跨页
- 图片居中: 附件类 block 默认垂直居中处理
- 暗色模式: 图片在暗色模式下保留原始颜色(不反色),但为纯文本装饰元素提供适配
- 诊断: 每个 attachment block 输出尺寸、placement、是否触发缩放
### D-04: 性能采样与诊断输出 [P1, QUAL-04]
分页深化后不显著恶化首屏时间、重分页耗时或交互流畅度;输出稳定采样数据。
- **关键文件:** `RDEPUBTextBookBuilder.swift`
- **技术决策:**
- 采样点: 每章渲染耗时、每章分页耗时、全书构建总耗时、缓存命中/未命中
- 输出方式: `RDEPUBTextBookBuilder` 回调中新增 `buildDiagnostics` 字段,包含耗时和缓存状态
- 不引入外部性能监控库,使用 `CFAbsoluteTimeGetCurrent()` 采样
### Claude's Discretion
- 缓存存储的线程安全策略(串行队列 vs 锁)
- `RDEPUBTextLayoutConfig` 是新增结构体还是扩展已有类型
- 性能诊断的阈值告警(可选,初期仅输出数据不告警)
### 强制约束:编译验证
每个 task 代码编写完成后,**必须**通过 XcodeBuildMCP 工具执行编译验证,确认无编译错误后方可标记 task 完成。若有编译问题需立即修复并重新验证。
- 工具: XcodeBuildMCP (`build_sim` / `run_build_sim`)
- 配置: workspace = `ReadViewDemo/ReadViewDemo.xcworkspace`, scheme = `ReadViewDemo`, simulator = `iPhone 17 Pro`
- 流程: 代码修改 → XcodeBuildMCP build → 有错误则修复 → 重新 build → 通过后继续
</decisions>
<canonical_refs>
## Canonical References
**Downstream agents MUST read these before planning or implementing.**
### Phase 8 核心文件
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` — 书籍构建器,已调用 rd_paginatedFrames
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPaginationSupport.swift` — 分页支持
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` — CoreText 分页引擎4 级语义断页
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift` — 帧模型
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` — 渲染协议、样式表类型
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBDTCoreTextRenderer.swift` — DTCoreText 渲染实现
- `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift` — 片段标记、属性标准化
### WXRead 逆向参考(实现时可直接参考)
- `Doc/WXRead/decompiled-doc.md` — 44 个逆向文件的职责说明
- `Doc/WXRead/resources-doc.md` — CSS/JS 资源文件清单与职责
- `Doc/WXRead/读书EPUB阅读器实现架构.md` — 双渲染引擎架构总览
### 架构文档
- `.planning/ARCHITECTURE-CONTEXT.md` — 4 Area 决策总览
- `Doc/架构对比分析_WXRead_vs_ReadViewSDK.md` — 10 维度对比
- `08-RESEARCH.md` — 研究产出(本目录下)
### 前置 Phase 成果
- Phase 6 SUMMARY: 页面几何与交互命中层
- Phase 7 SUMMARY: 自定义属性闭环avoidPageBreakInside/pageBreakBefore/pageBreakAfter/pageRelate 已注入 attributedString
</canonical_refs>
<specifics>
## Specific Ideas
### 缓存 key 设计
```
cacheKey = SHA256("\(bookID)_\(fontSize)_\(lineHeightMultiple)_\(contentInsets.top)_\(contentInsets.left)_\(contentInsets.bottom)_\(contentInsets.right)_v\(schemaVersion)")
```
- schemaVersion = 1代码变更导致缓存格式不兼容时 bump
- 失效条件:参数变化自动失效 + schema version bump 强制失效
- 存储Library/Caches/RDEPUBTextBookCache/ 目录
### 性能采样点
- 每章渲染耗时DTHTMLAttributedStringBuilder
- 每章分页耗时CTFramesetter pagination
- 全书构建总耗时
- 缓存命中/未命中计数
### avoidPageBreakInside 执行策略
```
当 CTFrame 可见范围尾部落在 avoidPageBreakInside block 内部时:
1. 向前扫描找到 block 起始位置
2. 将分页点移到 block 起始之前
3. 将整个 block 推到下一页
```
</specifics>
<deferred>
## Deferred Ideas
- **CoreText 直接绘制迁移**: v1.2/v2.0,超出本阶段范围
- **字体系统**: 内嵌固定字体集,后续版本
- **字符级位置精度**: P2与 CoreText 迁移关联
- **章节数据模型内聚**: P2独立重构
- **TTS / DRM / Pencil / 多栏排版**: P3独立功能模块
- **NSKeyedArchiver 对 DTCoreText 属性持久性验证**: 需运行时测试,若失败则降级为 decomposed JSON 策略
</deferred>
---
*Phase: 08-pagination-quality-cache-performance*
*Context gathered: 2026-05-23*
*Updated after research: D-01/D-02/D-04/D-05 confirmed already implemented*

View File

@ -1,459 +0,0 @@
# Phase 8: Pagination Quality, Cache & Performance Sampling - Pattern Map
**Mapped:** 2026-05-23
**Files analyzed:** 7 (2 new, 5 modified)
**Analogs found:** 7 / 7
## File Classification
| New/Modified File | Role | Data Flow | Closest Analog | Match Quality |
|---|---|---|---|---|
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift` (NEW) | utility | file-I/O | `Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift` | role-match |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift` (NEW) | utility | transform | (none — standard iOS pattern) | no-analog |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` (MODIFY) | controller | request-response | self | exact |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` (MODIFY) | service | transform | self | exact |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift` (MODIFY) | model | transform | self | exact |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift` (MODIFY) | utility | transform | self | exact |
| `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` (MODIFY) | model | transform | self | exact |
## Pattern Assignments
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookCache.swift` (NEW — utility, file-I/O)
**Analog:** `Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift`
**File I/O pattern — cachesDirectory + FileManager** (lines 55-66):
```swift
func temporaryExtractionDirectory(for epubURL: URL) -> URL {
let baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
.appendingPathComponent("ssreaderview-epub", isDirectory: true)
?? FileManager.default.temporaryDirectory.appendingPathComponent("ssreaderview-epub", isDirectory: true)
let fileAttributes = try? FileManager.default.attributesOfItem(atPath: epubURL.path)
let fileSize = (fileAttributes?[.size] as? NSNumber)?.stringValue ?? "0"
let modifiedAt = (fileAttributes?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0
let slug = epubURL.deletingPathExtension().lastPathComponent
.replacingOccurrences(of: " ", with: "-")
let signature = String(format: "%.0f", modifiedAt)
return baseURL.appendingPathComponent("\(slug)-\(fileSize)-\(signature)", isDirectory: true)
}
```
**Directory creation pattern** (lines 37):
```swift
try fileManager.createDirectory(at: extractionURL, withIntermediateDirectories: true)
```
**File existence check** (lines 29):
```swift
if fileManager.fileExists(atPath: extractionURL.path) {
return extractionURL
}
```
**Codable pattern for metadata** — `Sources/RDReaderView/EPUBCore/RDEPUBReadingModels.swift` lines 183-214:
```swift
public struct RDEPUBTextPageMetadata: Codable, Equatable {
public var breakReason: RDEPUBTextPageBreakReason
public var blockRange: NSRange?
public var attachmentRanges: [NSRange]
// ...
}
```
Note: `RDEPUBTextPageMetadata` declares `Codable` conformance but uses `NSRange` fields. The cache implementation must handle `NSRange` serialization — either via `NSKeyedArchiver` (which handles `NSAttributedString` + `NSRange` natively) or via a custom `Codable` wrapper that encodes `NSRange` as `{location: Int, length: Int}`.
**Conventions to follow:**
- `RDEPUB` prefix for all public types
- `public` access for API types, `internal` for implementation details
- Struct-based value types preferred (see `RDEPUBTextRenderStyle`, `RDEPUBTextChapter`)
- `Equatable` conformance on data types
- Cache subdirectory name: `RDEPUBTextBookCache` under `Library/Caches`
**New type — `RDEPUBTextBookCache`** should follow this structure:
```swift
import Foundation
import CryptoKit // for SHA256
public final class RDEPUBTextBookCache {
private let cacheDirectory: URL
private let queue = DispatchQueue(label: "com.rdreader.textbookcache", qos: .utility)
private let schemaVersion: Int = 1
public init(subdirectory: String = "RDEPUBTextBookCache") {
let base = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
self.cacheDirectory = base.appendingPathComponent(subdirectory, isDirectory: true)
try? FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
}
public func cacheKey(bookID: String, fontSize: CGFloat, lineHeightMultiple: CGFloat, contentInsets: UIEdgeInsets, pageSize: CGSize) -> String {
// SHA256 hash for safe filename
}
public func load(key: String) -> RDEPUBTextBook? { ... }
public func save(_ book: RDEPUBTextBook, key: String) { ... }
public func invalidateAll() { ... }
}
```
---
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextPerformanceSampler.swift` (NEW — utility, transform)
**No close analog in codebase.** Use standard iOS performance measurement pattern.
**Conventions to follow** (from existing types in `RDEPUBTextRenderer.swift`):
```swift
// Public struct pattern — line 90-113
public struct RDEPUBTextResourceReferenceDiagnostic: Equatable {
public var kind: RDEPUBTextResourceReferenceKind
public var chapterHref: String
// ...
public init(kind: ..., chapterHref: ..., ...) { ... }
}
```
**New type structure:**
```swift
import Foundation
public struct RDEPUBTextPerformanceSample: Equatable {
public var chapterHref: String
public var renderDuration: TimeInterval
public var paginateDuration: TimeInterval
public var pageCount: Int
public var attributedStringLength: Int
public var cacheHit: Bool
public init(chapterHref: String, renderDuration: TimeInterval, paginateDuration: TimeInterval, pageCount: Int, attributedStringLength: Int, cacheHit: Bool) { ... }
}
public final class RDEPUBTextPerformanceSampler {
public private(set) var samples: [RDEPUBTextPerformanceSample] = []
public func record(_ sample: RDEPUBTextPerformanceSample) { ... }
public func summary() -> String { ... }
public func reset() { samples.removeAll() }
}
```
**Measurement pattern:**
```swift
let start = CFAbsoluteTimeGetCurrent()
// ... operation ...
let duration = CFAbsoluteTimeGetCurrent() - start
```
---
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextBookBuilder.swift` (MODIFY — controller, request-response)
**Analog:** self (exact match)
**Cache integration point** — insert before the `for` loop at line 143:
```swift
public func build(
parser: RDEPUBParser,
publication: RDEPUBPublication,
pageSize: CGSize,
style: RDEPUBTextRenderStyle
) throws -> RDEPUBTextBook {
// NEW: Performance sampling
let buildStart = CFAbsoluteTimeGetCurrent()
// NEW: Cache lookup
// if let cached = cache.load(key: cacheKey) { return cached }
var chapters: [RDEPUBTextChapter] = []
var flatPages: [RDEPUBTextPage] = []
// ... existing loop ...
// NEW: Cache save + performance record
// cache.save(book, key: cacheKey)
// sampler.record(sample)
return RDEPUBTextBook(chapters: chapters, pages: flatPages)
}
```
**Diagnostics property pattern** — existing at lines 98-99:
```swift
public private(set) var lastBuildResourceDiagnostics: [RDEPUBTextResourceReferenceDiagnostic] = []
public private(set) var lastBuildPaginationDiagnostics: [RDEPUBTextChapterPaginationDiagnostic] = []
```
Add similar for performance:
```swift
public private(set) var lastBuildPerformanceSamples: [RDEPUBTextPerformanceSample] = []
public private(set) var lastBuildCacheStats: (hits: Int, misses: Int) = (0, 0)
```
**Initializer pattern** — existing at lines 101-107:
```swift
public init(renderer: RDEPUBTextRenderer) {
self.renderer = renderer
}
public convenience init() {
self.init(renderer: RDEPUBDTCoreTextRenderer())
}
```
Add optional cache parameter:
```swift
public init(renderer: RDEPUBTextRenderer, cache: RDEPUBTextBookCache? = nil) {
self.renderer = renderer
self.cache = cache
}
```
---
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayouter.swift` (MODIFY — service, transform)
**Analog:** self (exact match)
**avoidPageBreakInside enforcement** — insert into `adjustedRange()` at line 64, after the `preferredSemanticBoundary` check (line 114-139) but before `preferredAttachmentBoundary` (line 141):
The existing `preferredSemanticBoundary` at lines 243-250 already handles `avoidPageBreakInside` as a semantic hint boundary. The enhancement is to make this more aggressive — when the proposed page end falls INSIDE an `avoidPageBreakInside` block, push the entire block to the next page:
```swift
// After preferredSemanticBoundary returns nil, check if pageEnd
// falls inside an avoidPageBreakInside block
if let avoidBoundary = avoidPageBreakInsideBoundary(
in: proposedRange,
pageEnd: pageEnd,
minimumEnd: minimumEnd
) {
// Push to block start
let adjustedRange = NSRange(location: proposedRange.location, length: avoidBoundary - proposedRange.location)
return (range: adjustedRange, breakReason: .semanticBoundary, ...)
}
```
**Orphan/widow control** — add new private method after `preferredBlockBoundary` (line 268):
```swift
private func orphanWidowAdjustedRange(
from proposedRange: NSRange,
totalLength: Int
) -> NSRange? {
// Check if page starts with last line of paragraph (orphan)
// Check if page ends with first line of paragraph (widow)
// Use paragraphRange(containing:) pattern from line 294-298
}
```
**Existing paragraph range helper** — line 294-298:
```swift
private func paragraphRange(containing location: Int) -> NSRange {
let source = attributedString.string as NSString
guard source.length > 0 else { return NSRange(location: 0, length: 0) }
let safeLocation = min(max(location, 0), max(source.length - 1, 0))
return source.paragraphRange(for: NSRange(location: safeLocation, length: 0))
}
```
**Config type** — add to `RDEPUBTextRenderer.swift` (see below), then use in layouter init:
```swift
struct RDEPUBTextLayouter {
private let attributedString: NSAttributedString
private let pageSize: CGSize
private let config: RDEPUBTextLayoutConfig // NEW
// ...
init(attributedString: NSAttributedString, pageSize: CGSize, config: RDEPUBTextLayoutConfig = .default) {
self.config = config
// ...
}
}
```
---
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextLayoutFrame.swift` (MODIFY — model, transform)
**Analog:** self (exact match)
Current structure (lines 3-28):
```swift
struct RDEPUBTextLayoutFrame: Equatable {
var contentRange: NSRange
var breakReason: RDEPUBTextPageBreakReason
var blockRange: NSRange?
var attachmentRanges: [NSRange]
var attachmentKinds: [RDEPUBTextAttachmentKind]
var blockKinds: [RDEPUBTextBlockKind]
var semanticHints: [RDEPUBTextSemanticHint]
var attachmentPlacements: [RDEPUBTextAttachmentPlacement]
var trailingFragmentID: String?
var diagnostics: [String]
var metadata: RDEPUBTextPageMetadata { ... }
}
```
No structural changes needed for this file. The `RDEPUBTextLayoutConfig` type goes in `RDEPUBTextRenderer.swift` (see next).
---
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRendererSupport.swift` (MODIFY — utility, transform)
**Analog:** self (exact match)
**Image sizing enhancement** — extend `prepareHTMLElementForReaderRendering` at line 217-262. The existing method already handles footnote and cover images. Add general image fit-to-page logic:
Existing pattern for image sizing (lines 243-261):
```swift
if lowercasedClasses.contains("rd-front-cover-image") || lowercasedPath == "cover.jpg" {
let maxSize = UIScreen.main.bounds.insetBy(dx: 20, dy: 28).size
let originalSize = attachment.originalSize
if originalSize.width > 0, originalSize.height > 0 {
let scale = min(maxSize.width / originalSize.width, maxSize.height / originalSize.height)
attachment.displaySize = CGSize(
width: round(originalSize.width * scale),
height: round(originalSize.height * scale)
)
}
attachment.verticalAlignment = .baseline
element.displayStyle = .block
}
```
Add general image sizing after the cover check (around line 261):
```swift
// General image: fit within page height, do not cross pages
if attachment.image != nil || attachment.fileType?.lowercased().contains("image") == true {
let originalSize = attachment.originalSize
let maxImageHeight = UIScreen.main.bounds.insetBy(dx: 20, dy: 28).height
if originalSize.height > maxImageHeight {
let scale = maxImageHeight / originalSize.height
attachment.displaySize = CGSize(
width: round(originalSize.width * scale),
height: round(maxImageHeight)
)
}
// Center vertically if not already set
if element.displayStyle == .block {
attachment.verticalAlignment = .center
}
}
```
**Diagnostic output for attachments** — the existing `print("[EPUB][Attachment]...")` pattern at lines 237-239, 258-259 shows how diagnostics are emitted. Extend with size/placement/scale info.
---
### `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` (MODIFY — model, transform)
**Analog:** self (exact match)
**Add `RDEPUBTextLayoutConfig` struct** — insert after `RDEPUBTextRenderStyle` (line 48), following the same struct pattern:
```swift
public struct RDEPUBTextLayoutConfig: Equatable {
public var avoidOrphans: Bool
public var avoidWidows: Bool
public var avoidPageBreakInsideEnabled: Bool
public var imageMaxHeightRatio: CGFloat // ratio of page height
public init(
avoidOrphans: Bool = true,
avoidWidows: Bool = true,
avoidPageBreakInsideEnabled: Bool = true,
imageMaxHeightRatio: CGFloat = 0.85
) {
self.avoidOrphans = avoidOrphans
self.avoidWidows = avoidWidows
self.avoidPageBreakInsideEnabled = avoidPageBreakInsideEnabled
self.imageMaxHeightRatio = imageMaxHeightRatio
}
public static let `default` = RDEPUBTextLayoutConfig()
}
```
Pattern source — `RDEPUBTextRenderStyle` at lines 36-48:
```swift
public struct RDEPUBTextRenderStyle {
public var font: UIFont
public var lineSpacing: CGFloat
public var textColor: UIColor?
public var backgroundColor: UIColor?
public init(font: UIFont, lineSpacing: CGFloat, textColor: UIColor? = nil, backgroundColor: UIColor? = nil) {
self.font = font
self.lineSpacing = lineSpacing
self.textColor = textColor
self.backgroundColor = backgroundColor
}
}
```
## Shared Patterns
### File I/O — Cache Directory
**Source:** `Sources/RDReaderView/EPUBCore/RDEPUBParser+Archive.swift` lines 55-66
**Apply to:** `RDEPUBTextBookCache.swift`
```swift
let baseURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?
.appendingPathComponent("RDEPUBTextBookCache", isDirectory: true)
?? FileManager.default.temporaryDirectory.appendingPathComponent("RDEPUBTextBookCache", isDirectory: true)
try FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories: true)
```
### Thread Safety — Serial Dispatch Queue
**Source:** No existing pattern in EPUBTextRendering (no concurrent access currently). Standard iOS approach.
**Apply to:** `RDEPUBTextBookCache.swift`
```swift
private let queue = DispatchQueue(label: "com.rdreader.textbookcache", qos: .utility)
// All cache read/write operations wrapped in queue.sync { }
```
### Struct Declaration Pattern
**Source:** `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` lines 36-48, 58-66, 68-83
**Apply to:** All new struct types (`RDEPUBTextLayoutConfig`, `RDEPUBTextPerformanceSample`, `RDEPUBTextBookCacheKey`)
```swift
public struct RDEPUBTextTypeName: Equatable {
public var propertyName: PropertyType
public init(propertyName: PropertyType) {
self.propertyName = propertyName
}
}
```
### Enum Declaration Pattern
**Source:** `Sources/RDReaderView/EPUBTextRendering/RDEPUBTextRenderer.swift` lines 13-21, 23-28, 50-56
**Apply to:** Any new enums
```swift
public enum RDEPUBTextEnumName: String, Codable, Equatable, CaseIterable {
case value1
case value2
}
```
### Performance Measurement
**Source:** No codebase analog. Standard iOS pattern.
**Apply to:** `RDEPUBTextBookBuilder.swift` build method, `RDEPUBTextPerformanceSampler.swift`
```swift
let start = CFAbsoluteTimeGetCurrent()
// ... operation ...
let duration = CFAbsoluteTimeGetCurrent() - start
```
### NSAttributedString Serialization (Cache)
**Source:** No codebase analog. `NSAttributedString` supports `NSCoding`.
**Apply to:** `RDEPUBTextBookCache.swift`
```swift
// Archive
let data = try NSKeyedArchiver.archivedData(withRootObject: attributedString, requiringSecureCoding: false)
// Unarchive
let attributedString = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data)
```
## No Analog Found
| File | Role | Data Flow | Reason |
|---|---|---|---|
| `RDEPUBTextPerformanceSampler.swift` | utility | transform | No existing performance measurement code in project |
| `RDEPUBTextBookCache.swift` (serialization) | utility | file-I/O | No `NSKeyedArchiver` usage in project; `NSAttributedString` + `NSCoding` is new territory |
## Metadata
**Analog search scope:** `Sources/RDReaderView/EPUBTextRendering/`, `Sources/RDReaderView/EPUBCore/`, `Sources/RDReaderView/`
**Files scanned:** 12
**Pattern extraction date:** 2026-05-23

View File

@ -1,485 +0,0 @@
# Phase 8: 分页质量、缓存与性能采样 - Research
**Researched:** 2026-05-23
**Domain:** iOS/Swift EPUB reader - pagination caching, quality improvement, performance sampling
**Confidence:** HIGH
## Summary
Phase 8 builds on Phase 6 (page geometry) and Phase 7 (custom attribute closure) to address three concerns: pagination caching, pagination quality for complex image-heavy chapters, and performance diagnostics.
**Critical finding:** Several capabilities assumed to be "not yet integrated" in CONTEXT.md and ARCHITECTURE-CONTEXT.md are actually already implemented:
- `RDEPUBTextBookBuilder.build()` already calls `content.rd_paginatedFrames(size:)` (not `ss_pageRanges`). The integration is DONE.
- CSS `<link>` inlining is already implemented via `inlineLinkedStyleSheets()` in `RDEPUBTextRendererSupport`.
- The 5-layer CSS cascade is already implemented via `makeStyleSheetLayers()` producing `RDEPUBTextStyleSheetPackage` layers.
- `RDEPUBTextPage.metadata` is already populated with `RDEPUBTextPageMetadata` from `frame.metadata`.
**What actually needs building:**
1. **Pagination cache** (QUAL-01): Serialize `RDEPUBTextBook` to disk, keyed by layout parameters
2. **Image/attachment rules** (QUAL-03): Formalize sizing, dark mode, and page-break-around-image rules
3. **Performance sampling** (QUAL-04): Instrument render/paginate/build timings
4. **Pagination quality** (QUAL-02): Implement `avoidPageBreakInside` line-removal, orphan/widow control, image fit enforcement
**Primary recommendation:** Focus Phase 8 on cache serialization (the largest new code), performance instrumentation (straightforward), and incremental pagination quality improvements. Do NOT re-implement CSS `<link>` inlining or 5-layer cascade -- they already work.
## Architectural Responsibility Map
| Capability | Primary Tier | Secondary Tier | Rationale |
|------------|-------------|----------------|-----------|
| Pagination cache storage | API / Backend (file system) | -- | Cache is local disk persistence, no UI involvement |
| Cache key generation | API / Backend | -- | Pure computation from layout parameters |
| Performance timing | API / Backend | -- | CFAbsoluteTimeGetCurrent at build/render points |
| Image sizing rules | API / Backend (renderer) | Browser/Client (display) | Rules applied during DTCoreText rendering |
| avoidPageBreakInside enforcement | API / Backend (layouter) | -- | CoreText line-level calculation |
| Orphan/widow control | API / Backend (layouter) | -- | CoreText line-level calculation |
| Pagination diagnostic output | API / Backend | Browser/Client (logging) | Diagnostic data flows to console/log |
## User Constraints (from CONTEXT.md)
### Locked Decisions
- **D-01 [P0]:** Integrate `RDEPUBTextLayouter` into `RDEPUBTextBookBuilder` -- ALREADY DONE (see finding above)
- **D-02 [P0]:** Expose `metadata: RDEPUBTextPageMetadata` on `RDEPUBTextPage` -- ALREADY DONE
- **D-03 [P0]:** Pagination cache by `bookID + fontSize + lineHeightMultiple + contentInsets`, cache full `RDEPUBTextBook` to disk
- **D-04 [P0]:** CSS `<link>` inline processing -- ALREADY DONE
- **D-05 [P0]:** 5-layer CSS cascade -- ALREADY DONE
- **D-06 [P1]:** Image/attachment processing rules with diagnostics
- **D-07 [P1]:** Performance sampling -- output stable sampling data
### Claude's Discretion
- Cache storage format (file system plist/JSON vs SQLite) -- implementer decides
- CSS cascade replace.css content -- reference WXRead but don't copy exactly
- Performance sampling threshold values -- determine at implementation time
### Deferred Ideas (OUT OF SCOPE)
- CoreText direct drawing migration (v1.2/v2.0)
- Font system (embedded font set, future version)
- Character-level position precision (P2)
- Chapter data model cohesion (P2)
- TTS / DRM / Pencil / multi-column layout (P3)
<phase_requirements>
## Phase Requirements
| ID | Description | Research Support |
|----|-------------|------------------|
| QUAL-01 | Cache mechanism for layout frames/pagination results to avoid redundant full-layout | Cache key design from WXRead `WRChapterPageCount.currentCacheKeyWithBookId:`, serialization strategy for `RDEPUBTextBook` |
| QUAL-02 | Improve pagination quality for complex image-heavy chapters -- reduce bad breaks, orphan/widow lines, image whitespace issues, code/table truncation | WXRead `avoidPageBreakInsideByRemovingLastLinesIfNeeded` pattern, `WRCoreTextLayoutConfig` widow/orphan settings |
| QUAL-03 | Image/attachment sizing rules, dark mode adaptation, page background info with verifiable rules | WXRead `wr-vertical-center-style`, `DTPageBreakInsideAvoid`, existing `prepareHTMLElementForReaderRendering` |
| QUAL-04 | No significant degradation of first-screen time, repagination time, or interaction fluidity; output stable diagnostic/sampling data | Performance sampling points at render/paginate/build, `CFAbsoluteTimeGetCurrent` pattern |
</phase_requirements>
## Standard Stack
### Core (no new external dependencies)
This phase uses only existing project dependencies and Apple frameworks:
| Library | Version | Purpose | Why Standard |
|---------|---------|---------|--------------|
| Foundation | iOS SDK | NSKeyedArchiver, JSONEncoder, FileManager | System framework, no alternative |
| CoreText | iOS SDK | CTFramesetter, CTFrame line inspection | Already used by RDEPUBTextLayouter |
| DTCoreText | (existing) | HTML-to-NSAttributedString | Already integrated |
| CryptoKit / CommonCrypto | iOS SDK | SHA256 for cache key hashing | System framework |
### Supporting
| Library | Version | Purpose | When to Use |
|---------|---------|---------|-------------|
| os.signpost | iOS 15+ | Performance instrumentation with Instruments integration | If structured performance logging desired |
### Alternatives Considered
| Instead of | Could Use | Tradeoff |
|------------|-----------|----------|
| NSKeyedArchiver for cache | JSONEncoder | JSON is human-readable but can't handle NSAttributedString natively; NSKeyedArchiver handles it but produces opaque binary |
| File system cache | SQLite | File system is simpler for whole-object caching; SQLite adds complexity for no gain when caching complete objects |
| SHA256 cache key | Simple string concatenation | SHA256 produces fixed-length keys safe for filenames; raw string could exceed filesystem limits |
**Installation:** No new packages needed.
## Package Legitimacy Audit
No external packages are installed in this phase. All dependencies are existing project dependencies or Apple system frameworks.
| Package | Registry | Age | Downloads | Source Repo | slopcheck | Disposition |
|---------|----------|-----|-----------|-------------|-----------|-------------|
| (none) | -- | -- | -- | -- | -- | N/A |
## Architecture Patterns
### Current Data Flow (already working)
```
RDEPUBReaderController.paginate(restoreLocation:)
-> RDEPUBTextBookBuilder.build(parser:publication:pageSize:style:)
-> for each spine item:
-> RDEPUBTextRendererSupport.makeChapterRenderRequest(...)
-> inlineLinkedStyleSheets() [CSS <link> inlining - DONE]
-> makeStyleSheetLayers() [5-layer cascade - DONE]
-> injectPaginationSemanticMarkers() [semantic markers - DONE]
-> renderer.renderChapter(request:) [DTCoreText render]
-> content.rd_paginatedFrames(size:) [4-level semantic pagination - DONE]
-> RDEPUBTextPage with metadata [metadata exposure - DONE]
-> RDEPUBTextBook(chapters:, pages:)
-> applyTextBook(restoreLocation:)
```
### Recommended Cache Integration Point
```
RDEPUBReaderController.paginate(restoreLocation:)
-> compute cacheKey from bookID + layout params
-> if cached RDEPUBTextBook exists for key:
-> applyTextBook(cachedBook, restoreLocation:) [CACHE HIT - skip build]
-> else:
-> builder.build(...) [existing flow]
-> save RDEPUBTextBook to cache [CACHE WRITE]
-> applyTextBook(textBook, restoreLocation:)
```
### Recommended Project Structure
```
Sources/RDReaderView/EPUBTextRendering/
├── RDEPUBTextBookBuilder.swift # existing - add cache integration
├── RDEPUBTextBookCache.swift # NEW - cache key, read/write, eviction
├── RDEPUBTextLayouter.swift # existing - add avoidPageBreakInside enforcement
├── RDEPUBTextLayoutFrame.swift # existing - no changes needed
├── RDEPUBTextPaginationSupport.swift # existing - no changes needed
├── RDEPUBTextRenderer.swift # existing - no changes needed
├── RDEPUBTextRendererSupport.swift # existing - add image rule formalization
├── RDEPUBDTCoreTextRenderer.swift # existing - no changes needed
├── RDEPUBTextPerformanceSampler.swift # NEW - timing instrumentation
└── RDPlainTextBookBuilder.swift # existing - no changes needed
```
### Pattern 1: Cache Key Generation
**What:** Generate a deterministic cache key from layout parameters that change pagination results.
**When to use:** Before every `builder.build()` call.
**Example:**
```swift
// Reference: WXRead WRChapterPageCount.currentCacheKeyWithBookId:
// WXRead encodes: bookId + fontSize + lineSpacing + pageWidth + pageHeight
struct RDEPUBTextBookCacheKey {
let bookID: String
let fontSize: CGFloat
let lineHeightMultiple: CGFloat
let contentInsets: UIEdgeInsets
let pageSize: CGSize
var stringValue: String {
let raw = "\(bookID)|\(fontSize)|\(lineHeightMultiple)|\(contentInsets.top)|\(contentInsets.left)|\(contentInsets.bottom)|\(contentInsets.right)|\(pageSize.width)|\(pageSize.height)"
// SHA256 for safe filename
let data = Data(raw.utf8)
let hash = SHA256.hash(data: data)
return hash.map { String(format: "%02x", $0) }.joined()
}
}
```
**Source:** [VERIFIED: Doc/WXRead/decompiled/WRChapterPageCount.m lines 64-90]
### Pattern 2: avoidPageBreakInside Line Removal
**What:** When a block marked `avoidPageBreakInside` would cross a page boundary, remove trailing lines from the current page to push the entire block to the next page.
**When to use:** During `RDEPUBTextLayouter.adjustedRange()` after the 4-level semantic break detection.
**Example:**
```swift
// Reference: WXRead WRCoreTextLayoutFrame.avoidPageBreakInsideByRemovingLastLinesIfNeeded
// If the proposed page end falls inside an avoidPageBreakInside block:
// 1. Find the block's start location
// 2. If block start >= minimumEnd, break at block start
// 3. If block start < minimumEnd (block is too large), fall through to frameLimit
```
**Source:** [VERIFIED: Doc/WXRead/decompiled/WRCoreTextLayoutFrame.h line 280]
### Pattern 3: Performance Sampling
**What:** Measure wall-clock time for render, paginate, and full-build operations.
**When to use:** At the entry/exit of `builder.build()`, `renderer.renderChapter()`, and `content.rd_paginatedFrames()`.
**Example:**
```swift
struct RDEPUBTextPerformanceSample {
var chapterHref: String
var renderDuration: TimeInterval // DTHTMLAttributedStringBuilder
var paginateDuration: TimeInterval // CTFramesetter pagination
var totalDuration: TimeInterval // end-to-end
var attributedStringLength: Int
var pageCount: Int
var cacheHit: Bool
}
// Measurement pattern:
let start = CFAbsoluteTimeGetCurrent()
// ... operation ...
let duration = CFAbsoluteTimeGetCurrent() - start
```
**Source:** [ASSUMED] -- standard iOS performance measurement pattern
### Anti-Patterns to Avoid
- **Storing NSAttributedString via JSONEncoder:** NSAttributedString is not Codable. Use NSKeyedArchiver or store the raw HTML + re-render parameters instead.
- **Cache key that includes theme colors:** Theme (dark/light) changes CSS output but the pagination structure (NSRanges) is the same for the same font/size/insets. However, the attributed string content differs. Cache should store the full RDEPUBTextBook including styled content, so theme must be part of the key OR cache should store structure only and re-render content.
- **Measuring on main thread:** All build/paginate work happens on `DispatchQueue.global(qos: .userInitiated)`. Timing must be captured there, not dispatched back to main.
- **Infinite cache growth:** Must implement eviction (LRU or size-based) to prevent disk space issues.
## Don't Hand-Roll
| Problem | Don't Build | Use Instead | Why |
|---------|-------------|-------------|-----|
| SHA256 hashing | Custom hash function | CryptoKit or CommonCrypto | Cryptographic correctness, no collision risk |
| File system cache directory | Custom path logic | `FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)` | Standard iOS cache location, auto-managed by OS |
| Thread-safe cache access | Manual locks | `DispatchQueue` or `NSLock` | Standard concurrency pattern |
| Orphan/widow detection | Line counting heuristics | CTFrame line origins + paragraph range analysis | CoreText provides exact line positions |
**Key insight:** The hardest part of this phase is NOT the algorithms -- it's serializing `RDEPUBTextBook` which contains `NSAttributedString` (not Codable) and `NSRange` (not natively Codable in Swift). The serialization strategy is the most consequential design decision.
## Common Pitfalls
### Pitfall 1: NSAttributedString Serialization
**What goes wrong:** Attempting to JSONEncode an `RDEPUBTextBook` fails silently because `NSAttributedString` and `NSRange` are not Codable.
**Why it happens:** `RDEPUBTextPage.content` is `NSAttributedString`, and `RDEPUBTextPageMetadata` contains `[NSRange]` fields.
**How to avoid:** Use `NSKeyedArchiver` for the whole object, OR decompose into Codable parts (store HTML + parameters, re-render on load). The second approach is more resilient to code changes but slower on cache load.
**Warning signs:** `JSONEncoder.encode()` returns nil or throws.
### Pitfall 2: Cache Invalidation on Code Changes
**What goes wrong:** After updating the pagination engine code, cached results are stale but the cache key hasn't changed.
**Why it happens:** Cache key only encodes user-facing parameters (font, size, insets), not code version.
**How to avoid:** Include a schema version number in the cache key. Bump the version when pagination logic changes.
**Warning signs:** Pagination quality doesn't improve after code changes until cache is manually cleared.
### Pitfall 3: NSRange Codable in Metadata
**What goes wrong:** `RDEPUBTextPageMetadata` conforms to `Codable` but contains `NSRange` fields (`blockRange`, `attachmentRanges`) which don't have native Codable conformance.
**Why it happens:** `NSRange` is an Objective-C struct, not a Swift Codable type.
**How to avoid:** Add `Codable` conformance for `NSRange` via an extension that encodes as `{"location": Int, "length": Int}`, or use `NSKeyedArchiver` for the whole metadata.
**Warning signs:** Compiler error or runtime crash when encoding metadata.
### Pitfall 4: Image Pages Crossing Boundaries
**What goes wrong:** A large image that doesn't fit on the current page causes the page to have excessive whitespace or the image gets truncated.
**Why it happens:** CoreText treats `NSTextAttachment` as inline content and will break the line at the attachment, but doesn't check if the image height exceeds remaining page space.
**How to avoid:** Before pagination, check attachment heights against remaining page space. If an image won't fit, break the page before the image paragraph.
**Warning signs:** Pages with only 1-2 lines of text followed by a large gap.
### Pitfall 5: Cache Thread Safety
**What goes wrong:** Concurrent reads/writes to the cache directory cause file corruption or crashes.
**Why it happens:** `builder.build()` runs on a background queue, and multiple `paginate()` calls can overlap (pagination token pattern handles cancellation but not serialization).
**How to avoid:** Use a serial dispatch queue for all cache operations, or use `NSFileCoordinator` for file-level coordination.
**Warning signs:** Intermittent crashes on `NSKeyedUnarchiver.unarchiveObject`.
## Code Examples
### Cache Key Construction
```swift
// Based on WXRead WRChapterPageCount.currentCacheKeyWithBookId:
// Source: Doc/WXRead/decompiled/WRChapterPageCount.m lines 64-90
import CryptoKit
struct RDEPUBTextBookCacheKey: Hashable {
let bookID: String
let fontSize: CGFloat
let lineHeightMultiple: CGFloat
let contentInsets: UIEdgeInsets
let pageSize: CGSize
let schemaVersion: Int // bump when pagination logic changes
var filename: String {
let components = [
bookID,
String(format: "%.1f", fontSize),
String(format: "%.2f", lineHeightMultiple),
String(format: "%.0f", contentInsets.top),
String(format: "%.0f", contentInsets.left),
String(format: "%.0f", contentInsets.bottom),
String(format: "%.0f", contentInsets.right),
String(format: "%.0f", pageSize.width),
String(format: "%.0f", pageSize.height),
"v\(schemaVersion)"
]
let raw = components.joined(separator: "_")
let hash = SHA256.hash(data: Data(raw.utf8))
return hash.map { String(format: "%02x", $0) }.joined() + ".cache"
}
}
```
### NSKeyedArchiver Serialization for RDEPUBTextBook
```swift
// NSAttributedString supports NSCoding via NSKeyedArchiver
// RDEPUBTextBook/Chapter/Page need NSCoding conformance or wrapper
// Option A: Store as NSCoding-compatible wrapper
final class RDEPUBTextBookArchive: NSObject, NSCoding {
let chapters: [RDEPUBTextChapterArchive]
init(chapters: [RDEPUBTextChapterArchive]) { self.chapters = chapters }
required init?(coder: NSCoder) {
guard let chapters = coder.decodeObject(forKey: "chapters") as? [RDEPUBTextChapterArchive] else { return nil }
self.chapters = chapters
}
func encode(with coder: NSCoder) {
coder.encode(chapters, forKey: "chapters")
}
}
// Each RDEPUBTextChapterArchive stores:
// - attributedContent as NSData (NSKeyedArchiver)
// - page ranges as [[location, length]]
// - metadata as JSON Data
```
### Performance Sample Collection
```swift
// No existing pattern in codebase -- standard iOS approach
final class RDEPUBTextPerformanceSampler {
struct Sample {
let chapterHref: String
let renderDuration: TimeInterval
let paginateDuration: TimeInterval
let pageCount: Int
let attributedStringLength: Int
let cacheHit: Bool
}
private(set) var samples: [Sample] = []
func record(_ sample: Sample) {
samples.append(sample)
print("[PERF] \(sample.chapterHref): render=\(String(format: "%.1f", sample.renderDuration*1000))ms paginate=\(String(format: "%.1f", sample.paginateDuration*1000))ms pages=\(sample.pageCount) cache=\(sample.cacheHit ? "HIT" : "MISS")")
}
func summary() -> String {
let totalRender = samples.reduce(0) { $0 + $1.renderDuration }
let totalPaginate = samples.reduce(0) { $0 + $1.paginateDuration }
let hitRate = samples.filter(\.cacheHit).count
return "[PERF] chapters=\(samples.count) render=\(String(format: "%.0f", totalRender*1000))ms paginate=\(String(format: "%.0f", totalPaginate*1000))ms cacheHits=\(hitRate)/\(samples.count)"
}
}
```
## State of the Art
| Old Approach (assumed) | Current Approach (actual) | When Changed | Impact |
|------------------------|---------------------------|--------------|--------|
| `ss_pageRanges` for pagination | `rd_paginatedFrames` via `RDEPUBTextLayouter` | Phase 7 | 4-level semantic break engine already active |
| No CSS `<link>` handling | `inlineLinkedStyleSheets()` in renderer support | Phase 7 or earlier | EPUB external stylesheets already resolved |
| Flat CSS injection | 5-layer cascade via `RDEPUBTextStyleSheetPackage` | Phase 7 | default/replace/dark/epub/user layers already built |
| No page metadata | `RDEPUBTextPageMetadata` on every page | Phase 7 | breakReason, blockKinds, semanticHints already available |
**Deprecated/outdated in CONTEXT.md:**
- D-01 (integrate layouter): Already done. `RDEPUBTextBookBuilder` line 196 calls `content.rd_paginatedFrames(size:)`.
- D-02 (expose metadata): Already done. `RDEPUBTextPage.metadata` is populated from `frame.metadata`.
- D-04 (CSS `<link>` inline): Already done. `RDEPUBTextRendererSupport.inlineLinkedStyleSheets()` handles this.
- D-05 (5-layer cascade): Already done. `makeStyleSheetLayers()` produces the 5-layer package.
## Assumptions Log
| # | Claim | Section | Risk if Wrong |
|---|-------|---------|---------------|
| A1 | `NSKeyedArchiver` can serialize `NSAttributedString` with DTCoreText custom attributes | Cache serialization | Cache would fail silently; fallback to re-render every time |
| A2 | `CFAbsoluteTimeGetCurrent()` has sufficient precision for millisecond-level timing | Performance sampling | Sub-millisecond operations may show as 0ms |
| A3 | Cache key schema version bump is sufficient for invalidation on code changes | Cache invalidation | Stale cache could persist if version is forgotten |
| A4 | CTFrame line origins can detect orphan/widow conditions | Pagination quality | Orphan/widow control would need different approach |
## Open Questions (RESOLVED)
1. **Cache storage format: NSKeyedArchiver vs decomposed JSON?** ✅ RESOLVED
- Decision: Use `NSKeyedArchiver` first. Create private `NSCoding` wrapper classes for `RDEPUBTextBook`/`RDEPUBTextChapter`/`RDEPUBTextPage`/`RDEPUBTextPageMetadata`.
- Rationale: `NSAttributedString` and `NSRange` both support `NSCoding` natively. DTCoreText custom attributes are standard `NSAttributedString` attribute keys (string-typed) and survive archiver round-trip.
- Fallback: If runtime test reveals attribute loss, fall back to decomposed JSON (store HTML + render parameters, re-render on cache load).
2. **Should cache store full attributed content or just page ranges?** ✅ RESOLVED
- Decision: Cache full `RDEPUBTextBook` including `NSAttributedString` per page (matches D-01 decision in CONTEXT.md).
- Rationale: Re-slicing on load would negate the cache performance benefit. Memory pressure is manageable for typical EPUB books (< 500 pages).
- Mitigation: Cache eviction on memory warning (`didReceiveMemoryWarning` notification).
3. **Orphan/widow control: how aggressive?** ✅ RESOLVED
- Decision: Add `RDEPUBTextLayoutConfig` struct with configurable thresholds (`avoidOrphans: Bool = true`, `avoidWidows: Bool = true`), defaulting to enabled.
- Rationale: Follows the same pattern as `RDEPUBTextRenderStyle` (public struct + Equatable + explicit init). Hard-coding would prevent future tuning.
- WXRead reference: `WRCoreTextLayoutConfig` uses the same configurable approach.
## Environment Availability
| Dependency | Required By | Available | Version | Fallback |
|------------|------------|-----------|---------|----------|
| Xcode / iOS SDK | Build & run | ✓ | (system) | -- |
| DTCoreText | HTML rendering | ✓ | (existing dependency) | -- |
| CoreText | Pagination | ✓ | (system framework) | -- |
| CryptoKit | SHA256 for cache key | ✓ | iOS 13+ | CommonCrypto |
| FileManager | Cache directory | ✓ | (system framework) | -- |
**Missing dependencies with no fallback:** None
**Missing dependencies with fallback:** None
## Validation Architecture
### Test Framework
| Property | Value |
|----------|-------|
| Framework | None detected -- no test target in project |
| Config file | none |
| Quick run command | N/A |
| Full suite command | N/A |
### Phase Requirements -> Test Map
| Req ID | Behavior | Test Type | Automated Command | File Exists? |
|--------|----------|-----------|-------------------|-------------|
| QUAL-01 | Cache hit skips rebuild | manual/runtime | Print cache HIT/MISS in console | N/A |
| QUAL-02 | avoidPageBreakInside enforced | manual/runtime | Inspect page diagnostics for semanticBoundary breaks | N/A |
| QUAL-03 | Image sizing rules applied | manual/runtime | Verify image dimensions in diagnostic output | N/A |
| QUAL-04 | Performance samples output | manual/runtime | Check console for [PERF] lines | N/A |
### Sampling Rate
- **Per task commit:** Build succeeds (`build_sim`)
- **Per wave merge:** Runtime log includes [PERF] summary and cache HIT/MISS
- **Phase gate:** Full book builds with cache, second open shows HIT; complex chapter pagination quality visibly improved
### Wave 0 Gaps
- [ ] No test framework exists. All verification is manual/runtime via console output and simulator build.
- [ ] If automated tests desired, would need to create test target first (out of scope for Phase 8).
## Security Domain
No new security concerns introduced. Cache files are stored in the app's caches directory (sandboxed). No network requests, no user data exposure.
### Applicable ASVS Categories
| ASVS Category | Applies | Standard Control |
|---------------|---------|-----------------|
| V2 Authentication | no | N/A |
| V3 Session Management | no | N/A |
| V4 Access Control | no | N/A |
| V5 Input Validation | no | N/A |
| V6 Cryptography | no | SHA256 is one-way hash for cache key, not security-sensitive |
## Sources
### Primary (HIGH confidence)
- Project source code: `Sources/RDReaderView/EPUBTextRendering/*.swift` -- direct code inspection
- `Doc/WXRead/decompiled/WRChapterPageCount.h/.m` -- cache key pattern reference
- `Doc/WXRead/decompiled/WRCoreTextLayouter.h` -- layout config reference
- `Doc/WXRead/decompiled/WRCoreTextLayoutFrame.h/.m` -- avoidPageBreakInside reference
- `Doc/WXRead/resources/css/replace.css` -- CSS rule reference
### Secondary (MEDIUM confidence)
- `Doc/架构对比分析_WXRead_vs_ReadViewSDK.md` -- gap analysis (some gaps already closed)
### Tertiary (LOW confidence)
- A1 (NSKeyedArchiver + DTCoreText attributes): Needs runtime verification
## Metadata
**Confidence breakdown:**
- Standard stack: HIGH -- no new dependencies, all system/existing frameworks
- Architecture: HIGH -- integration points clearly visible in code
- Pitfalls: HIGH -- serialization issues are well-understood Cocoa patterns
- Cache design: MEDIUM -- NSKeyedArchiver with DTCoreText custom attributes needs runtime test
**Research date:** 2026-05-23
**Valid until:** 2026-06-23 (30 days -- stable codebase, incremental changes)

View File

@ -1,63 +0,0 @@
---
status: testing
phase: 08-pagination-quality-cache-performance
source:
- 08-01-SUMMARY.md
- 08-02-SUMMARY.md
- 08-03-SUMMARY.md
started: 2026-05-23T23:20:00+08:00
updated: 2026-05-24T00:12:00+08:00
---
## Current Test
number: 4
name: avoidPageBreakInside enforcement
expected: |
Navigate to a chapter with block-level elements (images, code blocks, tables, blockquotes).
Page breaks should NOT split a block — if a block doesn't fit on the current page, the entire block moves to the next page.
The block should appear complete on a single page, not cut in half across two pages.
awaiting: user response
## Tests
### 1. Cache hit/miss logging
result: pass
### 2. Cache invalidation on parameter change
result: pass
### 3. Performance timing output
result: pass
### 4. avoidPageBreakInside enforcement
expected: Block-level elements not split across page boundaries
result: [pending]
### 5. Orphan/widow control
expected: No 1-2 line paragraphs at page start or end
result: [pending]
### 6. General image fit-to-page
expected: Large images scaled to fit within 85% page height
result: [pending]
### 7. Dark mode image preservation
expected: Images keep original colors in dark mode
result: [pending]
### 8. Image vertical centering
expected: Block-level images vertically centered on page
result: [pending]
## Summary
total: 8
passed: 3
issues: 0
pending: 5
skipped: 0
## Gaps
[none yet]

View File

@ -1,77 +0,0 @@
---
phase: 8
slug: pagination-quality-cache-performance
status: draft
nyquist_compliant: true
wave_0_complete: true
created: 2026-05-23
---
# Phase 8 — Validation Strategy
> Per-phase validation contract for feedback sampling during execution.
---
## Test Infrastructure
| Property | Value |
|----------|-------|
| **Framework** | XCTest (ReadViewSDKDemoTests / ReadViewSDKDemoUITests) |
| **Config file** | ReadViewDemo/ReadViewDemo.xcodeproj |
| **Quick run command** | `xcodebuild test -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17' -only-testing:ReadViewSDKDemoTests` |
| **Full suite command** | `xcodebuild test -scheme ReadViewDemo -destination 'platform=iOS Simulator,name=iPhone 17'` |
| **Estimated runtime** | ~60 seconds |
---
## Sampling Rate
- **After every task commit:** Build succeeds (`xcodebuild build -scheme ReadViewDemo`)
- **After every plan wave:** Run quick test suite + runtime diagnostic log check
- **Before `/gsd:verify-work`:** Full suite green + runtime diagnostic evidence
- **Max feedback latency:** 120 seconds
---
## Per-Task Verification Map
| Task ID | Plan | Wave | Requirement | Automated Command | Status |
|---------|------|------|-------------|-------------------|--------|
| 08-01-01 | 01 | 1 | QUAL-01 | build succeeds + cache hit/miss log | ✅ green |
| 08-01-02 | 01 | 1 | QUAL-01 | build succeeds + cache invalidation log | ✅ green |
| 08-02-01 | 02 | 1 | QUAL-02 | build succeeds + pagination diagnostic log | ✅ green |
| 08-02-02 | 02 | 1 | QUAL-03 | build succeeds + attachment diagnostic log | ✅ green |
| 08-03-01 | 03 | 2 | QUAL-04 | build succeeds + timing diagnostic log | ✅ green |
*Status: ⬜ pending · ✅ green · ❌ red · ⚠️ flaky*
---
## Wave 0 Requirements
- Existing `ReadViewSDKDemoTests` covers parser / resolver / persistence
- No new test infrastructure needed — runtime diagnostic logs serve as evidence
---
## Manual-Only Verifications
| Behavior | Requirement | Why Manual | Test Instructions |
|----------|-------------|------------|-------------------|
| 缓存命中后不再重复排版 | QUAL-01 | 需要对比前后分页结果一致性 | 打开同一本书两次,检查第二次的日志无渲染耗时 |
| 复杂图文章节分页改善 | QUAL-02 | 需要视觉对比 | 用宝山辽墓样书,对比改善前后分页结果 |
| 图片不跨页、居中显示 | QUAL-03 | 需要视觉验证 | 检查含大图章节,确认图片在单页内居中 |
| 首屏时间不退化 | QUAL-04 | 需要实际设备计时 | 对比改善前后打开书籍的首屏时间 |
---
## Validation Sign-Off
- [x] All tasks have build-success verification
- [x] Runtime diagnostic logs captured for cache, pagination quality, and timing
- [ ] Manual verification completed for visual/behavioral checks
- [x] Wave 0: existing test infrastructure sufficient
- [x] Feedback latency < 120s
**Approval:** code-complete, manual verification pending

View File

@ -1,207 +0,0 @@
---
milestone: v1.0
audited: 2026-05-22T05:32:00Z
status: gaps_found
scores:
requirements: 1/10
phases: 5/5
integration: 3/3
flows: 4/4
nyquist:
compliant_phases: []
partial_phases: [1, 2, 3, 4, 5]
missing_phases: []
overall: partial
gaps:
requirements:
- id: "REND-01"
status: "unsatisfied"
phase: "Phase 2"
claimed_by_plans: ["02-02-PLAN.md", "02-03-PLAN.md"]
completed_by_plans: []
verification_status: "partial"
evidence: "02-VERIFICATION.md only marks REND-01 as partial; REQUIREMENTS.md remains unchecked; no SUMMARY frontmatter claims completion."
- id: "REND-02"
status: "partial"
phase: "Phase 2"
claimed_by_plans: ["02-01-PLAN.md", "02-02-PLAN.md", "02-03-PLAN.md"]
completed_by_plans: []
verification_status: "passed"
evidence: "02-VERIFICATION.md marks REND-02 satisfied, but REQUIREMENTS.md remains unchecked and no SUMMARY frontmatter records completion."
- id: "REND-03"
status: "orphaned"
phase: "Phase 3"
claimed_by_plans: ["03-01-PLAN.md", "03-02-PLAN.md", "03-03-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "Phase 3 summary/verifications describe page metadata and paginator work, but no Phase 3 VERIFICATION requirements table maps back to REND-03 and REQUIREMENTS.md remains pending."
- id: "REND-04"
status: "orphaned"
phase: "Phase 3"
claimed_by_plans: ["03-02-PLAN.md", "03-03-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "Phase 3 runtime evidence proves stronger pagination, but no requirement-level verification entry or checked-off requirement exists for REND-04."
- id: "COMP-01"
status: "orphaned"
phase: "Phase 4"
claimed_by_plans: ["04-01-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "Phase 4 verification describes restored reader entry flow, but no explicit requirement table or summary frontmatter marks COMP-01 complete."
- id: "COMP-03"
status: "orphaned"
phase: "Phase 4"
claimed_by_plans: ["04-02-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "Search/highlight/restore behavior is evidenced in Phase 4, but not reconciled into REQUIREMENTS.md or requirement-level verification records."
- id: "COMP-04"
status: "orphaned"
phase: "Phase 4"
claimed_by_plans: ["04-03-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "ROADMAP and summaries say RDReaderView stayed untouched, but milestone requirement tracking never marks COMP-04 complete."
- id: "STAB-01"
status: "orphaned"
phase: "Phase 5"
claimed_by_plans: ["05-01-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "05-VERIFICATION.md shows a 5-book matrix across required categories, but no requirement table or checked requirement ties that evidence to STAB-01."
- id: "STAB-02"
status: "orphaned"
phase: "Phase 5"
claimed_by_plans: ["05-02-PLAN.md"]
completed_by_plans: []
verification_status: "orphaned"
evidence: "05-VERIFICATION.md shows no crash/blank-page regressions in sampled flows, but milestone requirement tracking never records STAB-02 as satisfied."
integration: []
flows: []
tech_debt:
- phase: "01-current-engine-boundaries"
items:
- "01-VALIDATION.md remains draft with pending Wave 0 sign-off and nyquist_compliant false."
- phase: "02-typesetter-css"
items:
- "02-VALIDATION.md remains draft with pending Wave 0 sign-off and nyquist_compliant false."
- "02-VERIFICATION.md leaves REND-01 only partial even though later phases likely complete the milestone intent."
- phase: "03-page-metadata-pagination"
items:
- "03-VALIDATION.md has nyquist_compliant true but all task rows and sign-off remain pending."
- "03-VERIFICATION.md lacks a requirement coverage section for REND-03 / REND-04."
- phase: "04-reader-capabilities"
items:
- "04-VALIDATION.md has no frontmatter compliance markers."
- "04-VERIFICATION.md lacks requirement-level mapping for COMP-01 / COMP-03 / COMP-04."
- "Residual risk notes admit no full interactive UI automation for TOC/highlight/search."
- phase: "05-regression-stability"
items:
- "05-VALIDATION.md documents the matrix but not Nyquist frontmatter compliance."
- "05-VERIFICATION.md lacks requirement-level mapping for STAB-01 / STAB-02."
- "Residual risk notes admit no fully automated UI walkthrough of every sample/interaction."
---
# Milestone v1.0 Audit
## Result
Status: `gaps_found`
The implementation milestone appears substantively complete at the phase and runtime-evidence level, but the milestone does **not** pass the strict close-out gate because requirement bookkeeping was never reconciled after execution. Under the required 3-source cross-reference, only `COMP-02` is fully satisfied.
## Scope
- Milestone: `v1.0`
- Phases in scope: `01` through `05`
- Completed phases: `5/5`
- Verification files present: `5/5`
- Summary files present: `13/13`
## Phase Audit
| Phase | Verification | Summary Coverage | Audit Result |
|-------|--------------|------------------|--------------|
| 1 | present, `passed` | 2/2 | pass |
| 2 | present, `passed` | 3/3 | pass with requirement bookkeeping gap |
| 3 | present, runtime evidence strong | 3/3 | pass with orphaned requirement gap |
| 4 | present, runtime evidence strong | 3/3 | pass with orphaned requirement gap |
| 5 | present, runtime evidence strong | 2/2 | pass with orphaned requirement gap |
## Requirements Cross-Reference
| Requirement | Traceability | Verification | Summary Frontmatter | Final |
|-------------|--------------|--------------|---------------------|-------|
| COMP-02 | Complete | satisfied in Phase 1 | listed in 01 summaries | satisfied |
| REND-02 | Pending | satisfied in Phase 2 | not listed | partial |
| REND-01 | Pending | partial in Phase 2 | not listed | unsatisfied |
| REND-03 | Pending | no requirement table entry | not listed | orphaned |
| REND-04 | Pending | no requirement table entry | not listed | orphaned |
| COMP-01 | Pending | no requirement table entry | not listed | orphaned |
| COMP-03 | Pending | no requirement table entry | not listed | orphaned |
| COMP-04 | Pending | no requirement table entry | not listed | orphaned |
| STAB-01 | Pending | no requirement table entry | not listed | orphaned |
| STAB-02 | Pending | no requirement table entry | not listed | orphaned |
Interpretation:
- The code and runtime evidence strongly suggest several orphaned requirements were actually delivered.
- The milestone audit still fails because `REQUIREMENTS.md`, `*-VERIFICATION.md`, and `requirements-completed` summary metadata do not agree.
- This is a close-out gap, not necessarily an implementation gap.
## Integration Check
Cross-phase integration appears healthy from the shipped evidence:
- Phase 2 chapter preprocessing and CSS layering feed the Phase 3 paginator path.
- Phase 3 offset-compatible pagination semantics feed Phase 4 reader restore/search/highlight behavior.
- Phase 5 validates native reflowable, fixed/interactive WebKit, and TXT from the same demo/runtime surface.
No cross-phase wiring break or broken end-to-end flow was evidenced in the verification artifacts.
## Runtime / E2E Evidence
Observed milestone-level evidence from Phase 3-5 verification:
- `EPUB 资源验证2/2 通过`
- `分页诊断:宝山辽墓材料与释读 ...`
- `恢复诊断:宝山辽墓材料与释读 ...`
- `样本验证5/5 通过`
- `矩阵[Fixed/互动] 2/2`
- `矩阵[TXT] 1/1`
These support the claim that the milestone behavior is broadly working, but they do not by themselves satisfy the workflow's requirement-traceability gate.
## Nyquist Coverage
| Phase | VALIDATION.md | Compliance | Notes |
|-------|---------------|------------|-------|
| 1 | present | partial | draft, `nyquist_compliant: false` |
| 2 | present | partial | draft, `nyquist_compliant: false` |
| 3 | present | partial | `nyquist_compliant: true`, but task/sign-off rows remain pending |
| 4 | present | partial | validation doc exists, but no frontmatter compliance markers |
| 5 | present | partial | validation doc exists, but no frontmatter compliance markers |
## Why This Fails Close-Out
The milestone close workflow requires all of the following to align:
1. `REQUIREMENTS.md` checkboxes and traceability statuses
2. phase `VERIFICATION.md` requirement coverage
3. phase `SUMMARY.md` `requirements-completed` frontmatter
That alignment is missing for 9 of 10 requirements.
## Recommended Closure Path
1. Reconcile the requirement evidence into the existing phase artifacts:
- add requirement coverage sections where missing in Phases 3-5
- update `requirements-completed` frontmatter in relevant summaries
- update `.planning/REQUIREMENTS.md` checkboxes and traceability statuses
2. Run `$gsd-validate-phase 1`, `$gsd-validate-phase 2`, `$gsd-validate-phase 3`, `$gsd-validate-phase 4`, `$gsd-validate-phase 5` if you want Nyquist compliance brought up to date before close-out.
3. Re-run `$gsd-audit-milestone`.
## Bottom Line
The milestone looks operationally complete, but it is **not archive-ready** under the workflows audit rules because the requirement evidence chain is incomplete.

View File

@ -1,19 +1,18 @@
# Project Context & Rules
## Language Specification
- **Planning & Documentation:** All plans, task lists, and specifications generated inside the `.planning/` directory MUST be written in Chinese.
- **Project Docs:** All documents generated or updated under `Doc/`, project root Markdown documentation, and GSD-produced delivery/analysis documents MUST be written in Chinese.
- **Project Docs:** All documents generated or updated under `Doc/`, project root Markdown documentation MUST be written in Chinese.
- **Codebase:** Source code syntax (class names, function names, variables, file names, API identifiers, route identifiers) must remain in English, but all code comments, documentation (Docstrings), and commit messages MUST be written in Chinese.
## Agent / Sub-agent Enforcement (GSD & Codex)
## Agent / Sub-agent Enforcement
- **Mandatory pre-read:** Any agent/sub-agent that generates or updates files MUST read this file (`CONTEXT.md`) first and follow it as the source-of-truth for language/style constraints.
- **Chinese-only outputs:** Any artifact written under `.planning/` (including `.planning/codebase/*.md`) MUST be Chinese. Do not output English headings/sections unless the content is a literal code identifier or a proper noun that should not be translated.
- **Chinese-only outputs:** Any artifact written under `Doc/` MUST be Chinese. Do not output English headings/sections unless the content is a literal code identifier or a proper noun that should not be translated.
- **When spawning sub-agents:** The orchestrator MUST either:
- set `fork_context=true`, AND
- explicitly instruct the agent to read `CONTEXT.md` before writing; OR
- (if `fork_context=false`) explicitly include the above constraints in the sub-agent prompt and still require a `CONTEXT.md` pre-read.
### Recommended prompt snippet (copy into sub-agent tasks)
1) First read `CONTEXT.md` and follow all rules.
2) All markdown you write under `.planning/` MUST be Chinese.
3) Keep code identifiers / file paths / commands in English as-is.
1) First read `CONTEXT.md` and follow all rules.
2) All markdown you write under `Doc/` MUST be Chinese.
3) Keep code identifiers / file paths / commands in English as-is.

View File

@ -1,6 +1,6 @@
# ReadViewSDK 系统架构文档
> 最后更新2026-06-04
> 最后更新2026-06-09
---
@ -67,22 +67,27 @@ ReadViewSDK 是一个 iOS EPUB 阅读器 SDK支持文本重排Reflowable
用户点击书籍
RDEPUBReaderController.openBook(epubURL:)
RDEPUBReaderController(epubURL:delegate:persistence:) // 初始化,传入 epubURL
├─ RDEPUBParser.parse(epubURL:) // 解压 ZIP → 解析 OPF → 构建 spine/TOC
│ └─ extractArchiveIfNeeded() // ZIPFoundation 解压到 Caches
│ └─ parseContainerRootFile() // SAX 解析 container.xml
│ └─ parseOPF() // SAX 解析 OPF (metadata/manifest/spine)
│ └─ parseTOC() // NCX 或 Navigation Document
├─ viewDidLoad() → startInitialLoadIfNeeded()
│ │
│ ├─ RDEPUBReaderLoadCoordinator.startInitialLoadIfNeeded()
│ │ ├─ RDEPUBParser.parse(epubURL:) // 解压 ZIP → 解析 OPF → 构建 spine/TOC
│ │ │ └─ extractArchiveIfNeeded() // ZIPFoundation 解压到 Caches
│ │ │ └─ parseContainerRootFile() // SAX 解析 container.xml
│ │ │ └─ parseOPF() // SAX 解析 OPF (metadata/manifest/spine)
│ │ │ └─ parseTOC() // NCX 或 Navigation Document
│ │ │
│ │ ├─ RDEPUBPublication(parser:) // 创建门面对象
│ │ ├─ 恢复持久化数据(书签/高亮/位置)
│ │ └─ applyParsedPublication()
│ │
│ └─ 判断 readingProfile:
│ ├─ .textReflowable → 文本排版路径(本 SDK 核心路径)
│ ├─ .webInteractive → WebView 渲染路径
│ └─ .webFixedLayout → 固定布局路径
├─ RDEPUBPublication(parser:) // 创建门面对象
├─ 判断 readingProfile:
│ ├─ .textReflowable → 文本排版路径(本 SDK 核心路径)
│ ├─ .webInteractive → WebView 渲染路径
│ └─ .webFixedLayout → 固定布局路径
└─ paginateTextPublication() // 进入分页流程
└─ runtime.paginatePublication() // 进入分页流程
```
### 3.2 文本重排分页流程(大书优化路径)
@ -206,10 +211,17 @@ RDEPUBReaderController
│ ├─ configuration, persistence
│ └─ 便捷方法 (renderStyle, layoutConfig, cacheKey)
├─ RDEPUBReaderRuntime // 运行时协调器集合
├─ RDEPUBReaderRuntime // 运行时协调器集合Facade 模式)
│ ├─ chapterLoader // 章节加载器
│ ├─ chapterRuntimeStore // 内存缓存
│ ├─ summaryDiskCache // 磁盘摘要缓存
│ ├─ pageResolver // 页码解析器
│ ├─ loadCoordinator // 加载协调器
│ ├─ paginationCoordinator // 分页协调器
│ ├─ locationCoordinator // 位置协调器
│ ├─ searchCoordinator // 搜索协调器
│ ├─ chromeCoordinator // 工具栏协调器
│ ├─ annotationCoordinator // 标注协调器
│ └─ viewportMonitor // 视口变化监控
├─ RDEPUBReaderPaginationCoordinator // 分页协调器
@ -335,7 +347,7 @@ Sources/RDReaderView/
│ │ ├── cssInjector.js
│ │ ├── WeReadApi.js
│ │ ├── rangy-core.js / rangy-serializer.js
│ │ ├── wxread-default.css / wxread-dark.css / wxread-replace.css
│ │ ├── wxread-default.css / wxread-dark.css / wxread-replace-latin.css
│ │ └── epub-fixed-layout.html
│ ├── RDEPUBParser.swift # 核心解析器
│ ├── RDEPUBParser+Archive.swift # ZIP 解压
@ -398,27 +410,38 @@ Sources/RDReaderView/
│ │ ├── RDEPUBChapterLoader.swift
│ │ ├── RDEPUBChapterRuntimeStore.swift
│ │ ├── RDEPUBChapterSummaryDiskCache.swift
│ │ ├── RDEPUBChapterCacheKey.swift
│ │ ├── RDEPUBBookPageMap.swift
│ │ ├── RDEPUBChapterSummary.swift
│ │ ├── RDEPUBPageResolver.swift
│ │ └── ...
│ ├── RDEPUBReaderContext.swift // 共享状态中心
│ ├── RDEPUBReaderRuntime.swift // 运行时协调器
│ ├── RDEPUBReaderRuntime.swift // 运行时协调器Facade
│ ├── RDEPUBReaderDependencies.swift // 依赖注入
│ ├── RDEPUBReaderLoadCoordinator.swift // 加载协调器
│ ├── RDEPUBReaderPaginationCoordinator.swift // 分页协调器
│ ├── RDEPUBReaderAnnotationCoordinator.swift // 标注协调器
│ ├── RDEPUBReaderLocationCoordinator.swift // 位置协调器
│ ├── RDEPUBReaderSearchCoordinator.swift // 搜索协调器
│ ├── RDEPUBReaderNavigationCoordinator.swift // 导航协调器
│ ├── RDEPUBReaderChromeCoordinator.swift // 工具栏协调器
│ ├── RDEPUBReaderAnnotationCoordinator.swift // 标注协调器
│ ├── RDEPUBReaderAssemblyCoordinator.swift // 组装协调器
│ ├── RDEPUBReaderViewportMonitor.swift // 视口监控
│ └── ...
├── Settings/ # 设置面板
│ ├── RDEPUBReaderSettingsViewController.swift
│ ├── RDEPUBReaderThemeSelector.swift
│ ├── RDEPUBReaderConfiguration.swift # 配置模型
│ ├── RDEPUBReaderSettings.swift # 持久化设置
│ ├── RDEPUBReaderSettingsViewController.swift # 设置面板 VC
│ ├── RDEPUBReaderTheme.swift # 主题定义
│ └── ...
├── TextPage/ # 文本页面渲染
│ ├── RDEPUBTextContentView.swift
│ ├── RDEPUBTextPageViewController.swift
│ ├── RDEPUBTextContentView.swift # 文本内容视图CoreText
│ ├── RDEPUBTextSelectionController.swift # 文本选择控制器
│ ├── RDEPUBPageInteractionController.swift # 点击交互控制器
│ ├── RDEPUBSelectionOverlayView.swift # 选区覆盖层
│ ├── RDEPUBTextAnnotationOverlay.swift # 标注覆盖层
│ ├── RDEPUBTextPageRenderView.swift # CoreText 绘制视图
│ └── ...
├── RDEPUBReaderController.swift # 主控制器
├── RDEPUBReaderConfiguration.swift # 配置模型
├── RDEPUBReaderController.swift # 主控制器(+ContentDelegates/DataSource/PublicAPI 等扩展)
├── RDEPUBReaderDelegate.swift # 公开委托协议
├── RDEPUBReaderPersistence.swift # 持久化协议
└── ...
```
@ -432,7 +455,7 @@ Sources/RDReaderView/
| **Facade** | `RDEPUBPublication` 封装 `RDEPUBParser``RDEPUBChapterData` 封装章节查询 |
| **Builder** | `RDEPUBBookPageMap.Builder` 增量构建页码映射 |
| **Strategy** | `RDEPUBTextRenderer` 协议,可替换渲染器实现 |
| **Pipeline** | `RDEPUBTextTypesetterPipeline` 8 阶段排版管线 |
| **Pipeline** | `RDEPUBTextTypesetterPipeline` 排版管线8 个逻辑阶段,封装为 5-6 个顶层调用) |
| **State Machine** | `RDEPUBNavigatorState` 管理阅读器状态转换 |
| **Adapter** | `RDReaderLegacyDataSourceAdapter` 适配旧数据源协议 |
| **三级缓存** | 内存 → 磁盘摘要 → 全书分页,逐级降级 |

View File

@ -1,6 +1,6 @@
# ReadViewSDK 业务逻辑文档
> 最后更新2026-06-04
> 最后更新2026-06-09
---
@ -345,34 +345,46 @@ RTL 模式下左右互换。工具栏显示时,左右区域变为 `.center`
// 统一标注类型
struct RDEPUBAnnotation {
let id: String
let bookIdentifier: String?
let kind: RDEPUBAnnotationKind // .bookmark, .highlight, .underline
let location: RDEPUBLocation
let text: String?
let color: String?
let note: String?
let rangeInfo: String? // CoreText 选区范围信息
let chapterTitle: String?
let createdAt: Date
// computed: bookmark, highlight
}
// 书签
struct RDEPUBBookmark {
let id: String
let bookIdentifier: String?
let location: RDEPUBLocation
let chapterTitle: String?
let note: String?
let createdAt: Date
}
// 高亮
struct RDEPUBHighlight {
let id: String
let bookIdentifier: String?
let location: RDEPUBLocation
let text: String
let style: RDEPUBHighlightStyle // .highlight, .underline
let color: String
let note: String?
let rangeInfo: String?
let createdAt: Date
}
```
### 6.2 选区处理流程
SDK 支持两条选区处理路径,分别对应 WebView 渲染和原生文本渲染:
**路径 AWebView 渲染webInteractive / webFixedLayout**
```
用户长按 → WKWebView 选区变化
@ -387,6 +399,32 @@ RDEPUBReaderAnnotationCoordinator
└─ 显示操作菜单(拷贝/高亮/批注)
```
**路径 B原生文本渲染textReflowable**
```
用户长按 → RDEPUBTextContentView.handleLongPress(_:)
├─ layoutIfNeeded() // 确保布局完成
RDEPUBTextSelectionController.handleLongPress(_:)
├─ RDEPUBPageInteractionController.characterIndexForViewPoint()
│ └─ CoreText CTLineGetStringIndexForPosition 字符命中
├─ 计算选区范围 (NSRange)
├─ isSelecting = true
用户拖拽 → handlePan(_:)
├─ 更新选区范围
├─ RDEPUBSelectionOverlayView 绘制选区高亮
└─ .ended/.cancelled/.failed → isSelecting = false保留选区
RDEPUBTextContentView delegate → RDEPUBReaderAnnotationCoordinator
├─ 创建 RDEPUBSelection含 rangeInfo
└─ 显示操作菜单(拷贝/高亮/批注)
```
### 6.3 高亮渲染
文本模式下,高亮通过 NSAttributedString 属性注入:
@ -415,17 +453,34 @@ CoreText 渲染时识别这些自定义属性并绘制高亮背景/下划线。
### 7.1 全文搜索
SDK 提供两个搜索引擎,分别服务于不同的渲染路径:
**文本渲染路径:`RDEPUBTextSearchEngine`**
`RDEPUBTextSearchEngine.search(keyword:)`
1. 遍历所有 linear spine 条目html/xhtml 类型)
2. 读取 HTML转为纯文本
- 优先:`NSAttributedString(data:options:documentAttributes:)` with `.documentType: .html`
- 回退:正则去除 HTML 标签
3. 执行大小写不敏感的 `NSString.range(of:options:)` 搜索
1. 遍历 `RDEPUBTextBook.chapters` 中的所有章节
2. 对每个章节的 `attributedContent`(已渲染的 NSAttributedString执行搜索
3. 使用 `NSString.range(of:options:.caseInsensitive)` 进行大小写不敏感搜索
4. 为每个匹配生成:
- `progression`0.0-1.0 的阅读进度
- `previewText`:匹配位置前后各 12 字符
- `rangeAnchor`:精确的文本锚点
- `rangeAnchor`精确的文本锚点RDEPUBTextRangeAnchor
**纯文本文件搜索:`RDEPUBTextSearchEngine.searchWithoutPublication(textBook:keyword:)`**
静态方法,用于 `.txt` 文件(有 TextBook 但无 Publication的搜索
1. 遍历 TextBook 章节的 attributedContent
2. 跳过 publication 依赖的 href 规范化
3. 不生成 rangeAnchor纯文本无 CoreText 锚点)
**WebView 渲染路径:`RDEPUBHTMLSearchEngine`**
1. 遍历所有 linear spine 条目html/xhtml 类型)
2. 读取 HTML转为纯文本正则去除标签
3. 执行大小写不敏感搜索
4. 通过 JS Bridge 在 WebView DOM 中绘制搜索高亮
### 7.2 搜索结果导航
@ -439,7 +494,26 @@ struct RDEPUBSearchState {
}
```
WebView 通过 JS Bridge 接收搜索高亮数据,在 DOM 中绘制高亮矩形。
**搜索结果导航流程:**
`RDEPUBReaderSearchCoordinator` 协调搜索结果的前进/后退导航:
1. `goToNextMatch()` / `goToPreviousMatch()` 更新 `currentMatchIndex`
2. 根据匹配位置计算目标页码,触发页面跳转
3. 通知 `RDEPUBReaderController` 更新搜索计数显示
**搜索结果渲染:**
- **WebView 路径:** 通过 JS Bridge 接收搜索高亮数据,在 DOM 中绘制高亮矩形
- **原生文本路径:** `RDEPUBTextContentView` 根据 `rangeAnchor` 在 CoreText 绘制层高亮匹配文本
**搜索栏生命周期:**
搜索栏采用延迟安装模式:
1. `showSearchBar()` 设置 `isSearchBarVisible = true`,仅在工具栏可见时立即安装视图
2. 若工具栏隐藏,延迟到 `handleToolViewVisibilityChanged(isVisible: true)` 时安装
3. `installSearchBarView()` 负责实际的视图层级添加、约束、动画和焦点管理
---

View File

@ -61,15 +61,7 @@
## 可维护性与技术债
### 8) Legacy 与新实现并存(潜在双栈维护)
- **问题:** SDK 同时存在 `LegacyRDReaderController/*` 与较新的 `EPUBCore`/`EPUBUI` 实现,且存在体量很大的 controller 文件。
- **影响:** 行为重复、修复分叉、上手成本上升,长期维护成本更高。
- **建议缓解:**
- 明确弃用/冻结计划:哪些 API 仍受支持,哪些仅做兼容不再演进。
- 抽取共用原语models、persistence、navigation到统一位置逐步移除重复实现。
- 提供兼容 shim推动调用方迁移离开 legacy API。
### 9) DEBUG 下日志与 Web Inspector 可能泄露内容
### 8) DEBUG 下日志与 Web Inspector 可能泄露内容
- **问题:** Debug 辅助会打印导航/消息体selection payload 可能包含用户选中文本;且 DEBUG 下可能默认开启 inspectable。
- **影响:** 在 debug 构建(含内部测试/QA日志可能包含敏感内容并被导出/分享。
- **建议缓解:**
@ -78,21 +70,21 @@
## 构建与依赖脆弱性
### 10) 仓库中包含 vendored 的 `Pods/` 目录
### 9) 仓库中包含 vendored 的 `Pods/` 目录
- **问题:** 仓库根目录有 `Pods/`,示例工程内也有 `ReadViewDemo/Pods/`
- **影响:** diff 体积大、clone 慢、易产生 merge 冲突,也容易出现依赖陈旧导致的构建不一致。
- **建议缓解:**
- 通常建议不要提交 Pods仅提交 `Podfile.lock`,在 CI 中执行 `pod install`
- 如确有 vendoring 政策,需文档化并提供同步/校验工具,避免漂移。
### 11) Podfile 与 podspec 的部署版本不一致
### 10) Podfile 与 podspec 的部署版本不一致
- **问题:** `Podfile` 设为 `platform :ios, '15.6'`,而 podspec 声明 `s.platform = :ios, "15.0"`
- **影响:** 对外承诺与本地构建基线不一致,容易造成集成方预期偏差。
- **建议缓解:**
- 对齐 `Podfile`、`*.podspec`、Xcode project 的 deployment target。
- 在 CI 中增加漂移检查,防止版本被无意改动。
### 12) podspec 将 Swift 版本钉死为 5.10
### 11) podspec 将 Swift 版本钉死为 5.10
- **问题:** `s.swift_versions = ["5.10"]` 将 pod 与特定 Swift 版本强绑定。
- **影响:** 旧工具链的集成方无法使用;未来升级可能出现“突然不兼容”,尤其当依赖未同步时。
- **建议缓解:**
@ -101,7 +93,7 @@
## 不清晰/容易踩坑的契约
### 13) 默认的持久化协议实现可能静默丢失数据
### 12) 默认的持久化协议实现可能静默丢失数据
- **问题:** `RDEPUBReaderPersistence` 通过 protocol extension 提供了 bookmarks/settings 的默认 no-op 实现。
- **影响:** 集成方可能误以为这些能力默认会持久化,但实际数据会被静默丢弃,且不易排查。
- **建议缓解:**
@ -118,8 +110,7 @@
- Resource path validationpost-extraction`Sources/RDReaderView/EPUBCore/RDEPUBParser+Resources.swift`
- Scheme handler reads full file bytes`Sources/RDReaderView/EPUBCore/RDEPUBResourceURLSchemeHandler.swift`
- WebView bridge + message handling`Sources/RDReaderView/EPUBCore/RDEPUBWebView+JavaScriptBridge.swift`
- External link openingnew UI`Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`
- External link opening + selection persistencelegacy`Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`
- External link opening`Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`
- UserDefaults persistence implementation`Sources/RDReaderView/EPUBUI/RDEPUBReaderPersistence.swift`
- Hidden paginator web view`Sources/RDReaderView/EPUBCore/RDEPUBPaginator.swift`
- Debug logging`Sources/RDReaderView/EPUBCore/RDEPUBWebViewDebug.swift`

View File

@ -2,7 +2,7 @@
**分析日期:** 2026-05-21
> 说明:本仓库以 iOS/Swift 为主,未检测到统一的 lint/format 工具配置;代码风格在不同模块/年代间存在差异。`.planning/` 下的文档按项目规则使用中文描述,但代码标识符保持英文。
> 说明:本仓库以 iOS/Swift 为主,未检测到统一的 lint/format 工具配置;代码风格在不同模块间存在差异。文档按项目规则使用中文描述,但代码标识符保持英文。
## 语言与工程约束
@ -17,22 +17,21 @@
- 大量使用前缀区分模块域:
- `RD...`:阅读器 UI/控制器相关(如 `Sources/RDReaderView/RDReaderView.swift`、`Sources/RDReaderView/RDURLReaderController.swift`
- `RDEPUB...`EPUB Core/UI/渲染相关(如 `Sources/RDReaderView/EPUBCore/RDEPUBModels.swift`
- Extension 文件使用 `+` 命名:`Sources/RDReaderView/LegacyRDReaderController/RDReaderController+EPUBText.swift`
- Extension 文件使用 `+` 命名:`Sources/RDReaderView/EPUBUI/RDEPUBReaderController+ContentDelegates.swift`
**变量/函数命名:**
- 基本遵循 Swift lowerCamelCase`parse(epubURL:)``Sources/RDReaderView/EPUBCore/RDEPUBParser.swift`
- UI 代码中常见简写:`imageV``Sources/RDReaderView/LegacyRDReaderController/RDReaderCoverView.swift`
- 常量多用 `static let``epubPaginationCacheStorageKey``Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`
- 常量多用 `static let``kRDEPUBHighlightAttributeName``Sources/RDReaderView/EPUBCore/Models/RDEPUBAnnotationModels.swift`
## 代码风格与排版(从现有代码归纳)
**缩进与换行:**
- 多数文件使用 4 空格缩进(示例:`ReadViewDemo/ReadViewDemo/ViewController.swift`、`Sources/RDReaderView/EPUBCore/RDEPUBModels.swift`
- 历史代码中更常见“强制换行/多行括号”风格(示例:`Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift` 的 `CGRect(...)`
- 历史代码中更常见”强制换行/多行括号”风格
**空行与分组:**
- UI 相关文件常用空行分隔属性/初始化/布局段落(示例:`Sources/RDReaderView/LegacyRDReaderController/RDReaderCoverView.swift`
- `// MARK:` 用于分区组织(示例:`Sources/RDReaderView/RDReaderGestureController.swift`、`Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`、`Sources/RDReaderView/EPUBTextRendering/RDPlainTextBookBuilder.swift`
- UI 相关文件常用空行分隔属性/初始化/布局段落
- `// MARK:` 用于分区组织(示例:`Sources/RDReaderView/RDReaderGestureController.swift`、`Sources/RDReaderView/EPUBTextRendering/RDPlainTextBookBuilder.swift`
**类型组织:**
- 偏好用 `extension` 拆分职责/协议实现(示例:`ReadViewDemo/ReadViewDemo/ViewController.swift` 的 `UITableViewDataSource/Delegate`
@ -45,8 +44,8 @@
- UIKit/UI 文件:`import UIKit`(大量文件)
- Core/模型文件:`import Foundation`(如 `Sources/RDReaderView/EPUBCore/RDEPUBModels.swift`
- 三方依赖按需引入:
- `SnapKit`:布局(如 `Sources/RDReaderView/LegacyRDReaderController/RDReaderCoverView.swift`
- `SSAlertSwift`:弹窗/提示(如 `Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`
- `SnapKit`:布局
- `SSAlertSwift`:弹窗/提示
**Pods 目录说明:**
- `ReadViewDemo/Pods/**` 为依赖源码/生成配置,通常不作为本仓库代码风格的“标准样式”参考。
@ -60,7 +59,7 @@
## 注释与文档
- **项目规则(强约束)**:代码标识符保持英文,但**代码注释/文档/提交信息使用中文**(见 `CONTEXT.md`)。
- 历史文件常带 Xcode 头部注释块(示例:`Sources/RDReaderView/RDReaderView.swift`、`Sources/RDReaderView/LegacyRDReaderController/RDReaderCoverView.swift`)。
- 历史文件常带 Xcode 头部注释块(示例:`Sources/RDReaderView/ReaderView/RDReaderView.swift`)。
- 公共 API 处存在少量三斜线文档注释(示例:`Sources/RDReaderView/RDReaderView.swift` 的中文说明)。
## Lint / Formatter / 静态检查
@ -80,9 +79,7 @@
- `Podfile`
- `RDReaderView.podspec`
- `ReadViewDemo/ReadViewDemo/ViewController.swift`
- `Sources/RDReaderView/RDReaderView.swift`
- `Sources/RDReaderView/LegacyRDReaderController/RDReaderController.swift`
- `Sources/RDReaderView/LegacyRDReaderController/RDReaderCoverView.swift`
- `Sources/RDReaderView/ReaderView/RDReaderView.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBParser.swift`
- `Sources/RDReaderView/EPUBCore/RDEPUBModels.swift`
- `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
- `Sources/RDReaderView/EPUBUI/RDEPUBReaderController.swift`

View File

@ -34,7 +34,7 @@ ReadViewSDK 当前对 EPUB 有三类渲染路径:
## 2. 关键事实核验(当前代码真实路径)
> 纠偏说明:`.planning/PROJECT.md` 在初始化时曾把“reflowable EPUB 当前路径”概括为偏 `WKWebView` 的历史性表述。经本次代码核验,当前真实主路径是 `.textReflowable``RDEPUBTextBookBuilder``RDEPUBDTCoreTextRenderer` → CoreText 分页 → `RDEPUBTextContentView`。本设计以代码事实为准,并默认后续计划/实现都按此理解推进。
> 纠偏说明:项目初始化时曾把”reflowable EPUB 当前路径”概括为偏 `WKWebView` 的历史性表述。经本次代码核验,当前真实主路径是 `.textReflowable``RDEPUBTextBookBuilder``RDEPUBDTCoreTextRenderer` → CoreText 分页 → `RDEPUBTextContentView`。本设计以代码事实为准,并默认后续实现都按此理解推进。
### 2.1 渲染路径分流(已存在)
@ -255,7 +255,7 @@ WXRead 的更高阶策略(参考 `Doc/WXRead/analysis/DTCoreText自定义修
## 9. 下一步(交接到开发)
建议按 `.planning/ROADMAP.md` 从 Phase 1 开始推进:
建议按 `Doc/ARCHITECTURE-CONTEXT.md` 中的架构决策逐步推进:
- 先基于 `Doc/WXRead/analysis/*` 提炼“我们要实现的 CSS 分层最小集合”
- 再在 `.textReflowable` renderer 里实现“分层 CSS 注入 + baseURL/资源解析兜底”

123
Doc/TESTING.md Normal file
View File

@ -0,0 +1,123 @@
# 测试说明
**分析日期:** 2026-06-09更新
## 测试框架与现状
**Runner**
- XCTestiOS/Xcode 默认测试框架)
- **当前仓库状态**:包含 UI 测试 Target `ReadViewDemoUITests`,位于 `ReadViewDemo/ReadViewDemoUITests/`
**断言库:**
- XCTest 内建断言(`XCTAssert*`、`XCTAssertEqual`、`XCTAssertNotNil` 等)
- XCUIElement 断言(`exists`、`waitForExistence`、`isHittable` 等)
## 测试文件组织
**位置:**
- 测试文件:`ReadViewDemo/ReadViewDemoUITests/ReaderUITests/`
- 辅助文件:`ReadViewDemo/ReadViewDemoUITests/Helpers/`
**文件清单24 个测试文件):**
| 测试文件 | 覆盖功能 |
|----------|----------|
| BookmarkTests.swift | 书签基础操作 |
| BookmarkManagementTests.swift | 书签管理(增删改查) |
| ConcurrentParsingTests.swift | 并发解析稳定性 |
| ConfigurableWindowTests.swift | 可配置章节窗口 |
| DisplayTypeTests.swift | 显示模式切换 |
| ErrorAndEdgeCaseTests.swift | 错误与边界情况 |
| FanrenParseTimeTest.swift | 《凡人修仙传》解析性能基准 |
| HighlightsManagementTests.swift | 高亮标注管理 |
| LargeBookOnDemandTests.swift | 大书按需加载 |
| LocationPersistenceTests.swift | 阅读位置持久化 |
| MetadataParseBenchmarkTests.swift | 元数据解析性能基准 |
| PageNavigationTests.swift | 页面导航 |
| ReaderAnnotationTests.swift | 标注基础功能 |
| ReaderAnnotationExtendedTests.swift | 标注扩展功能 |
| ReaderOpenCloseTests.swift | 阅读器打开/关闭 |
| ReaderToolbarTests.swift | 工具栏交互 |
| SearchTests.swift | 全文搜索 |
| SelectionMenuTests.swift | 选区菜单 |
| SettingsEffectTests.swift | 设置效果验证 |
| SettingsExtendedTests.swift | 设置扩展功能 |
| SettingsPanelTests.swift | 设置面板交互 |
| TableOfContentsTests.swift | 目录功能 |
| TOCInteractionTests.swift | 目录交互 |
| ToolbarStateTests.swift | 工具栏状态管理 |
**辅助文件3 个):**
| 文件 | 用途 |
|------|------|
| AccessibilityIdentifiers.swift | UI 元素 accessibility identifier 定义 |
| DemoReaderState.swift | 测试用阅读器状态辅助 |
| XCUIApplication+Launch.swift | XCUIApplication 启动配置扩展 |
**统计:**
- 测试类23 个XCTestCase 子类)
- 测试方法:约 99 个(`func test...`
- 辅助文件3 个
## 如何运行
### CocoaPods 依赖准备
> 仓库包含示例工程 `ReadViewDemo`,并已提交 `Pods/``Podfile.lock`。如本地环境未同步,可在仓库根或示例工程目录运行:
```bash
pod install
```
(依赖入口:`Podfile`、`ReadViewDemo/Podfile`
### 运行 UI 测试
```bash
xcodebuild test \
-workspace ReadViewDemo/ReadViewDemo.xcworkspace \
-scheme ReadViewDemo \
-destination 'platform=iOS Simulator,name=iPhone 15' \
-only-testing:ReadViewDemoUITests
```
### 运行单个测试类
```bash
xcodebuild test \
-workspace ReadViewDemo/ReadViewDemo.xcworkspace \
-scheme ReadViewDemo \
-destination 'platform=iOS Simulator,name=iPhone 15' \
-only-testing:ReadViewDemoUITests/SearchTests
```
### 运行脚本
项目提供了自动化回归脚本:
```bash
./scripts/run_ui_regression.sh
```
测试报告输出到 `.artifacts/ui-tests/{timestamp}/UI-Test-Report.md`
## 覆盖率Coverage
- 当前未启用代码覆盖率收集
- 若需启用,可在 Xcode Scheme → Test → Options 中勾选 "Code Coverage"
- 或通过 `xcodebuild test``-enableCodeCoverage YES` 参数
## Mocking / Fixtures
- 未使用统一 mocking 框架
- 测试通过 Demo App 加载真实 EPUB 文件进行端到端验证
- 辅助文件 `DemoReaderState.swift` 提供测试状态管理
## Evidence关键证据文件
- `ReadViewDemo/ReadViewDemo.xcodeproj/project.pbxproj`
- `ReadViewDemo/ReadViewDemoUITests/` 目录
- `ReadViewDemo/Podfile`
- `ReadViewDemo/Podfile.lock`
- `.artifacts/ui-tests/` 下的历史测试报告

View File

@ -1,6 +1,6 @@
# ReadViewSDK UML 类图
> 最后更新2026-06-04
> 最后更新2026-06-09
> 图表格式Mermaid可在 GitHub / VS Code / Mermaid Live Editor 中渲染)
---
@ -426,7 +426,14 @@ classDiagram
+chapterLoader: RDEPUBChapterLoader
+chapterRuntimeStore: RDEPUBChapterRuntimeStore
+summaryDiskCache: RDEPUBChapterSummaryDiskCache
+viewportMonitor: RDEPUBViewportMonitor
+pageResolver: RDEPUBPageResolver
+loadCoordinator: RDEPUBReaderLoadCoordinator
+paginationCoordinator: RDEPUBReaderPaginationCoordinator
+locationCoordinator: RDEPUBReaderLocationCoordinator
+searchCoordinator: RDEPUBReaderSearchCoordinator
+chromeCoordinator: RDEPUBReaderChromeCoordinator
+annotationCoordinator: RDEPUBReaderAnnotationCoordinator
+viewportMonitor: RDEPUBReaderViewportMonitor
+applyBookPageMap(_:restoreLocation:)
+refreshBookPageMapInPlace(_:)
}
@ -440,6 +447,29 @@ classDiagram
-buildPageMap(from:summaries:) RDEPUBBookPageMap
}
class RDEPUBReaderLoadCoordinator {
-context: RDEPUBReaderContext
+startInitialLoadIfNeeded()
-loadPublication()
-applyParsedPublication()
}
class RDEPUBReaderSearchCoordinator {
-context: RDEPUBReaderContext
+search(keyword:)
+goToNextMatch()
+goToPreviousMatch()
+clearSearch()
}
class RDEPUBReaderAnnotationCoordinator {
-context: RDEPUBReaderContext
+addHighlight(from:)
+removeHighlight(id:)
+toggleBookmark(at:)
+handleSelectionMenuAction(_:)
}
class RDEPUBChapterLoader {
-context: RDEPUBReaderContext
+loadChapter(spineIndex:store:) async throws RDEPUBRuntimeChapter
@ -496,6 +526,9 @@ classDiagram
RDEPUBReaderRuntime --> RDEPUBChapterLoader : owns
RDEPUBReaderRuntime --> RDEPUBChapterRuntimeStore : owns
RDEPUBReaderRuntime --> RDEPUBChapterSummaryDiskCache : owns
RDEPUBReaderRuntime --> RDEPUBReaderLoadCoordinator : owns
RDEPUBReaderRuntime --> RDEPUBReaderSearchCoordinator : owns
RDEPUBReaderRuntime --> RDEPUBReaderAnnotationCoordinator : owns
RDEPUBReaderPaginationCoordinator --> RDEPUBReaderContext : uses
RDEPUBChapterLoader --> RDEPUBReaderContext : uses
RDEPUBChapterLoader --> RDEPUBChapterRuntimeStore : uses
@ -566,9 +599,13 @@ classDiagram
class RDEPUBAnnotation {
+id: String
+bookIdentifier: String?
+kind: RDEPUBAnnotationKind
+location: RDEPUBLocation
+text: String?
+rangeInfo: String?
+chapterTitle: String?
+createdAt: Date
+bookmark: RDEPUBBookmark?
+highlight: RDEPUBHighlight?
}

View File

@ -1,6 +1,6 @@
# ReadViewSDK 文档索引
> 最后更新2026-06-04
> 最后更新2026-06-09
---
@ -12,6 +12,15 @@
| [UML_CLASS_DIAGRAMS.md](UML_CLASS_DIAGRAMS.md) | UML 类图Mermaid 格式):模块关系、核心类图、并发模型、缓存键设计 |
| [BUSINESS_LOGIC.md](BUSINESS_LOGIC.md) | 业务逻辑详解EPUB 解析、文本渲染管线、后台解析优化、翻页容器、标注系统、搜索、设置 |
## 工程规范与风险
| 文档 | 说明 |
|------|------|
| [CONCERNS.md](CONCERNS.md) | 代码库风险与关注点12 项安全/性能/可维护性风险 |
| [TESTING.md](TESTING.md) | 测试基础设施UI 测试文件清单、运行方式、覆盖率 |
| [CONVENTIONS.md](CONVENTIONS.md) | 编码规范:命名约定、代码风格、导入规范、错误处理 |
| [ARCHITECTURE-CONTEXT.md](ARCHITECTURE-CONTEXT.md) | WXRead vs ReadViewSDK 架构差距分析4 个领域、14 项决策 |
## 专题文档
| 文档 | 说明 |
@ -21,7 +30,7 @@
## 项目信息
- **模块总数:** 4 个EPUBCore、EPUBTextRendering、RDReaderView、EPUBUI
- **Swift 文件数:** 138 个
- **测试用例数:** 18 个测试类66 个测试方法
- **Swift 文件数:** 139 个SDK Sources
- **测试用例数:** 23 个测试类,约 99 个测试方法UI 测试)
- **最低 iOS 版本:** 15.6
- **构建方式:** CocoaPods本地 pod

View File

@ -26,6 +26,7 @@ struct DemoReaderState {
var display: String? { fields["display"] }
var toolbar: String? { fields["toolbar"] }
var highlights: Int? { fields["highlights"].flatMap(Int.init) }
var bookmarks: Int? { fields["bookmarks"].flatMap(Int.init) }
var selection: Int? { fields["selection"].flatMap(Int.init) }
var href: String? { fields["href"] }
var progression: Double? { fields["progression"].flatMap(Double.init) }

View File

@ -56,23 +56,30 @@ final class BookmarkTests: XCTestCase {
}
func testBookmarksPanelIsAccessible() {
app.launchAndOpenSampleBook()
//
app.launchAndOpenSampleBook(resetsReaderState: false)
app.waitForReader()
app.showReaderChromeIfNeeded()
let bookmarkButton = app.buttons[IDs.readerBookmark]
XCTAssertTrue(bookmarkButton.waitForExistence(timeout: 5), "书签按钮未出现")
bookmarkButton.tap()
//
let state = app.currentDemoReaderState()
if state?.bookmarks == 0 || state?.bookmarks == nil {
let bookmarkButton = app.buttons[IDs.readerBookmark]
if bookmarkButton.waitForExistence(timeout: 5) {
bookmarkButton.tap()
RunLoop.current.run(until: Date().addingTimeInterval(1.5))
}
}
app.showReaderChromeIfNeeded()
let bookmarksListButton = app.buttons[IDs.readerBookmarks]
XCTAssertTrue(bookmarksListButton.waitForExistence(timeout: 5), "书签列表按钮未出现")
//
let enabledPredicate = NSPredicate(format: "isEnabled == true")
expectation(for: enabledPredicate, evaluatedWith: bookmarksListButton)
waitForExpectations(timeout: 10)
XCTAssertTrue(bookmarksListButton.isEnabled, "书签列表按钮未启用")
bookmarksListButton.tap()
let bookmarksPanel = app.tables[IDs.readerBookmarksTable]

View File

@ -18,8 +18,8 @@ final class ReaderAnnotationTests: XCTestCase {
app.waitForReaderState(containing: "toolbar=hidden", timeout: 5)
let start = content.coordinate(withNormalizedOffset: CGVector(dx: 0.35, dy: 0.45))
let end = content.coordinate(withNormalizedOffset: CGVector(dx: 0.68, dy: 0.45))
let start = content.coordinate(withNormalizedOffset: CGVector(dx: 0.2, dy: 0.5))
let end = content.coordinate(withNormalizedOffset: CGVector(dx: 0.8, dy: 0.5))
start.press(forDuration: 0.8, thenDragTo: end)
app.waitForReaderState(containing: "selection=1", timeout: 5)
@ -48,8 +48,8 @@ final class ReaderAnnotationTests: XCTestCase {
app.waitForReaderState(containing: "toolbar=hidden", timeout: 5)
let start = content.coordinate(withNormalizedOffset: CGVector(dx: 0.35, dy: 0.45))
let end = content.coordinate(withNormalizedOffset: CGVector(dx: 0.68, dy: 0.45))
let start = content.coordinate(withNormalizedOffset: CGVector(dx: 0.2, dy: 0.5))
let end = content.coordinate(withNormalizedOffset: CGVector(dx: 0.8, dy: 0.5))
start.press(forDuration: 0.8, thenDragTo: end)
app.waitForReaderState(containing: "selection=1", timeout: 8)

View File

@ -67,6 +67,7 @@ final class SearchTests: XCTestCase {
func testSearchFindsMatchesAndShowsCount() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10), "匹配计数标签应出现")
@ -83,6 +84,7 @@ final class SearchTests: XCTestCase {
func testSearchNavigatesToFirstMatch() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10), "匹配计数应出现")
@ -94,6 +96,7 @@ final class SearchTests: XCTestCase {
func testSearchNextButtonAdvancesMatch() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10))
@ -109,6 +112,7 @@ final class SearchTests: XCTestCase {
func testSearchPreviousButtonGoesBack() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10))
@ -129,6 +133,7 @@ final class SearchTests: XCTestCase {
func testSearchNextWrapsAround() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10))
@ -158,6 +163,7 @@ final class SearchTests: XCTestCase {
func testSearchWithNoResultsShowsZeroCount() {
app.launchAndOpenSampleBook(searchKeyword: "xyzzy_nonexistent_keyword_12345")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10), "计数标签应出现")
@ -167,6 +173,7 @@ final class SearchTests: XCTestCase {
func testSearchNavigationDisabledWhenNoResults() {
app.launchAndOpenSampleBook(searchKeyword: "xyzzy_nonexistent_keyword_12345")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10))
@ -185,6 +192,7 @@ final class SearchTests: XCTestCase {
func testCloseSearchClearsState() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let countLabel = app.staticTexts[IDs.searchCount]
XCTAssertTrue(countLabel.waitForExistence(timeout: 10))
@ -206,6 +214,7 @@ final class SearchTests: XCTestCase {
func testSearchBarHidesWhenToolbarsHide() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let searchBar = app.otherElements[IDs.searchBar]
XCTAssertTrue(searchBar.waitForExistence(timeout: 10), "搜索栏应可见")
@ -219,6 +228,7 @@ final class SearchTests: XCTestCase {
func testSearchBarRestoresWhenToolbarsShow() {
app.launchAndOpenSampleBook(searchKeyword: "")
app.waitForReader()
app.showReaderChromeIfNeeded()
let searchBar = app.otherElements[IDs.searchBar]
XCTAssertTrue(searchBar.waitForExistence(timeout: 10))

View File

@ -37,9 +37,9 @@ public struct RDEPUBSelection: Codable, Equatable {
self.createdAt = createdAt
}
///
///
public var isEmpty: Bool {
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || rangeInfo?.isEmpty != false
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}

View File

@ -81,4 +81,51 @@ final class RDEPUBTextSearchEngine: RDEPUBSearchEngine {
let range = NSRange(location: start, length: max(end - start, 0))
return text.substring(with: range).trimmingCharacters(in: .whitespacesAndNewlines)
}
/// publication txt
static func searchWithoutPublication(textBook: RDEPUBTextBook, keyword: String) -> [RDEPUBSearchMatch] {
let normalizedKeyword = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalizedKeyword.isEmpty else { return [] }
var matches: [RDEPUBSearchMatch] = []
for chapter in textBook.chapters {
let source = chapter.attributedContent.string as NSString
let fullLength = source.length
guard fullLength > 0 else { continue }
var localMatchIndex = 0
var searchRange = NSRange(location: 0, length: fullLength)
while searchRange.length > 0 {
let foundRange = source.range(of: normalizedKeyword, options: [.caseInsensitive], range: searchRange)
guard foundRange.location != NSNotFound else { break }
let progressionDenominator = max(fullLength - 1, 1)
let progression = Double(foundRange.location) / Double(progressionDenominator)
let previewRadius = 12
let previewStart = max(foundRange.location - previewRadius, 0)
let previewEnd = min(foundRange.location + foundRange.length + previewRadius, fullLength)
let previewRange = NSRange(location: previewStart, length: max(previewEnd - previewStart, 0))
let previewText = source.substring(with: previewRange).trimmingCharacters(in: .whitespacesAndNewlines)
matches.append(
RDEPUBSearchMatch(
href: chapter.href,
progression: progression,
previewText: previewText,
localMatchIndex: localMatchIndex,
rangeLocation: foundRange.location,
rangeLength: foundRange.length,
rangeAnchor: nil
)
)
localMatchIndex += 1
let nextLocation = foundRange.location + max(foundRange.length, 1)
if nextLocation >= fullLength { break }
searchRange = NSRange(location: nextLocation, length: fullLength - nextLocation)
}
}
return matches
}
}

View File

@ -202,7 +202,6 @@ extension RDEPUBReaderController: RDEPUBTextContentViewDelegate {
}
guard let textBook,
let publication,
let page = textBook.page(at: pageNumber) else {
return nil
}
@ -211,11 +210,14 @@ extension RDEPUBReaderController: RDEPUBTextContentViewDelegate {
?? textBook.location(forPageNumber: pageNumber, bookIdentifier: currentBookIdentifier)
guard let location else { return nil }
return publication.resourceResolver.normalizedLocation(
location,
relativeToSpineIndex: nil,
bookIdentifier: currentBookIdentifier
) ?? location
if let publication {
return publication.resourceResolver.normalizedLocation(
location,
relativeToSpineIndex: nil,
bookIdentifier: currentBookIdentifier
) ?? location
}
return location
}
/// spine

View File

@ -310,27 +310,13 @@ public final class RDEPUBReaderController: UIViewController {
// MARK: -
/// readerView
///
/// `handleToolViewVisibilityChanged`
func showSearchBar() {
guard !isSearchBarVisible else { return }
isSearchBarVisible = true
searchBarView.apply(theme: configuration.theme)
readerView.addSubview(searchBarView)
readerView.searchBarView = searchBarView
let topToolbarHeight: CGFloat = readerView.safeAreaInsets.top + 52
NSLayoutConstraint.activate([
searchBarView.leadingAnchor.constraint(equalTo: readerView.leadingAnchor),
searchBarView.trailingAnchor.constraint(equalTo: readerView.trailingAnchor),
searchBarView.topAnchor.constraint(equalTo: readerView.topAnchor, constant: topToolbarHeight),
searchBarView.heightAnchor.constraint(equalToConstant: 52)
])
searchBarView.transform = CGAffineTransform(translationX: 0, y: -52)
UIView.animate(withDuration: 0.3) {
self.searchBarView.transform = .identity
}
searchBarView.onSearchSubmit = { [weak self] keyword in
self?.runtime.search(keyword: keyword)
self?.updateSearchCount()
@ -347,12 +333,36 @@ public final class RDEPUBReaderController: UIViewController {
self?.hideSearchBar(clearSearch: true)
}
if readerView.isShowToolView {
installSearchBarView()
}
}
/// readerView
private func installSearchBarView() {
guard searchBarView.superview == nil else { return }
searchBarView.apply(theme: configuration.theme)
readerView.addSubview(searchBarView)
readerView.searchBarView = searchBarView
let topToolbarHeight: CGFloat = readerView.safeAreaInsets.top + 52
NSLayoutConstraint.activate([
searchBarView.leadingAnchor.constraint(equalTo: readerView.leadingAnchor),
searchBarView.trailingAnchor.constraint(equalTo: readerView.trailingAnchor),
searchBarView.topAnchor.constraint(equalTo: readerView.topAnchor, constant: topToolbarHeight),
searchBarView.heightAnchor.constraint(equalToConstant: 52)
])
searchBarView.transform = CGAffineTransform(translationX: 0, y: -52)
UIView.animate(withDuration: 0.3) {
self.searchBarView.transform = .identity
}
if let keyword = searchState?.keyword, !keyword.isEmpty {
searchBarView.restoreKeyword(keyword)
updateSearchCount()
}
//
DispatchQueue.main.async { [weak self] in
self?.searchBarView.textField.becomeFirstResponder()
}
@ -379,7 +389,7 @@ public final class RDEPUBReaderController: UIViewController {
}
///
private func updateSearchCount() {
func updateSearchCount() {
guard let searchState else {
searchBarView.showNoResults()
return
@ -394,7 +404,9 @@ public final class RDEPUBReaderController: UIViewController {
/// RDReaderView
func handleToolViewVisibilityChanged(isVisible: Bool) {
if isVisible {
if searchState != nil && !isSearchBarVisible {
if isSearchBarVisible {
installSearchBarView()
} else if searchState != nil {
showSearchBar()
}
} else {

View File

@ -53,6 +53,7 @@ public final class RDURLReaderController: UIViewController {
private let pendingDemoPageRetryDelay: TimeInterval = 0.25
private var demoStateTimer: Timer?
private var lastEmittedDemoState = ""
private var pendingSearchKeyword: String?
///
/// - Parameters:
@ -147,18 +148,41 @@ public final class RDURLReaderController: UIViewController {
}
/// Demo
///
/// `didUpdateLocation`
/// - Parameter keyword:
public func performDemoSearch(keyword: String) {
guard let readerController else { return }
readerController.showSearchBar()
//
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
if readerController.parser != nil || readerController.textBook != nil {
submitSearchAfterDelay(keyword: keyword, retries: 5)
} else {
pendingSearchKeyword = keyword
}
}
private func submitSearchAfterDelay(keyword: String, retries: Int = 0) {
guard let readerController else { return }
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
guard let self else { return }
readerController.search(keyword: keyword)
readerController.updateSearchCount()
if retries > 0,
readerController.searchState?.matches.isEmpty != false,
readerController.parser == nil {
self.submitSearchAfterDelay(keyword: keyword, retries: retries - 1)
}
}
}
private func executePendingSearchIfNeeded() {
guard let keyword = pendingSearchKeyword else { return }
guard let readerController, readerController.parser != nil || readerController.textBook != nil else {
return
}
pendingSearchKeyword = nil
submitSearchAfterDelay(keyword: keyword, retries: 5)
}
///
/// Child View Controller
private func embedReaderController() {
@ -339,6 +363,7 @@ public final class RDURLReaderController: UIViewController {
let display = readerController?.configuration.displayType.demoArgumentValue ?? epubConfiguration.displayType.demoArgumentValue
let toolbar = readerController?.readerView.isShowToolView == true ? "visible" : "hidden"
let highlights = readerController?.highlights.count ?? 0
let bookmarks = readerController?.activeBookmarks.count ?? 0
let selection = readerController?.currentSelection == nil ? 0 : 1
let location = readerController?.currentLocation
let href = encodedDemoLocationHref(location?.href)
@ -351,6 +376,7 @@ public final class RDURLReaderController: UIViewController {
"display=\(display)",
"toolbar=\(toolbar)",
"highlights=\(highlights)",
"bookmarks=\(bookmarks)",
"selection=\(selection)",
"href=\(href)",
"progression=\(progression)",
@ -439,11 +465,13 @@ public final class RDURLReaderController: UIViewController {
extension RDURLReaderController: RDEPUBReaderDelegate {
public func epubReader(_ reader: UIViewController, didOpen publication: RDEPUBPublication) {
retryPendingDemoPageIfNeeded()
executePendingSearchIfNeeded()
emitDemoState()
}
public func epubReader(_ reader: UIViewController, didUpdateLocation location: RDEPUBLocation) {
retryPendingDemoPageIfNeeded()
executePendingSearchIfNeeded()
emitDemoState()
}
@ -454,6 +482,10 @@ extension RDURLReaderController: RDEPUBReaderDelegate {
public func epubReader(_ reader: UIViewController, didUpdateHighlights highlights: [RDEPUBHighlight]) {
emitDemoState(prefix: "highlights=\(highlights.count)")
}
public func epubReader(_ reader: UIViewController, didUpdateBookmarks bookmarks: [RDEPUBBookmark]) {
emitDemoState(prefix: "bookmarks=\(bookmarks.count)")
}
}
/// Demo

View File

@ -53,8 +53,20 @@ final class RDEPUBReaderLocationCoordinator {
let readerView = context.readerView else {
return nil
}
let pageNumber = readerView.currentPage + 1
if (context.textBook != nil || context.bookPageMap != nil), readerView.currentPage >= 0 {
return controller.resolvedTextLocation(forPageNumber: readerView.currentPage + 1)
if let location = controller.resolvedTextLocation(forPageNumber: pageNumber) {
return location
}
// resolvedTextLocation nil
// readingSession activePages 退
if let readingSession = context.readingSession,
readingSession.activePages.indices.contains(readerView.currentPage) {
return readingSession.fallbackLocation(
for: readingSession.activePages[readerView.currentPage],
bookIdentifier: context.currentBookIdentifier
)
}
}
return context.readingSession?.currentReadingLocation(bookIdentifier: context.currentBookIdentifier)
}

View File

@ -103,8 +103,11 @@ final class RDEPUBReaderSearchCoordinator {
private func resolvedSearchMatches(for keyword: String) -> [RDEPUBSearchMatch] {
guard let controller else { return [] }
if let textBook = controller.textBook, let publication = controller.publication {
return RDEPUBTextSearchEngine(textBook: textBook, publication: publication).search(keyword: keyword)
if let textBook = controller.textBook {
if let publication = controller.publication {
return RDEPUBTextSearchEngine(textBook: textBook, publication: publication).search(keyword: keyword)
}
return RDEPUBTextSearchEngine.searchWithoutPublication(textBook: textBook, keyword: keyword)
}
if let parser = controller.parser, let publication = controller.publication {
return RDEPUBHTMLSearchEngine(parser: parser, publication: publication).search(keyword: keyword)

View File

@ -489,6 +489,7 @@ final class RDEPUBTextContentView: UIView, UIGestureRecognizerDelegate {
@objc private func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
#if canImport(DTCoreText)
layoutIfNeeded()
selectionController.handleLongPress(
gesture,
renderView: coreTextRenderView,

View File

@ -60,10 +60,8 @@ final class RDEPUBTextSelectionController: NSObject {
switch gesture.state {
case .began, .changed:
updateSelection(at: point, renderView: renderView, interactionController: interactionController)
case .ended:
case .ended, .cancelled, .failed:
isSelecting = false
case .cancelled, .failed:
clearSelection(renderView: renderView)
default:
break
}
@ -89,7 +87,9 @@ final class RDEPUBTextSelectionController: NSObject {
interactionController: RDEPUBPageInteractionController
) {
guard let index = interactionController.characterIndexForViewPoint(at: point, in: renderView) else {
clearSelection(renderView: renderView)
if !isSelecting {
clearSelection(renderView: renderView)
}
return
}
selectionStartIndex = index

View File

@ -4,7 +4,7 @@ set -u
set -o pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PROJECT_PATH="${PROJECT_PATH:-$ROOT_DIR/ReadViewDemo/ReadViewDemo.xcodeproj}"
PROJECT_PATH="${PROJECT_PATH:-$ROOT_DIR/ReadViewDemo/ReadViewDemo.xcworkspace}"
SCHEME_NAME="${SCHEME_NAME:-ReadViewDemo}"
CONFIGURATION="${CONFIGURATION:-Debug}"
SIMULATOR_NAME="${SIMULATOR_NAME:-iPhone 16 Plus}"
@ -111,10 +111,16 @@ echo " destination: $DESTINATION"
echo " test type: $TEST_TYPE"
echo " results: $RUN_DIR"
if [[ "$PROJECT_PATH" == *.xcworkspace ]]; then
PROJECT_FLAG="-workspace"
else
PROJECT_FLAG="-project"
fi
XCODEBUILD_ARGS=(
xcodebuild
test
-project "$PROJECT_PATH"
"$PROJECT_FLAG" "$PROJECT_PATH"
-scheme "$SCHEME_NAME"
-configuration "$CONFIGURATION"
-destination "$DESTINATION"